]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c
最近收到一些特殊的错误报告,最后证明是非标准的Ventoy环境的原因。尤其是单分区下环境下使用 Ventoy 。
[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 = gSector512Mode ? 512 : 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 if (gSector512Mode)
283 {
284 for (i = 0; i < g_img_chunk_num; i++)
285 {
286 region->image_sector_count = chunk->disk_end_sector - chunk->disk_start_sector + 1;
287 region->image_start_sector = chunk->img_start_sector * 4;
288 region->disk_start_sector = chunk->disk_start_sector;
289 region++;
290 chunk++;
291 }
292 }
293 else
294 {
295 for (i = 0; i < g_img_chunk_num; i++)
296 {
297 region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1;
298 region->image_start_sector = chunk->img_start_sector;
299 region->disk_start_sector = chunk->disk_start_sector;
300 region++;
301 chunk++;
302 }
303 }
304
305 return 0;
306 }
307
308 EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath)
309 {
310 EFI_HANDLE Handle = NULL;
311 EFI_STATUS Status = EFI_SUCCESS;
312 EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL;
313 EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL;
314 EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL;
315
316 pTmpDevPath = DuplicateDevicePath(pDevPath);
317 if (!pTmpDevPath)
318 {
319 return NULL;
320 }
321
322 pCurNode = pTmpDevPath;
323 while (!IsDevicePathEnd(pCurNode))
324 {
325 pLastNode = pCurNode;
326 pCurNode = NextDevicePathNode(pCurNode);
327 }
328 if (pLastNode)
329 {
330 CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL));
331 }
332
333 pCurNode = pTmpDevPath;
334 Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle);
335 debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE));
336
337 FreePool(pTmpDevPath);
338
339 return Handle;
340 }
341
342 EFI_STATUS EFIAPI ventoy_save_ramdisk_param(VOID)
343 {
344 EFI_STATUS Status = EFI_SUCCESS;
345 EFI_GUID VarGuid = VENTOY_GUID;
346
347 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
348 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
349 sizeof(g_ramdisk_param), &(g_ramdisk_param));
350 debug("set ramdisk variable %r", Status);
351
352 return Status;
353 }
354
355 EFI_STATUS EFIAPI ventoy_delete_ramdisk_param(VOID)
356 {
357 EFI_STATUS Status = EFI_SUCCESS;
358 EFI_GUID VarGuid = VENTOY_GUID;
359
360 Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid,
361 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
362 0, NULL);
363 debug("delete efi variable %r", Status);
364
365 return Status;
366 }
367
368
369 EFI_STATUS EFIAPI ventoy_save_variable(VOID)
370 {
371 EFI_STATUS Status = EFI_SUCCESS;
372 EFI_GUID VarGuid = VENTOY_GUID;
373
374 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
375 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
376 sizeof(g_chain->os_param), &(g_chain->os_param));
377 debug("set efi variable %r", Status);
378
379 return Status;
380 }
381
382 EFI_STATUS EFIAPI ventoy_delete_variable(VOID)
383 {
384 EFI_STATUS Status = EFI_SUCCESS;
385 EFI_GUID VarGuid = VENTOY_GUID;
386
387 Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid,
388 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
389 0, NULL);
390 debug("delete efi variable %r", Status);
391
392 return Status;
393 }
394
395 #if (VENTOY_DEVICE_WARN != 0)
396 STATIC VOID ventoy_warn_invalid_device(VOID)
397 {
398 STATIC BOOLEAN flag = FALSE;
399
400 if (flag)
401 {
402 return;
403 }
404
405 flag = TRUE;
406 gST->ConOut->ClearScreen(gST->ConOut);
407 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
408 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
409 gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n\r\n\r\n");
410
411 gST->ConOut->OutputString(gST->ConOut, L"This is NOT a standard Ventoy device and is NOT supported.\r\n\r\n");
412 gST->ConOut->OutputString(gST->ConOut, L"You should follow the official instructions in https://www.ventoy.net\r\n");
413
414 gST->ConOut->OutputString(gST->ConOut, L"\r\n\r\nWill exit after 10 seconds ...... ");
415
416 sleep(10);
417 }
418 #else
419 STATIC VOID ventoy_warn_invalid_device(VOID)
420 {
421
422 }
423 #endif
424
425 STATIC EFI_STATUS EFIAPI ventoy_load_image
426 (
427 IN EFI_HANDLE ImageHandle,
428 IN EFI_DEVICE_PATH_PROTOCOL *pDevicePath,
429 IN CONST CHAR16 *FileName,
430 IN UINTN FileNameLen,
431 OUT EFI_HANDLE *Image
432 )
433 {
434 EFI_STATUS Status = EFI_SUCCESS;
435 CHAR16 TmpBuf[256] = {0};
436 FILEPATH_DEVICE_PATH *pFilePath = NULL;
437 EFI_DEVICE_PATH_PROTOCOL *pImgPath = NULL;
438
439 pFilePath = (FILEPATH_DEVICE_PATH *)TmpBuf;
440 pFilePath->Header.Type = MEDIA_DEVICE_PATH;
441 pFilePath->Header.SubType = MEDIA_FILEPATH_DP;
442 pFilePath->Header.Length[0] = FileNameLen + sizeof(EFI_DEVICE_PATH_PROTOCOL);
443 pFilePath->Header.Length[1] = 0;
444 CopyMem(pFilePath->PathName, FileName, FileNameLen);
445
446 pImgPath = AppendDevicePathNode(pDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)pFilePath);
447 if (!pImgPath)
448 {
449 return EFI_NOT_FOUND;
450 }
451
452 Status = gBS->LoadImage(FALSE, ImageHandle, pImgPath, NULL, 0, Image);
453
454 debug("Load Image File %r DP: <%s>", Status, ConvertDevicePathToText(pImgPath, FALSE, FALSE));
455
456 FreePool(pImgPath);
457
458 return Status;
459 }
460
461
462 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
463 {
464 UINTN i = 0;
465 UINTN Count = 0;
466 UINT64 DiskSize = 0;
467 MBR_HEAD *pMBR = NULL;
468 UINT8 *pBuffer = NULL;
469 EFI_HANDLE *Handles;
470 EFI_STATUS Status = EFI_SUCCESS;
471 EFI_BLOCK_IO_PROTOCOL *pBlockIo;
472
473 pBuffer = AllocatePool(2048);
474 if (!pBuffer)
475 {
476 return EFI_OUT_OF_RESOURCES;
477 }
478
479 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiBlockIoProtocolGuid,
480 NULL, &Count, &Handles);
481 if (EFI_ERROR(Status))
482 {
483 FreePool(pBuffer);
484 return Status;
485 }
486
487 for (i = 0; i < Count; i++)
488 {
489 Status = gBS->HandleProtocol(Handles[i], &gEfiBlockIoProtocolGuid, (VOID **)&pBlockIo);
490 if (EFI_ERROR(Status))
491 {
492 continue;
493 }
494
495 DiskSize = (pBlockIo->Media->LastBlock + 1) * pBlockIo->Media->BlockSize;
496 debug("This Disk size: %llu", DiskSize);
497 if (g_chain->os_param.vtoy_disk_size != DiskSize)
498 {
499 continue;
500 }
501
502 Status = pBlockIo->ReadBlocks(pBlockIo, pBlockIo->Media->MediaId, 0, 512, pBuffer);
503 if (EFI_ERROR(Status))
504 {
505 debug("ReadBlocks filed %r", Status);
506 continue;
507 }
508
509 if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0)
510 {
511 pMBR = (MBR_HEAD *)pBuffer;
512 if (pMBR->PartTbl[0].FsFlag != 0xEE)
513 {
514 if (pMBR->PartTbl[0].StartSectorId != 2048 ||
515 pMBR->PartTbl[1].SectorCount != 65536 ||
516 pMBR->PartTbl[1].StartSectorId != pMBR->PartTbl[0].StartSectorId + pMBR->PartTbl[0].SectorCount)
517 {
518 debug("Failed to check disk part table");
519 ventoy_warn_invalid_device();
520 }
521 }
522
523 gBlockData.RawBlockIoHandle = Handles[i];
524 gBlockData.pRawBlockIo = pBlockIo;
525 gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
526 (VOID **)&(gBlockData.pDiskDevPath),
527 ImageHandle,
528 Handles[i],
529 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
530
531 debug("Find Ventoy Disk Handle:%p DP:%s", Handles[i],
532 ConvertDevicePathToText(gBlockData.pDiskDevPath, FALSE, FALSE));
533 break;
534 }
535 }
536
537 FreePool(Handles);
538
539 if (i >= Count)
540 {
541 return EFI_NOT_FOUND;
542 }
543 else
544 {
545 return EFI_SUCCESS;
546 }
547 }
548
549
550 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk_fs(IN EFI_HANDLE ImageHandle)
551 {
552 UINTN i = 0;
553 UINTN Count = 0;
554 EFI_HANDLE Parent = NULL;
555 EFI_HANDLE *Handles = NULL;
556 EFI_STATUS Status = EFI_SUCCESS;
557 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
558 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
559
560 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
561 NULL, &Count, &Handles);
562 if (EFI_ERROR(Status))
563 {
564 return Status;
565 }
566
567 debug("ventoy_find_iso_disk_fs fs count:%u", Count);
568
569 for (i = 0; i < Count; i++)
570 {
571 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
572 if (EFI_ERROR(Status))
573 {
574 continue;
575 }
576
577 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
578 (VOID **)&pDevPath,
579 ImageHandle,
580 Handles[i],
581 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
582 if (EFI_ERROR(Status))
583 {
584 debug("Failed to open device path protocol %r", Status);
585 continue;
586 }
587
588 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
589 Parent = ventoy_get_parent_handle(pDevPath);
590
591 if (Parent == gBlockData.RawBlockIoHandle)
592 {
593 debug("Find ventoy disk fs");
594 gBlockData.DiskFsHandle = Handles[i];
595 gBlockData.pDiskFs = pFile;
596 gBlockData.pDiskFsDevPath = pDevPath;
597 break;
598 }
599 }
600
601 FreePool(Handles);
602
603 return EFI_SUCCESS;
604 }
605
606 STATIC EFI_STATUS EFIAPI ventoy_load_isoefi_driver(IN EFI_HANDLE ImageHandle)
607 {
608 EFI_HANDLE Image = NULL;
609 EFI_STATUS Status = EFI_SUCCESS;
610 CHAR16 LogVar[4] = L"5";
611
612 Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath,
613 gIso9660EfiDriverPath,
614 sizeof(gIso9660EfiDriverPath),
615 &Image);
616 debug("load iso efi driver status:%r", Status);
617
618 if (gDebugPrint)
619 {
620 gRT->SetVariable(L"FS_LOGGING", &gShellVariableGuid,
621 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
622 sizeof(LogVar), LogVar);
623 }
624
625 gRT->SetVariable(L"FS_NAME_NOCASE", &gShellVariableGuid,
626 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
627 sizeof(LogVar), LogVar);
628
629 gBlockData.IsoDriverImage = Image;
630 Status = gBS->StartImage(Image, NULL, NULL);
631 debug("Start iso efi driver status:%r", Status);
632
633 return EFI_SUCCESS;
634 }
635
636 STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
637 {
638 UINT32 i = 0;
639 UINT32 old_cnt = 0;
640 UINTN size = 0;
641 UINT8 chksum = 0;
642 const char *pEnv = NULL;
643 CHAR16 *pPos = NULL;
644 CHAR16 *pCmdLine = NULL;
645 EFI_STATUS Status = EFI_SUCCESS;
646 ventoy_grub_param *pGrubParam = NULL;
647 EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL;
648 ventoy_chain_head *chain = NULL;
649
650 Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo);
651 if (EFI_ERROR(Status))
652 {
653 VtoyDebug("Failed to handle load image protocol %r", Status);
654 return Status;
655 }
656
657 pCmdLine = (CHAR16 *)AllocatePool(pImageInfo->LoadOptionsSize + 4);
658 SetMem(pCmdLine, pImageInfo->LoadOptionsSize + 4, 0);
659 CopyMem(pCmdLine, pImageInfo->LoadOptions, pImageInfo->LoadOptionsSize);
660
661 if (StrStr(pCmdLine, L"debug"))
662 {
663 gDebugPrint = TRUE;
664 }
665
666 if (StrStr(pCmdLine, L"dotefi"))
667 {
668 gDotEfiBoot = TRUE;
669 }
670
671 if (StrStr(pCmdLine, L"isoefi=on"))
672 {
673 gLoadIsoEfi = TRUE;
674 }
675
676 pPos = StrStr(pCmdLine, L"FirstTry=@");
677 if (pPos)
678 {
679 pPos += StrLen(L"FirstTry=");
680 for (i = 0; i < ARRAY_SIZE(gFirstTryBootFile); i++, pPos++)
681 {
682 if (*pPos != L' ' && *pPos != L'\t' && *pPos)
683 {
684 gFirstTryBootFile[i] = (*pPos == '@') ? '\\' : *pPos;
685 }
686 else
687 {
688 break;
689 }
690 }
691
692 gEfiBootFileName[0] = gFirstTryBootFile;
693 gBootFileStartIndex = 0;
694 }
695
696 debug("cmdline:<%s>", pCmdLine);
697
698 if (gFirstTryBootFile[0])
699 {
700 debug("First Try:<%s>", gFirstTryBootFile);
701 }
702
703 pPos = StrStr(pCmdLine, L"env_param=");
704 if (!pPos)
705 {
706 return EFI_INVALID_PARAMETER;
707 }
708
709 pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param="));
710 grub_env_set = pGrubParam->grub_env_set;
711 grub_env_get = pGrubParam->grub_env_get;
712 pEnv = grub_env_get("VTOY_CHKDEV_RESULT_STRING");
713 if (!pEnv)
714 {
715 return EFI_INVALID_PARAMETER;
716 }
717
718 if (pEnv[0] != '0' || pEnv[1] != 0)
719 {
720 ventoy_warn_invalid_device();
721 return EFI_INVALID_PARAMETER;
722 }
723
724 g_file_replace_list = &pGrubParam->file_replace;
725 old_cnt = g_file_replace_list->old_file_cnt;
726 debug("file replace: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
727 g_file_replace_list->magic,
728 g_file_replace_list->new_file_virtual_id,
729 old_cnt,
730 old_cnt > 0 ? g_file_replace_list->old_file_name[0] : "",
731 old_cnt > 1 ? g_file_replace_list->old_file_name[1] : "",
732 old_cnt > 2 ? g_file_replace_list->old_file_name[2] : "",
733 old_cnt > 3 ? g_file_replace_list->old_file_name[3] : ""
734 );
735
736 pPos = StrStr(pCmdLine, L"mem:");
737 chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
738
739 pPos = StrStr(pPos, L"size:");
740 size = StrDecimalToUintn(pPos + 5);
741
742 debug("memory addr:%p size:%lu", chain, size);
743
744 if (StrStr(pCmdLine, L"sector512"))
745 {
746 gSector512Mode = TRUE;
747 }
748
749 if (StrStr(pCmdLine, L"memdisk"))
750 {
751 g_iso_data_buf = (UINT8 *)chain + sizeof(ventoy_chain_head);
752 g_iso_buf_size = size - sizeof(ventoy_chain_head);
753 debug("memdisk mode iso_buf_size:%u", g_iso_buf_size);
754
755 g_chain = chain;
756 gMemdiskMode = TRUE;
757 }
758 else
759 {
760 debug("This is normal mode");
761 g_chain = AllocatePool(size);
762 CopyMem(g_chain, chain, size);
763
764 g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset);
765 g_img_chunk_num = g_chain->img_chunk_num;
766 g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset);
767 g_override_chunk_num = g_chain->override_chunk_num;
768 g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset);
769 g_virt_chunk_num = g_chain->virt_chunk_num;
770
771 g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
772
773 /* Workaround for Windows & ISO9660 */
774 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
775 {
776 g_fixup_iso9660_secover_enable = TRUE;
777 }
778
779 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
780 {
781 g_hook_keyboard = TRUE;
782 }
783
784 debug("internal param: secover:%u keyboard:%u", g_fixup_iso9660_secover_enable, g_hook_keyboard);
785
786 for (i = 0; i < sizeof(ventoy_os_param); i++)
787 {
788 chksum += *((UINT8 *)(&(g_chain->os_param)) + i);
789 }
790
791 if (gDebugPrint)
792 {
793 debug("os param checksum: 0x%x %a", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
794 }
795
796 ventoy_update_image_location(&(g_chain->os_param));
797
798 if (gDebugPrint)
799 {
800 ventoy_dump_chain(g_chain);
801 }
802 }
803
804 g_fix_windows_1st_cdrom_issue = FALSE;
805 if (ventoy_chain_windows == g_os_param_reserved[2] ||
806 ventoy_chain_wim == g_os_param_reserved[2])
807 {
808 if (ventoy_is_cdrom_dp_exist())
809 {
810 debug("fixup the 1st cdrom influences when boot windows ...");
811 g_fix_windows_1st_cdrom_issue = TRUE;
812 }
813 }
814
815 ventoy_debug_pause();
816
817 FreePool(pCmdLine);
818 return EFI_SUCCESS;
819 }
820
821 EFI_STATUS EFIAPI ventoy_clean_env(VOID)
822 {
823 FreePool(g_sector_flag);
824 g_sector_flag_num = 0;
825
826 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
827 {
828 gBS->UnloadImage(gBlockData.IsoDriverImage);
829 }
830
831 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
832
833 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
834 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
835 &gEfiDevicePathProtocolGuid, gBlockData.Path,
836 NULL);
837
838 ventoy_delete_variable();
839
840 if (g_chain->os_param.vtoy_img_location_addr)
841 {
842 FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr);
843 }
844
845 FreePool(g_chain);
846
847 return EFI_SUCCESS;
848 }
849
850 STATIC EFI_STATUS ventoy_hook_start(VOID)
851 {
852 /* don't add debug print in this function */
853
854 if (g_fix_windows_1st_cdrom_issue)
855 {
856 ventoy_hook_1st_cdrom_start();
857 }
858
859 /* let this the last */
860 if (g_hook_keyboard)
861 {
862 ventoy_hook_keyboard_start();
863 }
864
865 return EFI_SUCCESS;
866 }
867
868 STATIC EFI_STATUS ventoy_hook_stop(VOID)
869 {
870 /* don't add debug print in this function */
871
872 if (g_fix_windows_1st_cdrom_issue)
873 {
874 ventoy_hook_1st_cdrom_stop();
875 }
876
877 /* let this the last */
878 if (g_hook_keyboard)
879 {
880 ventoy_hook_keyboard_stop();
881 }
882
883 return EFI_SUCCESS;
884 }
885
886 EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
887 {
888 UINTN t = 0;
889 UINTN i = 0;
890 UINTN j = 0;
891 UINTN Find = 0;
892 UINTN Count = 0;
893 EFI_HANDLE Image = NULL;
894 EFI_HANDLE *Handles = NULL;
895 EFI_STATUS Status = EFI_SUCCESS;
896 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
897 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
898
899 for (t = 0; t < 3; t++)
900 {
901 Count = 0;
902 Handles = NULL;
903
904 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
905 NULL, &Count, &Handles);
906 if (EFI_ERROR(Status))
907 {
908 return Status;
909 }
910
911 debug("ventoy_boot fs count:%u", Count);
912
913 for (i = 0; i < Count; i++)
914 {
915 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
916 if (EFI_ERROR(Status))
917 {
918 continue;
919 }
920
921 debug("FS:%u Protocol:%p OpenVolume:%p", i, pFile, pFile->OpenVolume);
922
923 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
924 (VOID **)&pDevPath,
925 ImageHandle,
926 Handles[i],
927 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
928 if (EFI_ERROR(Status))
929 {
930 debug("Failed to open device path protocol %r", Status);
931 continue;
932 }
933
934 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
935 if (CompareMem(gBlockData.Path, pDevPath, gBlockData.DevicePathCompareLen))
936 {
937 debug("Not ventoy disk file system");
938 continue;
939 }
940
941 for (j = gBootFileStartIndex; j < ARRAY_SIZE(gEfiBootFileName); j++)
942 {
943 Status = ventoy_load_image(ImageHandle, pDevPath, gEfiBootFileName[j],
944 StrSize(gEfiBootFileName[j]), &Image);
945 if (EFI_SUCCESS == Status)
946 {
947 break;
948 }
949 debug("Failed to load image %r <%s>", Status, gEfiBootFileName[j]);
950 }
951
952 if (j >= ARRAY_SIZE(gEfiBootFileName))
953 {
954 continue;
955 }
956
957 Find++;
958 debug("Find boot file, now try to boot .....");
959 ventoy_debug_pause();
960
961 if (gDebugPrint)
962 {
963 gST->ConIn->Reset(gST->ConIn, FALSE);
964 }
965
966 if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC)
967 {
968 ventoy_wrapper_push_openvolume(pFile->OpenVolume);
969 pFile->OpenVolume = ventoy_wrapper_open_volume;
970 }
971
972 ventoy_hook_start();
973 /* can't add debug print here */
974 //ventoy_wrapper_system();
975 Status = gBS->StartImage(Image, NULL, NULL);
976 ventoy_hook_stop();
977
978 if (EFI_ERROR(Status))
979 {
980 debug("Failed to start image %r", Status);
981 sleep(3);
982 gBS->UnloadImage(Image);
983 break;
984 }
985 }
986
987 FreePool(Handles);
988
989 if (Find == 0)
990 {
991 if (gDotEfiBoot)
992 {
993 break;
994 }
995
996 debug("Fs not found, now wait and retry...");
997 sleep(2);
998 }
999 }
1000
1001 if (Find == 0)
1002 {
1003 return EFI_NOT_FOUND;
1004 }
1005
1006 return EFI_SUCCESS;
1007 }
1008
1009 EFI_STATUS EFIAPI VentoyEfiMain
1010 (
1011 IN EFI_HANDLE ImageHandle,
1012 IN EFI_SYSTEM_TABLE *SystemTable
1013 )
1014 {
1015 EFI_STATUS Status = EFI_SUCCESS;
1016 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *Protocol;
1017
1018 g_sector_flag_num = 512; /* initial value */
1019
1020 g_sector_flag = AllocatePool(g_sector_flag_num * sizeof(ventoy_sector_flag));
1021 if (NULL == g_sector_flag)
1022 {
1023 return EFI_OUT_OF_RESOURCES;
1024 }
1025
1026 Status = gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&Protocol);
1027 if (EFI_SUCCESS == Status)
1028 {
1029 g_con_simple_input_ex = Protocol;
1030 }
1031
1032 gST->ConOut->ClearScreen(gST->ConOut);
1033 ventoy_clear_input();
1034
1035 Status = ventoy_parse_cmdline(ImageHandle);
1036 if (EFI_ERROR(Status))
1037 {
1038 return Status;
1039 }
1040
1041 if (gMemdiskMode)
1042 {
1043 g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_iso_data_buf;
1044 g_ramdisk_param.DiskSize = (UINT64)g_iso_buf_size;
1045
1046 ventoy_save_ramdisk_param();
1047
1048 if (gLoadIsoEfi)
1049 {
1050 ventoy_find_iso_disk(ImageHandle);
1051 ventoy_find_iso_disk_fs(ImageHandle);
1052 ventoy_load_isoefi_driver(ImageHandle);
1053 }
1054
1055 ventoy_install_blockio(ImageHandle, g_iso_buf_size);
1056 ventoy_debug_pause();
1057
1058 Status = ventoy_boot(ImageHandle);
1059
1060 ventoy_delete_ramdisk_param();
1061
1062 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
1063 {
1064 gBS->UnloadImage(gBlockData.IsoDriverImage);
1065 }
1066
1067 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
1068 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
1069 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
1070 &gEfiDevicePathProtocolGuid, gBlockData.Path,
1071 NULL);
1072 }
1073 else
1074 {
1075 ventoy_save_variable();
1076 Status = ventoy_find_iso_disk(ImageHandle);
1077 if (!EFI_ERROR(Status))
1078 {
1079 if (gLoadIsoEfi)
1080 {
1081 ventoy_find_iso_disk_fs(ImageHandle);
1082 ventoy_load_isoefi_driver(ImageHandle);
1083 }
1084
1085 ventoy_debug_pause();
1086
1087 ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
1088
1089 ventoy_debug_pause();
1090
1091 Status = ventoy_boot(ImageHandle);
1092 }
1093
1094 ventoy_clean_env();
1095 }
1096
1097 if (FALSE == gDotEfiBoot)
1098 {
1099 if (EFI_NOT_FOUND == Status)
1100 {
1101 gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
1102 gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC L"!\r\n");
1103 sleep(30);
1104 }
1105 }
1106
1107 ventoy_clear_input();
1108 gST->ConOut->ClearScreen(gST->ConOut);
1109
1110 if (gDotEfiBoot && (EFI_NOT_FOUND == Status))
1111 {
1112 grub_env_set("vtoy_dotefi_retry", "YES");
1113 }
1114
1115 return EFI_SUCCESS;
1116 }
1117