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