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