]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c
968049afa72e0cae5f2f39d56154a2faa6c2c699
[Ventoy.git] / EDK2 / edk2_mod / edk2-edk2-stable201911 / MdeModulePkg / Application / Ventoy / Ventoy.c
1 /******************************************************************************
2 * Ventoy.c
3 *
4 * Copyright (c) 2020, longpanda <admin@ventoy.net>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 #include <Uefi.h>
22 #include <Library/DebugLib.h>
23 #include <Library/PrintLib.h>
24 #include <Library/UefiLib.h>
25 #include <Library/BaseMemoryLib.h>
26 #include <Library/DevicePathLib.h>
27 #include <Library/MemoryAllocationLib.h>
28 #include <Library/UefiBootServicesTableLib.h>
29 #include <Library/UefiRuntimeServicesTableLib.h>
30 #include <Library/UefiApplicationEntryPoint.h>
31 #include <Protocol/LoadedImage.h>
32 #include <Guid/FileInfo.h>
33 #include <Guid/FileSystemInfo.h>
34 #include <Protocol/BlockIo.h>
35 #include <Protocol/RamDisk.h>
36 #include <Protocol/SimpleFileSystem.h>
37 #include <Ventoy.h>
38
39 BOOLEAN gDebugPrint = FALSE;
40 ventoy_ram_disk g_ramdisk_param;
41 ventoy_chain_head *g_chain;
42 ventoy_img_chunk *g_chunk;
43 UINT8 *g_os_param_reserved;
44 UINT32 g_img_chunk_num;
45 ventoy_override_chunk *g_override_chunk;
46 UINT32 g_override_chunk_num;
47 ventoy_virt_chunk *g_virt_chunk;
48 UINT32 g_virt_chunk_num;
49 vtoy_block_data gBlockData;
50 static grub_env_get_pf grub_env_get = NULL;
51
52 ventoy_grub_param_file_replace *g_file_replace_list = NULL;
53 ventoy_efi_file_replace g_efi_file_replace;
54
55 BOOLEAN g_fix_windows_1st_cdrom_issue = FALSE;
56
57 STATIC BOOLEAN g_hook_keyboard = FALSE;
58
59 CHAR16 gFirstTryBootFile[256] = {0};
60
61 /* Boot filename */
62 UINTN gBootFileStartIndex = 1;
63 CONST CHAR16 *gEfiBootFileName[] =
64 {
65 L"@",
66 EFI_REMOVABLE_MEDIA_FILE_NAME,
67 L"\\EFI\\BOOT\\GRUBX64.EFI",
68 L"\\EFI\\BOOT\\BOOTx64.EFI",
69 L"\\EFI\\BOOT\\bootx64.efi",
70 L"\\efi\\boot\\bootx64.efi",
71 };
72
73 VOID EFIAPI VtoyDebug(IN CONST CHAR8 *Format, ...)
74 {
75 VA_LIST Marker;
76 CHAR16 Buffer[512];
77
78 VA_START (Marker, Format);
79 UnicodeVSPrintAsciiFormat(Buffer, sizeof(Buffer), Format, Marker);
80 VA_END (Marker);
81
82 gST->ConOut->OutputString(gST->ConOut, Buffer);
83 }
84
85 VOID EFIAPI ventoy_clear_input(VOID)
86 {
87 EFI_INPUT_KEY Key;
88
89 gST->ConIn->Reset(gST->ConIn, FALSE);
90 while (EFI_SUCCESS == gST->ConIn->ReadKeyStroke(gST->ConIn, &Key))
91 {
92 ;
93 }
94 gST->ConIn->Reset(gST->ConIn, FALSE);
95 }
96
97 static void EFIAPI ventoy_dump_img_chunk(ventoy_chain_head *chain)
98 {
99 UINT32 i;
100 int errcnt = 0;
101 UINT64 img_sec = 0;
102 ventoy_img_chunk *chunk;
103
104 chunk = (ventoy_img_chunk *)((char *)chain + chain->img_chunk_offset);
105
106 debug("##################### ventoy_dump_img_chunk #######################");
107
108 for (i = 0; i < chain->img_chunk_num; i++)
109 {
110 debug("%2u: [ %u - %u ] <==> [ %llu - %llu ]",
111 i, chunk[i].img_start_sector, chunk[i].img_end_sector,
112 chunk[i].disk_start_sector, chunk[i].disk_end_sector);
113
114 if (i > 0 && (chunk[i].img_start_sector != chunk[i - 1].img_end_sector + 1))
115 {
116 errcnt++;
117 }
118
119 img_sec += chunk[i].img_end_sector - chunk[i].img_start_sector + 1;
120 }
121
122 if (errcnt == 0 && (img_sec * 2048 == g_chain->real_img_size_in_bytes))
123 {
124 debug("image chunk size check success");
125 }
126 else
127 {
128 debug("image chunk size check failed %d", errcnt);
129 }
130
131 ventoy_debug_pause();
132 }
133
134 static void EFIAPI ventoy_dump_override_chunk(ventoy_chain_head *chain)
135 {
136 UINT32 i;
137 ventoy_override_chunk *chunk;
138
139 chunk = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset);
140
141 debug("##################### ventoy_dump_override_chunk #######################");
142
143 for (i = 0; i < g_override_chunk_num; i++)
144 {
145 debug("%2u: [ %llu, %u ]", i, chunk[i].img_offset, chunk[i].override_size);
146 }
147
148 ventoy_debug_pause();
149 }
150
151 static void EFIAPI ventoy_dump_virt_chunk(ventoy_chain_head *chain)
152 {
153 UINT32 i;
154 ventoy_virt_chunk *node;
155
156 debug("##################### ventoy_dump_virt_chunk #######################");
157 debug("virt_chunk_offset=%u", chain->virt_chunk_offset);
158 debug("virt_chunk_num=%u", chain->virt_chunk_num);
159
160 node = (ventoy_virt_chunk *)((char *)chain + chain->virt_chunk_offset);
161 for (i = 0; i < chain->virt_chunk_num; i++, node++)
162 {
163 debug("%2u: mem:[ %u, %u, %u ] remap:[ %u, %u, %u ]", i,
164 node->mem_sector_start,
165 node->mem_sector_end,
166 node->mem_sector_offset,
167 node->remap_sector_start,
168 node->remap_sector_end,
169 node->org_sector_start);
170 }
171
172 ventoy_debug_pause();
173 }
174
175 static void EFIAPI ventoy_dump_chain(ventoy_chain_head *chain)
176 {
177 UINT32 i = 0;
178 UINT8 chksum = 0;
179 UINT8 *guid;
180
181 guid = chain->os_param.vtoy_disk_guid;
182 for (i = 0; i < sizeof(ventoy_os_param); i++)
183 {
184 chksum += *((UINT8 *)(&(chain->os_param)) + i);
185 }
186
187 debug("##################### ventoy_dump_chain #######################");
188
189 debug("os_param->chksum=0x%x (%a)", chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
190 debug("os_param->vtoy_disk_guid=%02x%02x%02x%02x", guid[0], guid[1], guid[2], guid[3]);
191 debug("os_param->vtoy_disk_size=%llu", chain->os_param.vtoy_disk_size);
192 debug("os_param->vtoy_disk_part_id=%u", chain->os_param.vtoy_disk_part_id);
193 debug("os_param->vtoy_disk_part_type=%u", chain->os_param.vtoy_disk_part_type);
194 debug("os_param->vtoy_img_path=<%a>", chain->os_param.vtoy_img_path);
195 debug("os_param->vtoy_img_size=<%llu>", chain->os_param.vtoy_img_size);
196 debug("os_param->vtoy_img_location_addr=<0x%llx>", chain->os_param.vtoy_img_location_addr);
197 debug("os_param->vtoy_img_location_len=<%u>", chain->os_param.vtoy_img_location_len);
198 debug("os_param->vtoy_reserved=<%u %u %u %u %u>",
199 g_os_param_reserved[0],
200 g_os_param_reserved[1],
201 g_os_param_reserved[2],
202 g_os_param_reserved[3],
203 g_os_param_reserved[4]
204 );
205
206 ventoy_debug_pause();
207
208 debug("chain->disk_drive=0x%x", chain->disk_drive);
209 debug("chain->disk_sector_size=%u", chain->disk_sector_size);
210 debug("chain->real_img_size_in_bytes=%llu", chain->real_img_size_in_bytes);
211 debug("chain->virt_img_size_in_bytes=%llu", chain->virt_img_size_in_bytes);
212 debug("chain->boot_catalog=%u", chain->boot_catalog);
213 debug("chain->img_chunk_offset=%u", chain->img_chunk_offset);
214 debug("chain->img_chunk_num=%u", chain->img_chunk_num);
215 debug("chain->override_chunk_offset=%u", chain->override_chunk_offset);
216 debug("chain->override_chunk_num=%u", chain->override_chunk_num);
217
218 ventoy_debug_pause();
219
220 ventoy_dump_img_chunk(chain);
221 ventoy_dump_override_chunk(chain);
222 ventoy_dump_virt_chunk(chain);
223 }
224
225 static int ventoy_update_image_location(ventoy_os_param *param)
226 {
227 EFI_STATUS Status = EFI_SUCCESS;
228 UINT8 chksum = 0;
229 unsigned int i;
230 unsigned int length;
231 UINTN address = 0;
232 void *buffer = NULL;
233 ventoy_image_location *location = NULL;
234 ventoy_image_disk_region *region = NULL;
235 ventoy_img_chunk *chunk = g_chunk;
236
237 length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region);
238
239 Status = gBS->AllocatePool(EfiRuntimeServicesData, length + 4096 * 2, &buffer);
240 if (EFI_ERROR(Status) || NULL == buffer)
241 {
242 debug("Failed to allocate runtime pool %r\n", Status);
243 return 1;
244 }
245
246 address = (UINTN)buffer;
247
248 if (address % 4096)
249 {
250 address += 4096 - (address % 4096);
251 }
252
253 param->chksum = 0;
254 param->vtoy_img_location_addr = address;
255 param->vtoy_img_location_len = length;
256
257 /* update check sum */
258 for (i = 0; i < sizeof(ventoy_os_param); i++)
259 {
260 chksum += *((UINT8 *)param + i);
261 }
262 param->chksum = (chksum == 0) ? 0 : (UINT8)(0x100 - chksum);
263
264 location = (ventoy_image_location *)(unsigned long)(param->vtoy_img_location_addr);
265 if (NULL == location)
266 {
267 return 0;
268 }
269
270 CopyMem(&location->guid, &param->guid, sizeof(ventoy_guid));
271 location->image_sector_size = 2048;
272 location->disk_sector_size = g_chain->disk_sector_size;
273 location->region_count = g_img_chunk_num;
274
275 region = location->regions;
276
277 for (i = 0; i < g_img_chunk_num; i++)
278 {
279 region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1;
280 region->image_start_sector = chunk->img_start_sector;
281 region->disk_start_sector = chunk->disk_start_sector;
282 region++;
283 chunk++;
284 }
285
286 return 0;
287 }
288
289 EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath)
290 {
291 EFI_HANDLE Handle = NULL;
292 EFI_STATUS Status = EFI_SUCCESS;
293 EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL;
294 EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL;
295 EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL;
296
297 pTmpDevPath = DuplicateDevicePath(pDevPath);
298 if (!pTmpDevPath)
299 {
300 return NULL;
301 }
302
303 pCurNode = pTmpDevPath;
304 while (!IsDevicePathEnd(pCurNode))
305 {
306 pLastNode = pCurNode;
307 pCurNode = NextDevicePathNode(pCurNode);
308 }
309 if (pLastNode)
310 {
311 CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL));
312 }
313
314 pCurNode = pTmpDevPath;
315 Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle);
316 debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE));
317
318 FreePool(pTmpDevPath);
319
320 return Handle;
321 }
322
323 EFI_STATUS EFIAPI ventoy_save_ramdisk_param(VOID)
324 {
325 EFI_STATUS Status = EFI_SUCCESS;
326 EFI_GUID VarGuid = VENTOY_GUID;
327
328 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
329 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
330 sizeof(g_ramdisk_param), &(g_ramdisk_param));
331 debug("set efi variable %r", Status);
332
333 return Status;
334 }
335
336 EFI_STATUS EFIAPI ventoy_delete_ramdisk_param(VOID)
337 {
338 EFI_STATUS Status = EFI_SUCCESS;
339 EFI_GUID VarGuid = VENTOY_GUID;
340
341 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
342 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
343 0, NULL);
344 debug("delete efi variable %r", Status);
345
346 return Status;
347 }
348
349
350 EFI_STATUS EFIAPI ventoy_save_variable(VOID)
351 {
352 EFI_STATUS Status = EFI_SUCCESS;
353 EFI_GUID VarGuid = VENTOY_GUID;
354
355 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
356 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
357 sizeof(g_chain->os_param), &(g_chain->os_param));
358 debug("set efi variable %r", Status);
359
360 return Status;
361 }
362
363 EFI_STATUS EFIAPI ventoy_delete_variable(VOID)
364 {
365 EFI_STATUS Status = EFI_SUCCESS;
366 EFI_GUID VarGuid = VENTOY_GUID;
367
368 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
369 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
370 0, NULL);
371 debug("delete efi variable %r", Status);
372
373 return Status;
374 }
375
376 STATIC EFI_STATUS EFIAPI ventoy_load_image
377 (
378 IN EFI_HANDLE ImageHandle,
379 IN EFI_DEVICE_PATH_PROTOCOL *pDevicePath,
380 IN CONST CHAR16 *FileName,
381 IN UINTN FileNameLen,
382 OUT EFI_HANDLE *Image
383 )
384 {
385 EFI_STATUS Status = EFI_SUCCESS;
386 CHAR16 TmpBuf[256] = {0};
387 FILEPATH_DEVICE_PATH *pFilePath = NULL;
388 EFI_DEVICE_PATH_PROTOCOL *pImgPath = NULL;
389
390 pFilePath = (FILEPATH_DEVICE_PATH *)TmpBuf;
391 pFilePath->Header.Type = MEDIA_DEVICE_PATH;
392 pFilePath->Header.SubType = MEDIA_FILEPATH_DP;
393 pFilePath->Header.Length[0] = FileNameLen + sizeof(EFI_DEVICE_PATH_PROTOCOL);
394 pFilePath->Header.Length[1] = 0;
395 CopyMem(pFilePath->PathName, FileName, FileNameLen);
396
397 pImgPath = AppendDevicePathNode(pDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)pFilePath);
398 if (!pImgPath)
399 {
400 return EFI_NOT_FOUND;
401 }
402
403 Status = gBS->LoadImage(FALSE, ImageHandle, pImgPath, NULL, 0, Image);
404
405 debug("Load Image File %r DP: <%s>", Status, ConvertDevicePathToText(pImgPath, FALSE, FALSE));
406
407 FreePool(pImgPath);
408
409 return Status;
410 }
411
412
413 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
414 {
415 UINTN i = 0;
416 UINTN Count = 0;
417 UINT64 DiskSize = 0;
418 UINT8 *pBuffer = NULL;
419 EFI_HANDLE *Handles;
420 EFI_STATUS Status = EFI_SUCCESS;
421 EFI_BLOCK_IO_PROTOCOL *pBlockIo;
422
423 pBuffer = AllocatePool(2048);
424 if (!pBuffer)
425 {
426 return EFI_OUT_OF_RESOURCES;
427 }
428
429 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiBlockIoProtocolGuid,
430 NULL, &Count, &Handles);
431 if (EFI_ERROR(Status))
432 {
433 FreePool(pBuffer);
434 return Status;
435 }
436
437 for (i = 0; i < Count; i++)
438 {
439 Status = gBS->HandleProtocol(Handles[i], &gEfiBlockIoProtocolGuid, (VOID **)&pBlockIo);
440 if (EFI_ERROR(Status))
441 {
442 continue;
443 }
444
445 DiskSize = (pBlockIo->Media->LastBlock + 1) * pBlockIo->Media->BlockSize;
446 debug("This Disk size: %llu", DiskSize);
447 if (g_chain->os_param.vtoy_disk_size != DiskSize)
448 {
449 continue;
450 }
451
452 Status = pBlockIo->ReadBlocks(pBlockIo, pBlockIo->Media->MediaId, 0, 512, pBuffer);
453 if (EFI_ERROR(Status))
454 {
455 debug("ReadBlocks filed %r", Status);
456 continue;
457 }
458
459 if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0)
460 {
461 gBlockData.RawBlockIoHandle = Handles[i];
462 gBlockData.pRawBlockIo = pBlockIo;
463 gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
464 (VOID **)&(gBlockData.pDiskDevPath),
465 ImageHandle,
466 Handles[i],
467 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
468
469 debug("Find Ventoy Disk Handle:%p DP:%s", Handles[i],
470 ConvertDevicePathToText(gBlockData.pDiskDevPath, FALSE, FALSE));
471 break;
472 }
473 }
474
475 FreePool(Handles);
476
477 if (i >= Count)
478 {
479 return EFI_NOT_FOUND;
480 }
481 else
482 {
483 return EFI_SUCCESS;
484 }
485 }
486
487 STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
488 {
489 UINT32 i = 0;
490 UINT32 old_cnt = 0;
491 UINTN size = 0;
492 UINT8 chksum = 0;
493 CHAR16 *pPos = NULL;
494 CHAR16 *pCmdLine = NULL;
495 EFI_STATUS Status = EFI_SUCCESS;
496 ventoy_grub_param *pGrubParam = NULL;
497 EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL;
498 ventoy_chain_head *chain = NULL;
499
500 Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo);
501 if (EFI_ERROR(Status))
502 {
503 VtoyDebug("Failed to handle load image protocol %r", Status);
504 return Status;
505 }
506
507 pCmdLine = (CHAR16 *)AllocatePool(pImageInfo->LoadOptionsSize + 4);
508 SetMem(pCmdLine, pImageInfo->LoadOptionsSize + 4, 0);
509 CopyMem(pCmdLine, pImageInfo->LoadOptions, pImageInfo->LoadOptionsSize);
510
511 if (StrStr(pCmdLine, L"debug"))
512 {
513 gDebugPrint = TRUE;
514 }
515
516 pPos = StrStr(pCmdLine, L"FirstTry=@");
517 if (pPos)
518 {
519 pPos += StrLen(L"FirstTry=");
520 for (i = 0; i < ARRAY_SIZE(gFirstTryBootFile); i++, pPos++)
521 {
522 if (*pPos != L' ' && *pPos != L'\t' && *pPos)
523 {
524 gFirstTryBootFile[i] = (*pPos == '@') ? '\\' : *pPos;
525 }
526 else
527 {
528 break;
529 }
530 }
531
532 gEfiBootFileName[0] = gFirstTryBootFile;
533 gBootFileStartIndex = 0;
534 }
535
536 debug("cmdline:<%s>", pCmdLine);
537
538 if (gFirstTryBootFile[0])
539 {
540 debug("First Try:<%s>", gFirstTryBootFile);
541 }
542
543 pPos = StrStr(pCmdLine, L"env_param=");
544 if (!pPos)
545 {
546 return EFI_INVALID_PARAMETER;
547 }
548
549 pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param="));
550 grub_env_get = pGrubParam->grub_env_get;
551
552 g_file_replace_list = &pGrubParam->file_replace;
553 old_cnt = g_file_replace_list->old_file_cnt;
554 debug("file replace: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
555 g_file_replace_list->magic,
556 g_file_replace_list->new_file_virtual_id,
557 old_cnt,
558 old_cnt > 0 ? g_file_replace_list->old_file_name[0] : "",
559 old_cnt > 1 ? g_file_replace_list->old_file_name[1] : "",
560 old_cnt > 2 ? g_file_replace_list->old_file_name[2] : "",
561 old_cnt > 3 ? g_file_replace_list->old_file_name[3] : ""
562 );
563
564 pPos = StrStr(pCmdLine, L"mem:");
565 chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
566
567 pPos = StrStr(pPos, L"size:");
568 size = StrDecimalToUintn(pPos + 5);
569
570 debug("memory addr:%p size:%lu", chain, size);
571
572 g_chain = AllocatePool(size);
573 CopyMem(g_chain, chain, size);
574
575 if (StrStr(pCmdLine, L"memdisk"))
576 {
577 g_iso_buf_size = size;
578 gMemdiskMode = TRUE;
579 }
580 else
581 {
582 g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset);
583 g_img_chunk_num = g_chain->img_chunk_num;
584 g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset);
585 g_override_chunk_num = g_chain->override_chunk_num;
586 g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset);
587 g_virt_chunk_num = g_chain->virt_chunk_num;
588
589 g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
590
591 /* Workaround for Windows & ISO9660 */
592 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
593 {
594 g_fixup_iso9660_secover_enable = TRUE;
595 }
596
597 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
598 {
599 g_hook_keyboard = TRUE;
600 }
601
602 debug("internal param: secover:%u keyboard:%u", g_fixup_iso9660_secover_enable, g_hook_keyboard);
603
604 for (i = 0; i < sizeof(ventoy_os_param); i++)
605 {
606 chksum += *((UINT8 *)(&(g_chain->os_param)) + i);
607 }
608
609 if (gDebugPrint)
610 {
611 debug("os param checksum: 0x%x %a", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
612 }
613
614 ventoy_update_image_location(&(g_chain->os_param));
615
616 if (gDebugPrint)
617 {
618 ventoy_dump_chain(g_chain);
619 }
620 }
621
622 g_fix_windows_1st_cdrom_issue = FALSE;
623 if (ventoy_chain_windows == g_os_param_reserved[2] ||
624 ventoy_chain_wim == g_os_param_reserved[2])
625 {
626 if (ventoy_is_cdrom_dp_exist())
627 {
628 debug("fixup the 1st cdrom influences when boot windows ...");
629 g_fix_windows_1st_cdrom_issue = TRUE;
630 }
631 }
632
633 FreePool(pCmdLine);
634 return EFI_SUCCESS;
635 }
636
637 EFI_STATUS EFIAPI ventoy_clean_env(VOID)
638 {
639 FreePool(g_sector_flag);
640 g_sector_flag_num = 0;
641
642 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
643
644 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
645 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
646 &gEfiDevicePathProtocolGuid, gBlockData.Path,
647 NULL);
648
649 ventoy_delete_variable();
650
651 if (g_chain->os_param.vtoy_img_location_addr)
652 {
653 FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr);
654 }
655
656 FreePool(g_chain);
657
658 return EFI_SUCCESS;
659 }
660
661 STATIC EFI_STATUS ventoy_hook_start(VOID)
662 {
663 /* don't add debug print in this function */
664
665 if (g_fix_windows_1st_cdrom_issue)
666 {
667 ventoy_hook_1st_cdrom_start();
668 }
669
670 /* let this the last */
671 if (g_hook_keyboard)
672 {
673 ventoy_hook_keyboard_start();
674 }
675
676 return EFI_SUCCESS;
677 }
678
679 STATIC EFI_STATUS ventoy_hook_stop(VOID)
680 {
681 /* don't add debug print in this function */
682
683 if (g_fix_windows_1st_cdrom_issue)
684 {
685 ventoy_hook_1st_cdrom_stop();
686 }
687
688 /* let this the last */
689 if (g_hook_keyboard)
690 {
691 ventoy_hook_keyboard_stop();
692 }
693
694 return EFI_SUCCESS;
695 }
696
697 EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
698 {
699 UINTN t = 0;
700 UINTN i = 0;
701 UINTN j = 0;
702 UINTN Find = 0;
703 UINTN Count = 0;
704 EFI_HANDLE Image = NULL;
705 EFI_HANDLE *Handles = NULL;
706 EFI_STATUS Status = EFI_SUCCESS;
707 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
708 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
709
710 for (t = 0; t < 3; t++)
711 {
712 Count = 0;
713 Handles = NULL;
714
715 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
716 NULL, &Count, &Handles);
717 if (EFI_ERROR(Status))
718 {
719 return Status;
720 }
721
722 debug("ventoy_boot fs count:%u", Count);
723
724 for (i = 0; i < Count; i++)
725 {
726 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
727 if (EFI_ERROR(Status))
728 {
729 continue;
730 }
731
732 debug("FS:%u Protocol:%p OpenVolume:%p", i, pFile, pFile->OpenVolume);
733
734 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
735 (VOID **)&pDevPath,
736 ImageHandle,
737 Handles[i],
738 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
739 if (EFI_ERROR(Status))
740 {
741 debug("Failed to open device path protocol %r", Status);
742 continue;
743 }
744
745 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
746 if (CompareMem(gBlockData.Path, pDevPath, gBlockData.DevicePathCompareLen))
747 {
748 debug("Not ventoy disk file system");
749 continue;
750 }
751
752 for (j = gBootFileStartIndex; j < ARRAY_SIZE(gEfiBootFileName); j++)
753 {
754 Status = ventoy_load_image(ImageHandle, pDevPath, gEfiBootFileName[j],
755 StrSize(gEfiBootFileName[j]), &Image);
756 if (EFI_SUCCESS == Status)
757 {
758 break;
759 }
760 debug("Failed to load image %r <%s>", Status, gEfiBootFileName[j]);
761 }
762
763 if (j >= ARRAY_SIZE(gEfiBootFileName))
764 {
765 continue;
766 }
767
768 Find++;
769 debug("Find boot file, now try to boot .....");
770 ventoy_debug_pause();
771
772 if (gDebugPrint)
773 {
774 gST->ConIn->Reset(gST->ConIn, FALSE);
775 }
776
777 if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC)
778 {
779 ventoy_wrapper_push_openvolume(pFile->OpenVolume);
780 pFile->OpenVolume = ventoy_wrapper_open_volume;
781 }
782
783 ventoy_hook_start();
784 /* can't add debug print here */
785 //ventoy_wrapper_system();
786 Status = gBS->StartImage(Image, NULL, NULL);
787 ventoy_hook_stop();
788
789 if (EFI_ERROR(Status))
790 {
791 debug("Failed to start image %r", Status);
792 sleep(3);
793 gBS->UnloadImage(Image);
794 break;
795 }
796 }
797
798 FreePool(Handles);
799
800 if (Find == 0)
801 {
802 debug("Fs not found, now wait and retry...");
803 sleep(2);
804 }
805 }
806
807 if (Find == 0)
808 {
809 return EFI_NOT_FOUND;
810 }
811
812 return EFI_SUCCESS;
813 }
814
815 EFI_STATUS EFIAPI VentoyEfiMain
816 (
817 IN EFI_HANDLE ImageHandle,
818 IN EFI_SYSTEM_TABLE *SystemTable
819 )
820 {
821 EFI_STATUS Status = EFI_SUCCESS;
822 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *Protocol;
823
824 g_sector_flag_num = 512; /* initial value */
825
826 g_sector_flag = AllocatePool(g_sector_flag_num * sizeof(ventoy_sector_flag));
827 if (NULL == g_sector_flag)
828 {
829 return EFI_OUT_OF_RESOURCES;
830 }
831
832 Status = gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&Protocol);
833 if (EFI_SUCCESS == Status)
834 {
835 g_con_simple_input_ex = Protocol;
836 }
837
838 gST->ConOut->ClearScreen(gST->ConOut);
839 ventoy_clear_input();
840
841 ventoy_parse_cmdline(ImageHandle);
842
843 if (gMemdiskMode)
844 {
845 g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_chain;
846 g_ramdisk_param.DiskSize = (UINT64)g_iso_buf_size;
847
848 ventoy_save_ramdisk_param();
849
850 ventoy_install_blockio(ImageHandle, g_iso_buf_size);
851 Status = ventoy_boot(ImageHandle);
852
853 ventoy_delete_ramdisk_param();
854 }
855 else
856 {
857 ventoy_save_variable();
858 ventoy_find_iso_disk(ImageHandle);
859
860 ventoy_debug_pause();
861
862 ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
863
864 ventoy_debug_pause();
865
866 Status = ventoy_boot(ImageHandle);
867
868 ventoy_clean_env();
869 }
870
871 if (EFI_NOT_FOUND == Status)
872 {
873 gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
874 gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC L"!\r\n");
875 sleep(30);
876 }
877
878 ventoy_clear_input();
879 gST->ConOut->ClearScreen(gST->ConOut);
880
881 return EFI_SUCCESS;
882 }
883