]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c
debug CI
[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 BOOLEAN gBootFallBack = FALSE;
41 BOOLEAN gDotEfiBoot = FALSE;
42 BOOLEAN gLoadIsoEfi = FALSE;
43 BOOLEAN gIsoUdf = FALSE;
44 ventoy_ram_disk g_ramdisk_param;
45 ventoy_chain_head *g_chain;
46 void *g_vtoy_img_location_buf;
47 ventoy_img_chunk *g_chunk;
48 UINT8 *g_os_param_reserved;
49 UINT32 g_img_chunk_num;
50 ventoy_override_chunk *g_override_chunk;
51 UINT32 g_override_chunk_num;
52 ventoy_virt_chunk *g_virt_chunk;
53 UINT32 g_virt_chunk_num;
54 vtoy_block_data gBlockData;
55 static grub_env_get_pf grub_env_get = NULL;
56 static grub_env_set_pf grub_env_set = NULL;
57
58 ventoy_grub_param_file_replace *g_file_replace_list = NULL;
59 ventoy_efi_file_replace g_efi_file_replace;
60
61 CONST CHAR16 gIso9660EfiDriverPath[] = ISO9660_EFI_DRIVER_PATH;
62 CONST CHAR16 gUdfEfiDriverPath[] = UDF_EFI_DRIVER_PATH;
63
64 BOOLEAN g_fix_windows_1st_cdrom_issue = FALSE;
65
66 STATIC BOOLEAN g_hook_keyboard = FALSE;
67
68 CHAR16 gFirstTryBootFile[256] = {0};
69
70 /* Boot filename */
71 UINTN gBootFileStartIndex = 1;
72 CONST CHAR16 *gEfiBootFileName[] =
73 {
74 L"@",
75 EFI_REMOVABLE_MEDIA_FILE_NAME,
76 #if defined (MDE_CPU_IA32)
77 L"\\EFI\\BOOT\\GRUBIA32.EFI",
78 L"\\EFI\\BOOT\\BOOTia32.EFI",
79 L"\\EFI\\BOOT\\bootia32.efi",
80 L"\\efi\\boot\\bootia32.efi",
81 #elif defined (MDE_CPU_X64)
82 L"\\EFI\\BOOT\\GRUBX64.EFI",
83 L"\\EFI\\BOOT\\BOOTx64.EFI",
84 L"\\EFI\\BOOT\\bootx64.efi",
85 L"\\efi\\boot\\bootx64.efi",
86 #elif defined (MDE_CPU_ARM)
87 L"\\EFI\\BOOT\\GRUBARM.EFI",
88 L"\\EFI\\BOOT\\BOOTarm.EFI",
89 L"\\EFI\\BOOT\\bootarm.efi",
90 L"\\efi\\boot\\bootarm.efi",
91 #elif defined (MDE_CPU_AARCH64)
92 L"\\EFI\\BOOT\\GRUBAA64.EFI",
93 L"\\EFI\\BOOT\\BOOTaa64.EFI",
94 L"\\EFI\\BOOT\\bootaa64.efi",
95 L"\\efi\\boot\\bootaa64.efi",
96 #endif
97
98 };
99
100 VOID EFIAPI VtoyDebug(IN CONST CHAR8 *Format, ...)
101 {
102 VA_LIST Marker;
103 CHAR16 Buffer[512];
104
105 VA_START (Marker, Format);
106 UnicodeVSPrintAsciiFormat(Buffer, sizeof(Buffer), Format, Marker);
107 VA_END (Marker);
108
109 gST->ConOut->OutputString(gST->ConOut, Buffer);
110 }
111
112 VOID EFIAPI ventoy_clear_input(VOID)
113 {
114 EFI_INPUT_KEY Key;
115
116 gST->ConIn->Reset(gST->ConIn, FALSE);
117 while (EFI_SUCCESS == gST->ConIn->ReadKeyStroke(gST->ConIn, &Key))
118 {
119 ;
120 }
121 gST->ConIn->Reset(gST->ConIn, FALSE);
122 }
123
124 static void EFIAPI ventoy_dump_img_chunk(ventoy_chain_head *chain)
125 {
126 UINT32 i;
127 int errcnt = 0;
128 UINT64 img_sec = 0;
129 ventoy_img_chunk *chunk;
130
131 chunk = (ventoy_img_chunk *)((char *)chain + chain->img_chunk_offset);
132
133 debug("##################### ventoy_dump_img_chunk #######################");
134
135 for (i = 0; i < chain->img_chunk_num; i++)
136 {
137 debug("%2u: [ %u - %u ] <==> [ %llu - %llu ]",
138 i, chunk[i].img_start_sector, chunk[i].img_end_sector,
139 chunk[i].disk_start_sector, chunk[i].disk_end_sector);
140
141 if (i > 0 && (chunk[i].img_start_sector != chunk[i - 1].img_end_sector + 1))
142 {
143 errcnt++;
144 }
145
146 img_sec += chunk[i].img_end_sector - chunk[i].img_start_sector + 1;
147 }
148
149 if (errcnt == 0 && (img_sec * 2048 == g_chain->real_img_size_in_bytes))
150 {
151 debug("image chunk size check success");
152 }
153 else
154 {
155 debug("image chunk size check failed %d", errcnt);
156 }
157
158 ventoy_debug_pause();
159 }
160
161 static void EFIAPI ventoy_dump_override_chunk(ventoy_chain_head *chain)
162 {
163 UINT32 i;
164 ventoy_override_chunk *chunk;
165
166 chunk = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset);
167
168 debug("##################### ventoy_dump_override_chunk #######################");
169
170 for (i = 0; i < g_override_chunk_num; i++)
171 {
172 debug("%2u: [ %llu, %u ]", i, chunk[i].img_offset, chunk[i].override_size);
173 }
174
175 ventoy_debug_pause();
176 }
177
178 static void EFIAPI ventoy_dump_virt_chunk(ventoy_chain_head *chain)
179 {
180 UINT32 i;
181 ventoy_virt_chunk *node;
182
183 debug("##################### ventoy_dump_virt_chunk #######################");
184 debug("virt_chunk_offset=%u", chain->virt_chunk_offset);
185 debug("virt_chunk_num=%u", chain->virt_chunk_num);
186
187 node = (ventoy_virt_chunk *)((char *)chain + chain->virt_chunk_offset);
188 for (i = 0; i < chain->virt_chunk_num; i++, node++)
189 {
190 debug("%2u: mem:[ %u, %u, %u ] remap:[ %u, %u, %u ]", i,
191 node->mem_sector_start,
192 node->mem_sector_end,
193 node->mem_sector_offset,
194 node->remap_sector_start,
195 node->remap_sector_end,
196 node->org_sector_start);
197 }
198
199 ventoy_debug_pause();
200 }
201
202 static void EFIAPI ventoy_dump_chain(ventoy_chain_head *chain)
203 {
204 UINT32 i = 0;
205 UINT8 chksum = 0;
206 UINT8 *guid;
207
208 guid = chain->os_param.vtoy_disk_guid;
209 for (i = 0; i < sizeof(ventoy_os_param); i++)
210 {
211 chksum += *((UINT8 *)(&(chain->os_param)) + i);
212 }
213
214 debug("##################### ventoy_dump_chain #######################");
215
216 debug("os_param->chksum=0x%x (%a)", chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
217 debug("os_param->vtoy_disk_guid=%02x%02x%02x%02x", guid[0], guid[1], guid[2], guid[3]);
218 debug("os_param->vtoy_disk_size=%llu", chain->os_param.vtoy_disk_size);
219 debug("os_param->vtoy_disk_part_id=%u", chain->os_param.vtoy_disk_part_id);
220 debug("os_param->vtoy_disk_part_type=%u", chain->os_param.vtoy_disk_part_type);
221 debug("os_param->vtoy_img_path=<%a>", chain->os_param.vtoy_img_path);
222 debug("os_param->vtoy_img_size=<%llu>", chain->os_param.vtoy_img_size);
223 debug("os_param->vtoy_img_location_addr=<0x%llx>", chain->os_param.vtoy_img_location_addr);
224 debug("os_param->vtoy_img_location_len=<%u>", chain->os_param.vtoy_img_location_len);
225 debug("os_param->vtoy_reserved=<%u %u %u %u %u>",
226 g_os_param_reserved[0],
227 g_os_param_reserved[1],
228 g_os_param_reserved[2],
229 g_os_param_reserved[3],
230 g_os_param_reserved[4]
231 );
232
233 ventoy_debug_pause();
234
235 debug("chain->disk_drive=0x%x", chain->disk_drive);
236 debug("chain->disk_sector_size=%u", chain->disk_sector_size);
237 debug("chain->real_img_size_in_bytes=%llu", chain->real_img_size_in_bytes);
238 debug("chain->virt_img_size_in_bytes=%llu", chain->virt_img_size_in_bytes);
239 debug("chain->boot_catalog=%u", chain->boot_catalog);
240 debug("chain->img_chunk_offset=%u", chain->img_chunk_offset);
241 debug("chain->img_chunk_num=%u", chain->img_chunk_num);
242 debug("chain->override_chunk_offset=%u", chain->override_chunk_offset);
243 debug("chain->override_chunk_num=%u", chain->override_chunk_num);
244
245 ventoy_debug_pause();
246
247 ventoy_dump_img_chunk(chain);
248 ventoy_dump_override_chunk(chain);
249 ventoy_dump_virt_chunk(chain);
250 }
251
252 static int ventoy_update_image_location(ventoy_os_param *param)
253 {
254 EFI_STATUS Status = EFI_SUCCESS;
255 UINT8 chksum = 0;
256 unsigned int i;
257 unsigned int length;
258 UINTN address = 0;
259 void *buffer = NULL;
260 ventoy_image_location *location = NULL;
261 ventoy_image_disk_region *region = NULL;
262 ventoy_img_chunk *chunk = g_chunk;
263
264 length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region);
265
266 Status = gBS->AllocatePool(EfiRuntimeServicesData, length + 4096 * 2, &buffer);
267 if (EFI_ERROR(Status) || NULL == buffer)
268 {
269 debug("Failed to allocate runtime pool %r\n", Status);
270 return 1;
271 }
272
273 address = (UINTN)buffer;
274 g_vtoy_img_location_buf = buffer;
275
276 if (address % 4096)
277 {
278 address += 4096 - (address % 4096);
279 }
280
281 param->chksum = 0;
282 param->vtoy_img_location_addr = address;
283 param->vtoy_img_location_len = length;
284
285 /* update check sum */
286 for (i = 0; i < sizeof(ventoy_os_param); i++)
287 {
288 chksum += *((UINT8 *)param + i);
289 }
290 param->chksum = (chksum == 0) ? 0 : (UINT8)(0x100 - chksum);
291
292 location = (ventoy_image_location *)(unsigned long)(param->vtoy_img_location_addr);
293 if (NULL == location)
294 {
295 return 0;
296 }
297
298 CopyMem(&location->guid, &param->guid, sizeof(ventoy_guid));
299 location->image_sector_size = gSector512Mode ? 512 : 2048;
300 location->disk_sector_size = g_chain->disk_sector_size;
301 location->region_count = g_img_chunk_num;
302
303 region = location->regions;
304
305 if (gSector512Mode)
306 {
307 for (i = 0; i < g_img_chunk_num; i++)
308 {
309 region->image_sector_count = chunk->disk_end_sector - chunk->disk_start_sector + 1;
310 region->image_start_sector = chunk->img_start_sector * 4;
311 region->disk_start_sector = chunk->disk_start_sector;
312 region++;
313 chunk++;
314 }
315 }
316 else
317 {
318 for (i = 0; i < g_img_chunk_num; i++)
319 {
320 region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1;
321 region->image_start_sector = chunk->img_start_sector;
322 region->disk_start_sector = chunk->disk_start_sector;
323 region++;
324 chunk++;
325 }
326 }
327
328 return 0;
329 }
330
331 EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath)
332 {
333 EFI_HANDLE Handle = NULL;
334 EFI_STATUS Status = EFI_SUCCESS;
335 EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL;
336 EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL;
337 EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL;
338
339 pTmpDevPath = DuplicateDevicePath(pDevPath);
340 if (!pTmpDevPath)
341 {
342 return NULL;
343 }
344
345 pCurNode = pTmpDevPath;
346 while (!IsDevicePathEnd(pCurNode))
347 {
348 pLastNode = pCurNode;
349 pCurNode = NextDevicePathNode(pCurNode);
350 }
351 if (pLastNode)
352 {
353 CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL));
354 }
355
356 pCurNode = pTmpDevPath;
357 Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle);
358 debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE));
359
360 FreePool(pTmpDevPath);
361
362 return Handle;
363 }
364
365 EFI_STATUS EFIAPI ventoy_save_ramdisk_param(VOID)
366 {
367 EFI_STATUS Status = EFI_SUCCESS;
368 EFI_GUID VarGuid = VENTOY_GUID;
369
370 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
371 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
372 sizeof(g_ramdisk_param), &(g_ramdisk_param));
373 debug("set ramdisk variable %r", Status);
374
375 return Status;
376 }
377
378 EFI_STATUS EFIAPI ventoy_delete_ramdisk_param(VOID)
379 {
380 EFI_STATUS Status = EFI_SUCCESS;
381 EFI_GUID VarGuid = VENTOY_GUID;
382
383 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
384 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
385 0, NULL);
386 debug("delete efi variable %r", Status);
387
388 return Status;
389 }
390
391
392 EFI_STATUS EFIAPI ventoy_save_variable(VOID)
393 {
394 EFI_STATUS Status = EFI_SUCCESS;
395 EFI_GUID VarGuid = VENTOY_GUID;
396
397 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
398 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
399 sizeof(g_chain->os_param), &(g_chain->os_param));
400 debug("set efi variable %r", Status);
401
402 return Status;
403 }
404
405 EFI_STATUS EFIAPI ventoy_delete_variable(VOID)
406 {
407 EFI_STATUS Status = EFI_SUCCESS;
408 EFI_GUID VarGuid = VENTOY_GUID;
409
410 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
411 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
412 0, NULL);
413 debug("delete efi variable %r", Status);
414
415 return Status;
416 }
417
418 #if (VENTOY_DEVICE_WARN != 0)
419 STATIC VOID ventoy_warn_invalid_device(VOID)
420 {
421 STATIC BOOLEAN flag = FALSE;
422
423 if (flag)
424 {
425 return;
426 }
427
428 flag = TRUE;
429 gST->ConOut->ClearScreen(gST->ConOut);
430 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
431 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
432 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n\r\n\r\n");
433
434 gST->ConOut->OutputString(gST->ConOut, L"This is NOT a standard Ventoy device and is NOT supported.\r\n\r\n");
435 gST->ConOut->OutputString(gST->ConOut, L"You should follow the official instructions in https://www.ventoy.net\r\n");
436
437 gST->ConOut->OutputString(gST->ConOut, L"\r\n\r\nWill exit after 10 seconds ...... ");
438
439 sleep(10);
440 }
441 #else
442 STATIC VOID ventoy_warn_invalid_device(VOID)
443 {
444
445 }
446 #endif
447
448 STATIC EFI_STATUS EFIAPI ventoy_load_image
449 (
450 IN EFI_HANDLE ImageHandle,
451 IN EFI_DEVICE_PATH_PROTOCOL *pDevicePath,
452 IN CONST CHAR16 *FileName,
453 IN UINTN FileNameLen,
454 OUT EFI_HANDLE *Image
455 )
456 {
457 EFI_STATUS Status = EFI_SUCCESS;
458 CHAR16 TmpBuf[256] = {0};
459 FILEPATH_DEVICE_PATH *pFilePath = NULL;
460 EFI_DEVICE_PATH_PROTOCOL *pImgPath = NULL;
461
462 pFilePath = (FILEPATH_DEVICE_PATH *)TmpBuf;
463 pFilePath->Header.Type = MEDIA_DEVICE_PATH;
464 pFilePath->Header.SubType = MEDIA_FILEPATH_DP;
465 pFilePath->Header.Length[0] = FileNameLen + sizeof(EFI_DEVICE_PATH_PROTOCOL);
466 pFilePath->Header.Length[1] = 0;
467 CopyMem(pFilePath->PathName, FileName, FileNameLen);
468
469 pImgPath = AppendDevicePathNode(pDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)pFilePath);
470 if (!pImgPath)
471 {
472 return EFI_NOT_FOUND;
473 }
474
475 Status = gBS->LoadImage(FALSE, ImageHandle, pImgPath, NULL, 0, Image);
476
477 debug("Load Image File %r DP: <%s>", Status, ConvertDevicePathToText(pImgPath, FALSE, FALSE));
478
479 FreePool(pImgPath);
480
481 return Status;
482 }
483
484
485 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
486 {
487 UINTN i = 0;
488 UINTN Count = 0;
489 UINT64 DiskSize = 0;
490 MBR_HEAD *pMBR = NULL;
491 UINT8 *pBuffer = NULL;
492 EFI_HANDLE *Handles;
493 EFI_STATUS Status = EFI_SUCCESS;
494 EFI_BLOCK_IO_PROTOCOL *pBlockIo;
495
496 pBuffer = AllocatePool(2048);
497 if (!pBuffer)
498 {
499 return EFI_OUT_OF_RESOURCES;
500 }
501
502 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiBlockIoProtocolGuid,
503 NULL, &Count, &Handles);
504 if (EFI_ERROR(Status))
505 {
506 FreePool(pBuffer);
507 return Status;
508 }
509
510 for (i = 0; i < Count; i++)
511 {
512 Status = gBS->HandleProtocol(Handles[i], &gEfiBlockIoProtocolGuid, (VOID **)&pBlockIo);
513 if (EFI_ERROR(Status))
514 {
515 continue;
516 }
517
518 DiskSize = (pBlockIo->Media->LastBlock + 1) * pBlockIo->Media->BlockSize;
519 debug("This Disk size: %llu", DiskSize);
520 if (g_chain->os_param.vtoy_disk_size != DiskSize)
521 {
522 continue;
523 }
524
525 Status = pBlockIo->ReadBlocks(pBlockIo, pBlockIo->Media->MediaId, 0, 512, pBuffer);
526 if (EFI_ERROR(Status))
527 {
528 debug("ReadBlocks filed %r", Status);
529 continue;
530 }
531
532 if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0)
533 {
534 pMBR = (MBR_HEAD *)pBuffer;
535 if (pMBR->PartTbl[0].FsFlag != 0xEE)
536 {
537 if (pMBR->PartTbl[0].StartSectorId != 2048 ||
538 pMBR->PartTbl[1].SectorCount != 65536 ||
539 pMBR->PartTbl[1].StartSectorId != pMBR->PartTbl[0].StartSectorId + pMBR->PartTbl[0].SectorCount)
540 {
541 debug("Failed to check disk part table");
542 ventoy_warn_invalid_device();
543 }
544 }
545
546 gBlockData.RawBlockIoHandle = Handles[i];
547 gBlockData.pRawBlockIo = pBlockIo;
548 gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
549 (VOID **)&(gBlockData.pDiskDevPath),
550 ImageHandle,
551 Handles[i],
552 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
553
554 debug("Find Ventoy Disk Handle:%p DP:%s", Handles[i],
555 ConvertDevicePathToText(gBlockData.pDiskDevPath, FALSE, FALSE));
556 break;
557 }
558 }
559
560 FreePool(Handles);
561
562 if (i >= Count)
563 {
564 return EFI_NOT_FOUND;
565 }
566 else
567 {
568 return EFI_SUCCESS;
569 }
570 }
571
572
573 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk_fs(IN EFI_HANDLE ImageHandle)
574 {
575 UINTN i = 0;
576 UINTN Count = 0;
577 EFI_HANDLE Parent = NULL;
578 EFI_HANDLE *Handles = NULL;
579 EFI_STATUS Status = EFI_SUCCESS;
580 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
581 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
582
583 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
584 NULL, &Count, &Handles);
585 if (EFI_ERROR(Status))
586 {
587 return Status;
588 }
589
590 debug("ventoy_find_iso_disk_fs fs count:%u", Count);
591
592 for (i = 0; i < Count; i++)
593 {
594 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
595 if (EFI_ERROR(Status))
596 {
597 continue;
598 }
599
600 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
601 (VOID **)&pDevPath,
602 ImageHandle,
603 Handles[i],
604 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
605 if (EFI_ERROR(Status))
606 {
607 debug("Failed to open device path protocol %r", Status);
608 continue;
609 }
610
611 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
612 Parent = ventoy_get_parent_handle(pDevPath);
613
614 if (Parent == gBlockData.RawBlockIoHandle)
615 {
616 debug("Find ventoy disk fs");
617 gBlockData.DiskFsHandle = Handles[i];
618 gBlockData.pDiskFs = pFile;
619 gBlockData.pDiskFsDevPath = pDevPath;
620 break;
621 }
622 }
623
624 FreePool(Handles);
625
626 return EFI_SUCCESS;
627 }
628
629 STATIC EFI_STATUS EFIAPI ventoy_load_isoefi_driver(IN EFI_HANDLE ImageHandle)
630 {
631 EFI_HANDLE Image = NULL;
632 EFI_STATUS Status = EFI_SUCCESS;
633 CHAR16 LogVar[4] = L"5";
634
635 if (gIsoUdf)
636 {
637 Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath,
638 gUdfEfiDriverPath,
639 sizeof(gUdfEfiDriverPath),
640 &Image);
641 debug("load iso UDF efi driver status:%r", Status);
642 }
643 else
644 {
645 Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath,
646 gIso9660EfiDriverPath,
647 sizeof(gIso9660EfiDriverPath),
648 &Image);
649 debug("load iso 9660 efi driver status:%r", Status);
650 }
651
652 if (gDebugPrint)
653 {
654 gRT->SetVariable(L"FS_LOGGING", &gShellVariableGuid,
655 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
656 sizeof(LogVar), LogVar);
657 }
658
659 gRT->SetVariable(L"FS_NAME_NOCASE", &gShellVariableGuid,
660 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
661 sizeof(LogVar), LogVar);
662
663 gBlockData.IsoDriverImage = Image;
664 Status = gBS->StartImage(Image, NULL, NULL);
665 debug("Start iso efi driver status:%r", Status);
666
667 return EFI_SUCCESS;
668 }
669
670 STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
671 {
672 UINT32 i = 0;
673 UINT32 old_cnt = 0;
674 UINTN size = 0;
675 UINT8 chksum = 0;
676 const char *pEnv = NULL;
677 CHAR16 *pPos = NULL;
678 CHAR16 *pCmdLine = NULL;
679 EFI_STATUS Status = EFI_SUCCESS;
680 ventoy_grub_param *pGrubParam = NULL;
681 EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL;
682 ventoy_chain_head *chain = NULL;
683
684 Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo);
685 if (EFI_ERROR(Status))
686 {
687 VtoyDebug("Failed to handle load image protocol %r", Status);
688 return Status;
689 }
690
691 pCmdLine = (CHAR16 *)AllocatePool(pImageInfo->LoadOptionsSize + 4);
692 SetMem(pCmdLine, pImageInfo->LoadOptionsSize + 4, 0);
693 CopyMem(pCmdLine, pImageInfo->LoadOptions, pImageInfo->LoadOptionsSize);
694
695 if (StrStr(pCmdLine, L"debug"))
696 {
697 gDebugPrint = TRUE;
698 }
699
700 if (StrStr(pCmdLine, L"fallback"))
701 {
702 gBootFallBack = TRUE;
703 }
704
705 if (StrStr(pCmdLine, L"dotefi"))
706 {
707 gDotEfiBoot = TRUE;
708 }
709
710 if (StrStr(pCmdLine, L"isoefi=on"))
711 {
712 gLoadIsoEfi = TRUE;
713 }
714
715 if (StrStr(pCmdLine, L"iso_udf"))
716 {
717 gIsoUdf = TRUE;
718 }
719
720 pPos = StrStr(pCmdLine, L"FirstTry=@");
721 if (pPos)
722 {
723 pPos += StrLen(L"FirstTry=");
724 for (i = 0; i < ARRAY_SIZE(gFirstTryBootFile); i++, pPos++)
725 {
726 if (*pPos != L' ' && *pPos != L'\t' && *pPos)
727 {
728 gFirstTryBootFile[i] = (*pPos == '@') ? '\\' : *pPos;
729 }
730 else
731 {
732 break;
733 }
734 }
735
736 gEfiBootFileName[0] = gFirstTryBootFile;
737 gBootFileStartIndex = 0;
738 }
739
740 debug("cmdline:<%s>", pCmdLine);
741
742 if (gFirstTryBootFile[0])
743 {
744 debug("First Try:<%s>", gFirstTryBootFile);
745 }
746
747 pPos = StrStr(pCmdLine, L"env_param=");
748 if (!pPos)
749 {
750 return EFI_INVALID_PARAMETER;
751 }
752
753 pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param="));
754 grub_env_set = pGrubParam->grub_env_set;
755 grub_env_get = pGrubParam->grub_env_get;
756 pEnv = grub_env_get("VTOY_CHKDEV_RESULT_STRING");
757 if (!pEnv)
758 {
759 return EFI_INVALID_PARAMETER;
760 }
761
762 if (pEnv[0] != '0' || pEnv[1] != 0)
763 {
764 ventoy_warn_invalid_device();
765 return EFI_INVALID_PARAMETER;
766 }
767
768 g_file_replace_list = &pGrubParam->file_replace;
769 old_cnt = g_file_replace_list->old_file_cnt;
770 debug("file replace: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
771 g_file_replace_list->magic,
772 g_file_replace_list->new_file_virtual_id,
773 old_cnt,
774 old_cnt > 0 ? g_file_replace_list->old_file_name[0] : "",
775 old_cnt > 1 ? g_file_replace_list->old_file_name[1] : "",
776 old_cnt > 2 ? g_file_replace_list->old_file_name[2] : "",
777 old_cnt > 3 ? g_file_replace_list->old_file_name[3] : ""
778 );
779
780 pPos = StrStr(pCmdLine, L"mem:");
781 chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
782
783 pPos = StrStr(pPos, L"size:");
784 size = StrDecimalToUintn(pPos + 5);
785
786 debug("memory addr:%p size:%lu", chain, size);
787
788 if (StrStr(pCmdLine, L"sector512"))
789 {
790 gSector512Mode = TRUE;
791 }
792
793 if (StrStr(pCmdLine, L"memdisk"))
794 {
795 g_iso_data_buf = (UINT8 *)chain + sizeof(ventoy_chain_head);
796 g_iso_buf_size = size - sizeof(ventoy_chain_head);
797 debug("memdisk mode iso_buf_size:%u", g_iso_buf_size);
798
799 g_chain = chain;
800 gMemdiskMode = TRUE;
801 }
802 else
803 {
804 debug("This is normal mode");
805 g_chain = AllocatePool(size);
806 CopyMem(g_chain, chain, size);
807
808 g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset);
809 g_img_chunk_num = g_chain->img_chunk_num;
810 g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset);
811 g_override_chunk_num = g_chain->override_chunk_num;
812 g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset);
813 g_virt_chunk_num = g_chain->virt_chunk_num;
814
815 g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
816
817 /* Workaround for Windows & ISO9660 */
818 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
819 {
820 g_fixup_iso9660_secover_enable = TRUE;
821 }
822
823 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
824 {
825 g_hook_keyboard = TRUE;
826 }
827
828 debug("internal param: secover:%u keyboard:%u", g_fixup_iso9660_secover_enable, g_hook_keyboard);
829
830 for (i = 0; i < sizeof(ventoy_os_param); i++)
831 {
832 chksum += *((UINT8 *)(&(g_chain->os_param)) + i);
833 }
834
835 if (gDebugPrint)
836 {
837 debug("os param checksum: 0x%x %a", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
838 }
839
840 ventoy_update_image_location(&(g_chain->os_param));
841
842 if (gDebugPrint)
843 {
844 ventoy_dump_chain(g_chain);
845 }
846 }
847
848 g_fix_windows_1st_cdrom_issue = FALSE;
849 if (ventoy_chain_windows == g_os_param_reserved[2] ||
850 ventoy_chain_wim == g_os_param_reserved[2])
851 {
852 if (ventoy_is_cdrom_dp_exist())
853 {
854 debug("fixup the 1st cdrom influences when boot windows ...");
855 g_fix_windows_1st_cdrom_issue = TRUE;
856 }
857 }
858
859 ventoy_debug_pause();
860
861 FreePool(pCmdLine);
862 return EFI_SUCCESS;
863 }
864
865 EFI_STATUS EFIAPI ventoy_clean_env(VOID)
866 {
867 FreePool(g_sector_flag);
868 g_sector_flag_num = 0;
869
870 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
871 {
872 gBS->UnloadImage(gBlockData.IsoDriverImage);
873 }
874
875 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
876
877 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
878 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
879 &gEfiDevicePathProtocolGuid, gBlockData.Path,
880 NULL);
881
882 ventoy_delete_variable();
883
884 if (g_vtoy_img_location_buf)
885 {
886 FreePool(g_vtoy_img_location_buf);
887 }
888
889 if (!gMemdiskMode)
890 {
891 FreePool(g_chain);
892 }
893
894 return EFI_SUCCESS;
895 }
896
897 STATIC EFI_STATUS ventoy_hook_start(VOID)
898 {
899 /* don't add debug print in this function */
900
901 if (g_fix_windows_1st_cdrom_issue)
902 {
903 ventoy_hook_1st_cdrom_start();
904 }
905
906 /* let this the last */
907 if (g_hook_keyboard)
908 {
909 ventoy_hook_keyboard_start();
910 }
911
912 return EFI_SUCCESS;
913 }
914
915 STATIC EFI_STATUS ventoy_hook_stop(VOID)
916 {
917 /* don't add debug print in this function */
918
919 if (g_fix_windows_1st_cdrom_issue)
920 {
921 ventoy_hook_1st_cdrom_stop();
922 }
923
924 /* let this the last */
925 if (g_hook_keyboard)
926 {
927 ventoy_hook_keyboard_stop();
928 }
929
930 return EFI_SUCCESS;
931 }
932
933 EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
934 {
935 UINTN t = 0;
936 UINTN i = 0;
937 UINTN j = 0;
938 UINTN Find = 0;
939 UINTN Count = 0;
940 EFI_HANDLE Image = NULL;
941 EFI_HANDLE *Handles = NULL;
942 EFI_STATUS Status = EFI_SUCCESS;
943 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
944 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
945
946 for (t = 0; t < 3; t++)
947 {
948 Count = 0;
949 Handles = NULL;
950
951 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
952 NULL, &Count, &Handles);
953 if (EFI_ERROR(Status))
954 {
955 return Status;
956 }
957
958 debug("ventoy_boot fs count:%u", Count);
959
960 for (i = 0; i < Count; i++)
961 {
962 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
963 if (EFI_ERROR(Status))
964 {
965 continue;
966 }
967
968 debug("FS:%u Protocol:%p OpenVolume:%p", i, pFile, pFile->OpenVolume);
969
970 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
971 (VOID **)&pDevPath,
972 ImageHandle,
973 Handles[i],
974 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
975 if (EFI_ERROR(Status))
976 {
977 debug("Failed to open device path protocol %r", Status);
978 continue;
979 }
980
981 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
982 if (CompareMem(gBlockData.Path, pDevPath, gBlockData.DevicePathCompareLen))
983 {
984 debug("Not ventoy disk file system");
985 continue;
986 }
987
988 for (j = gBootFileStartIndex; j < ARRAY_SIZE(gEfiBootFileName); j++)
989 {
990 Status = ventoy_load_image(ImageHandle, pDevPath, gEfiBootFileName[j],
991 StrSize(gEfiBootFileName[j]), &Image);
992 if (EFI_SUCCESS == Status)
993 {
994 break;
995 }
996 debug("Failed to load image %r <%s>", Status, gEfiBootFileName[j]);
997 }
998
999 if (j >= ARRAY_SIZE(gEfiBootFileName))
1000 {
1001 continue;
1002 }
1003
1004 Find++;
1005 debug("Find boot file, now try to boot .....");
1006 ventoy_debug_pause();
1007
1008 if (gDebugPrint)
1009 {
1010 gST->ConIn->Reset(gST->ConIn, FALSE);
1011 }
1012
1013 if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC)
1014 {
1015 ventoy_wrapper_push_openvolume(pFile->OpenVolume);
1016 pFile->OpenVolume = ventoy_wrapper_open_volume;
1017 }
1018
1019 ventoy_hook_start();
1020 /* can't add debug print here */
1021 //ventoy_wrapper_system();
1022 Status = gBS->StartImage(Image, NULL, NULL);
1023 ventoy_hook_stop();
1024
1025 if (EFI_ERROR(Status))
1026 {
1027 debug("Failed to start image %r", Status);
1028 sleep(3);
1029 gBS->UnloadImage(Image);
1030 break;
1031 }
1032 }
1033
1034 FreePool(Handles);
1035
1036 if (Find == 0)
1037 {
1038 if (gDotEfiBoot)
1039 {
1040 break;
1041 }
1042
1043 debug("Fs not found, now wait and retry...");
1044 sleep(1);
1045 }
1046 }
1047
1048 if (Find == 0)
1049 {
1050 return EFI_NOT_FOUND;
1051 }
1052
1053 return EFI_SUCCESS;
1054 }
1055
1056 EFI_STATUS EFIAPI VentoyEfiMain
1057 (
1058 IN EFI_HANDLE ImageHandle,
1059 IN EFI_SYSTEM_TABLE *SystemTable
1060 )
1061 {
1062 EFI_STATUS Status = EFI_SUCCESS;
1063 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *Protocol;
1064
1065 g_sector_flag_num = 512; /* initial value */
1066
1067 g_sector_flag = AllocatePool(g_sector_flag_num * sizeof(ventoy_sector_flag));
1068 if (NULL == g_sector_flag)
1069 {
1070 return EFI_OUT_OF_RESOURCES;
1071 }
1072
1073 Status = gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&Protocol);
1074 if (EFI_SUCCESS == Status)
1075 {
1076 g_con_simple_input_ex = Protocol;
1077 }
1078
1079 gST->ConOut->ClearScreen(gST->ConOut);
1080 ventoy_clear_input();
1081
1082 Status = ventoy_parse_cmdline(ImageHandle);
1083 if (EFI_ERROR(Status))
1084 {
1085 return Status;
1086 }
1087
1088 if (gMemdiskMode)
1089 {
1090 g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_iso_data_buf;
1091 g_ramdisk_param.DiskSize = (UINT64)g_iso_buf_size;
1092
1093 ventoy_save_ramdisk_param();
1094
1095 if (gLoadIsoEfi)
1096 {
1097 ventoy_find_iso_disk(ImageHandle);
1098 ventoy_find_iso_disk_fs(ImageHandle);
1099 ventoy_load_isoefi_driver(ImageHandle);
1100 }
1101
1102 ventoy_install_blockio(ImageHandle, g_iso_buf_size);
1103 ventoy_debug_pause();
1104
1105 Status = ventoy_boot(ImageHandle);
1106
1107 ventoy_delete_ramdisk_param();
1108
1109 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
1110 {
1111 gBS->UnloadImage(gBlockData.IsoDriverImage);
1112 }
1113
1114 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
1115 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
1116 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
1117 &gEfiDevicePathProtocolGuid, gBlockData.Path,
1118 NULL);
1119 }
1120 else
1121 {
1122 ventoy_save_variable();
1123 Status = ventoy_find_iso_disk(ImageHandle);
1124 if (!EFI_ERROR(Status))
1125 {
1126 if (gLoadIsoEfi)
1127 {
1128 ventoy_find_iso_disk_fs(ImageHandle);
1129 ventoy_load_isoefi_driver(ImageHandle);
1130 }
1131
1132 ventoy_debug_pause();
1133
1134 ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
1135
1136 ventoy_debug_pause();
1137
1138 Status = ventoy_boot(ImageHandle);
1139 }
1140
1141 ventoy_clean_env();
1142 }
1143
1144 if (FALSE == gDotEfiBoot && FALSE == gBootFallBack)
1145 {
1146 if (EFI_NOT_FOUND == Status)
1147 {
1148 gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
1149 gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC L"!\r\n");
1150 sleep(30);
1151 }
1152 }
1153
1154 ventoy_clear_input();
1155 gST->ConOut->ClearScreen(gST->ConOut);
1156
1157 if (gDotEfiBoot && (EFI_NOT_FOUND == Status))
1158 {
1159 grub_env_set("vtoy_dotefi_retry", "YES");
1160 }
1161
1162 return EFI_SUCCESS;
1163 }
1164