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