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