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