]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c
Fix typo in BuildVentoyFromSource.txt (#580)
[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 officially 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 continue to boot after 15 seconds ...... ");
415
416 sleep(15);
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 }
722
723 g_file_replace_list = &pGrubParam->file_replace;
724 old_cnt = g_file_replace_list->old_file_cnt;
725 debug("file replace: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
726 g_file_replace_list->magic,
727 g_file_replace_list->new_file_virtual_id,
728 old_cnt,
729 old_cnt > 0 ? g_file_replace_list->old_file_name[0] : "",
730 old_cnt > 1 ? g_file_replace_list->old_file_name[1] : "",
731 old_cnt > 2 ? g_file_replace_list->old_file_name[2] : "",
732 old_cnt > 3 ? g_file_replace_list->old_file_name[3] : ""
733 );
734
735 pPos = StrStr(pCmdLine, L"mem:");
736 chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
737
738 pPos = StrStr(pPos, L"size:");
739 size = StrDecimalToUintn(pPos + 5);
740
741 debug("memory addr:%p size:%lu", chain, size);
742
743 if (StrStr(pCmdLine, L"sector512"))
744 {
745 gSector512Mode = TRUE;
746 }
747
748 if (StrStr(pCmdLine, L"memdisk"))
749 {
750 g_iso_data_buf = (UINT8 *)chain + sizeof(ventoy_chain_head);
751 g_iso_buf_size = size - sizeof(ventoy_chain_head);
752 debug("memdisk mode iso_buf_size:%u", g_iso_buf_size);
753
754 g_chain = chain;
755 gMemdiskMode = TRUE;
756 }
757 else
758 {
759 debug("This is normal mode");
760 g_chain = AllocatePool(size);
761 CopyMem(g_chain, chain, size);
762
763 g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset);
764 g_img_chunk_num = g_chain->img_chunk_num;
765 g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset);
766 g_override_chunk_num = g_chain->override_chunk_num;
767 g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset);
768 g_virt_chunk_num = g_chain->virt_chunk_num;
769
770 g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
771
772 /* Workaround for Windows & ISO9660 */
773 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
774 {
775 g_fixup_iso9660_secover_enable = TRUE;
776 }
777
778 if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
779 {
780 g_hook_keyboard = TRUE;
781 }
782
783 debug("internal param: secover:%u keyboard:%u", g_fixup_iso9660_secover_enable, g_hook_keyboard);
784
785 for (i = 0; i < sizeof(ventoy_os_param); i++)
786 {
787 chksum += *((UINT8 *)(&(g_chain->os_param)) + i);
788 }
789
790 if (gDebugPrint)
791 {
792 debug("os param checksum: 0x%x %a", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS");
793 }
794
795 ventoy_update_image_location(&(g_chain->os_param));
796
797 if (gDebugPrint)
798 {
799 ventoy_dump_chain(g_chain);
800 }
801 }
802
803 g_fix_windows_1st_cdrom_issue = FALSE;
804 if (ventoy_chain_windows == g_os_param_reserved[2] ||
805 ventoy_chain_wim == g_os_param_reserved[2])
806 {
807 if (ventoy_is_cdrom_dp_exist())
808 {
809 debug("fixup the 1st cdrom influences when boot windows ...");
810 g_fix_windows_1st_cdrom_issue = TRUE;
811 }
812 }
813
814 ventoy_debug_pause();
815
816 FreePool(pCmdLine);
817 return EFI_SUCCESS;
818 }
819
820 EFI_STATUS EFIAPI ventoy_clean_env(VOID)
821 {
822 FreePool(g_sector_flag);
823 g_sector_flag_num = 0;
824
825 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
826 {
827 gBS->UnloadImage(gBlockData.IsoDriverImage);
828 }
829
830 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
831
832 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
833 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
834 &gEfiDevicePathProtocolGuid, gBlockData.Path,
835 NULL);
836
837 ventoy_delete_variable();
838
839 if (g_chain->os_param.vtoy_img_location_addr)
840 {
841 FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr);
842 }
843
844 FreePool(g_chain);
845
846 return EFI_SUCCESS;
847 }
848
849 STATIC EFI_STATUS ventoy_hook_start(VOID)
850 {
851 /* don't add debug print in this function */
852
853 if (g_fix_windows_1st_cdrom_issue)
854 {
855 ventoy_hook_1st_cdrom_start();
856 }
857
858 /* let this the last */
859 if (g_hook_keyboard)
860 {
861 ventoy_hook_keyboard_start();
862 }
863
864 return EFI_SUCCESS;
865 }
866
867 STATIC EFI_STATUS ventoy_hook_stop(VOID)
868 {
869 /* don't add debug print in this function */
870
871 if (g_fix_windows_1st_cdrom_issue)
872 {
873 ventoy_hook_1st_cdrom_stop();
874 }
875
876 /* let this the last */
877 if (g_hook_keyboard)
878 {
879 ventoy_hook_keyboard_stop();
880 }
881
882 return EFI_SUCCESS;
883 }
884
885 EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
886 {
887 UINTN t = 0;
888 UINTN i = 0;
889 UINTN j = 0;
890 UINTN Find = 0;
891 UINTN Count = 0;
892 EFI_HANDLE Image = NULL;
893 EFI_HANDLE *Handles = NULL;
894 EFI_STATUS Status = EFI_SUCCESS;
895 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL;
896 EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL;
897
898 for (t = 0; t < 3; t++)
899 {
900 Count = 0;
901 Handles = NULL;
902
903 Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid,
904 NULL, &Count, &Handles);
905 if (EFI_ERROR(Status))
906 {
907 return Status;
908 }
909
910 debug("ventoy_boot fs count:%u", Count);
911
912 for (i = 0; i < Count; i++)
913 {
914 Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile);
915 if (EFI_ERROR(Status))
916 {
917 continue;
918 }
919
920 debug("FS:%u Protocol:%p OpenVolume:%p", i, pFile, pFile->OpenVolume);
921
922 Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid,
923 (VOID **)&pDevPath,
924 ImageHandle,
925 Handles[i],
926 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
927 if (EFI_ERROR(Status))
928 {
929 debug("Failed to open device path protocol %r", Status);
930 continue;
931 }
932
933 debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE));
934 if (CompareMem(gBlockData.Path, pDevPath, gBlockData.DevicePathCompareLen))
935 {
936 debug("Not ventoy disk file system");
937 continue;
938 }
939
940 for (j = gBootFileStartIndex; j < ARRAY_SIZE(gEfiBootFileName); j++)
941 {
942 Status = ventoy_load_image(ImageHandle, pDevPath, gEfiBootFileName[j],
943 StrSize(gEfiBootFileName[j]), &Image);
944 if (EFI_SUCCESS == Status)
945 {
946 break;
947 }
948 debug("Failed to load image %r <%s>", Status, gEfiBootFileName[j]);
949 }
950
951 if (j >= ARRAY_SIZE(gEfiBootFileName))
952 {
953 continue;
954 }
955
956 Find++;
957 debug("Find boot file, now try to boot .....");
958 ventoy_debug_pause();
959
960 if (gDebugPrint)
961 {
962 gST->ConIn->Reset(gST->ConIn, FALSE);
963 }
964
965 if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC)
966 {
967 ventoy_wrapper_push_openvolume(pFile->OpenVolume);
968 pFile->OpenVolume = ventoy_wrapper_open_volume;
969 }
970
971 ventoy_hook_start();
972 /* can't add debug print here */
973 //ventoy_wrapper_system();
974 Status = gBS->StartImage(Image, NULL, NULL);
975 ventoy_hook_stop();
976
977 if (EFI_ERROR(Status))
978 {
979 debug("Failed to start image %r", Status);
980 sleep(3);
981 gBS->UnloadImage(Image);
982 break;
983 }
984 }
985
986 FreePool(Handles);
987
988 if (Find == 0)
989 {
990 if (gDotEfiBoot)
991 {
992 break;
993 }
994
995 debug("Fs not found, now wait and retry...");
996 sleep(2);
997 }
998 }
999
1000 if (Find == 0)
1001 {
1002 return EFI_NOT_FOUND;
1003 }
1004
1005 return EFI_SUCCESS;
1006 }
1007
1008 EFI_STATUS EFIAPI VentoyEfiMain
1009 (
1010 IN EFI_HANDLE ImageHandle,
1011 IN EFI_SYSTEM_TABLE *SystemTable
1012 )
1013 {
1014 EFI_STATUS Status = EFI_SUCCESS;
1015 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *Protocol;
1016
1017 g_sector_flag_num = 512; /* initial value */
1018
1019 g_sector_flag = AllocatePool(g_sector_flag_num * sizeof(ventoy_sector_flag));
1020 if (NULL == g_sector_flag)
1021 {
1022 return EFI_OUT_OF_RESOURCES;
1023 }
1024
1025 Status = gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&Protocol);
1026 if (EFI_SUCCESS == Status)
1027 {
1028 g_con_simple_input_ex = Protocol;
1029 }
1030
1031 gST->ConOut->ClearScreen(gST->ConOut);
1032 ventoy_clear_input();
1033
1034 Status = ventoy_parse_cmdline(ImageHandle);
1035 if (EFI_ERROR(Status))
1036 {
1037 return Status;
1038 }
1039
1040 if (gMemdiskMode)
1041 {
1042 g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_iso_data_buf;
1043 g_ramdisk_param.DiskSize = (UINT64)g_iso_buf_size;
1044
1045 ventoy_save_ramdisk_param();
1046
1047 if (gLoadIsoEfi)
1048 {
1049 ventoy_find_iso_disk(ImageHandle);
1050 ventoy_find_iso_disk_fs(ImageHandle);
1051 ventoy_load_isoefi_driver(ImageHandle);
1052 }
1053
1054 ventoy_install_blockio(ImageHandle, g_iso_buf_size);
1055 ventoy_debug_pause();
1056
1057 Status = ventoy_boot(ImageHandle);
1058
1059 ventoy_delete_ramdisk_param();
1060
1061 if (gLoadIsoEfi && gBlockData.IsoDriverImage)
1062 {
1063 gBS->UnloadImage(gBlockData.IsoDriverImage);
1064 }
1065
1066 gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
1067 gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
1068 &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
1069 &gEfiDevicePathProtocolGuid, gBlockData.Path,
1070 NULL);
1071 }
1072 else
1073 {
1074 ventoy_save_variable();
1075 Status = ventoy_find_iso_disk(ImageHandle);
1076 if (!EFI_ERROR(Status))
1077 {
1078 if (gLoadIsoEfi)
1079 {
1080 ventoy_find_iso_disk_fs(ImageHandle);
1081 ventoy_load_isoefi_driver(ImageHandle);
1082 }
1083
1084 ventoy_debug_pause();
1085
1086 ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
1087
1088 ventoy_debug_pause();
1089
1090 Status = ventoy_boot(ImageHandle);
1091 }
1092
1093 ventoy_clean_env();
1094 }
1095
1096 if (FALSE == gDotEfiBoot)
1097 {
1098 if (EFI_NOT_FOUND == Status)
1099 {
1100 gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
1101 gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC L"!\r\n");
1102 sleep(30);
1103 }
1104 }
1105
1106 ventoy_clear_input();
1107 gST->ConOut->ClearScreen(gST->ConOut);
1108
1109 if (gDotEfiBoot && (EFI_NOT_FOUND == Status))
1110 {
1111 grub_env_set("vtoy_dotefi_retry", "YES");
1112 }
1113
1114 return EFI_SUCCESS;
1115 }
1116