forked from pbatard/uefi-ntfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboot.c
638 lines (558 loc) · 21 KB
/
boot.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/*
* uefi-ntfs: UEFI → NTFS/exFAT chain loader
* Copyright © 2014-2020 Pete Batard <[email protected]>
* With parts from GRUB © 2006-2015 Free Software Foundation, Inc.
* With parts from rEFInd © 2012-2016 Roderick W. Smith
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <efi.h>
#include <efilib.h>
#include <efistdarg.h>
#include <libsmbios.h>
#define FILE_INFO_SIZE (512 * sizeof(CHAR16))
#define NUM_RETRIES 1
#define DELAY 3 // delay before retry, in seconds
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(Array) (sizeof (Array) / sizeof ((Array)[0]))
#endif
EFI_HANDLE MainImageHandle = NULL;
// NB: FreePool(NULL) is perfectly valid
#define SafeFree(p) do { FreePool(p); p = NULL;} while(0)
#if defined(_M_X64) || defined(__x86_64__)
static CHAR16* Arch = L"x64";
static CHAR16* ArchName = L"64-bit x86";
#elif defined(_M_IX86) || defined(__i386__)
static CHAR16* Arch = L"ia32";
static CHAR16* ArchName = L"32-bit x86";
#elif defined (_M_ARM64) || defined(__aarch64__)
static CHAR16* Arch = L"aa64";
static CHAR16* ArchName = L"64-bit ARM";
#elif defined (_M_ARM) || defined(__arm__)
static CHAR16* Arch = L"arm";
static CHAR16* ArchName = L"32-bit ARM";
#else
# error Unsupported architecture
#endif
/*
* In addition to the standard %-based flags, Print() supports the following:
* %N Set output attribute to normal
* %H Set output attribute to highlight
* %E Set output attribute to error
* %B Set output attribute to blue color
* %V Set output attribute to green color
* %r Human readable version of a status code
*/
#define PrintInfo(fmt, ...) Print(L"[INFO] " fmt L"\n", ##__VA_ARGS__);
#define PrintWarning(fmt, ...) Print(L"%E[WARN] " fmt L"%N\n", ##__VA_ARGS__);
#define PrintError(fmt, ...) Print(L"%E[FAIL] " fmt L": [%d] %r%N\n", ##__VA_ARGS__, (Status&0x7FFFFFFF), Status);
/* Convenience debug function to display an hex dump of a buffer */
#if defined(_DEBUG)
static VOID DumpBufferHex(VOID * Buf, INTN Size)
{
UINT8* Buffer = (UINT8*)Buf;
INTN i, j, k;
CHAR16 Line[80] = L"";
for (i = 0; i < Size; i += 16) {
if (i != 0)
Print(L"%s\n", Line);
Line[0] = 0;
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L" %08x ", (UINTN)i);
for (j = 0, k = 0; k < 16; j++, k++) {
if (i + j < Size) {
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L"%02x", Buffer[i + j]);
} else {
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L" ");
}
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L" ");
}
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L" ");
for (j = 0, k = 0; k < 16; j++, k++) {
if (i + j < Size) {
if ((Buffer[i + j] < 32) || (Buffer[i + j] > 126)) {
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L".");
} else {
SPrint(&Line[StrLen(Line)], 80 - StrLen(Line), L"%c", Buffer[i + j]);
}
}
}
}
Print(L"%s\n", Line);
}
#endif
/* Return the device path node right before the end node */
static EFI_DEVICE_PATH* GetLastDevicePath(CONST EFI_DEVICE_PATH_PROTOCOL* dp)
{
EFI_DEVICE_PATH *next, *p;
if (IsDevicePathEnd(dp))
return NULL;
for (p = (EFI_DEVICE_PATH *) dp, next = NextDevicePathNode(p);
!IsDevicePathEnd(next);
p = next, next = NextDevicePathNode(next));
return p;
}
/*
* Get the parent device in an EFI_DEVICE_PATH
* Note: the returned device path is allocated and must be freed
*/
static EFI_DEVICE_PATH* GetParentDevice(CONST EFI_DEVICE_PATH* DevicePath)
{
EFI_DEVICE_PATH *dp, *ldp;
dp = DuplicateDevicePath((EFI_DEVICE_PATH*)DevicePath);
if (dp == NULL)
return NULL;
ldp = GetLastDevicePath(dp);
if (ldp == NULL)
return NULL;
ldp->Type = END_DEVICE_PATH_TYPE;
ldp->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
SetDevicePathNodeLength(ldp, sizeof (*ldp));
return dp;
}
/* Compare device paths */
static INTN CompareDevicePaths(CONST EFI_DEVICE_PATH *dp1, CONST EFI_DEVICE_PATH *dp2)
{
if (dp1 == NULL || dp2 == NULL)
return -1;
while (1) {
UINT8 type1, type2;
UINT8 subtype1, subtype2;
UINT16 len1, len2;
INTN ret;
type1 = DevicePathType(dp1);
type2 = DevicePathType(dp2);
if (type1 != type2)
return (int) type2 - (int) type1;
subtype1 = DevicePathSubType(dp1);
subtype2 = DevicePathSubType(dp2);
if (subtype1 != subtype2)
return (int) subtype1 - (int) subtype2;
len1 = DevicePathNodeLength(dp1);
len2 = DevicePathNodeLength(dp2);
if (len1 != len2)
return (int) len1 - (int) len2;
ret = CompareMem(dp1, dp2, len1);
if (ret != 0)
return ret;
if (IsDevicePathEnd(dp1))
break;
dp1 = (EFI_DEVICE_PATH*) ((char *)dp1 + len1);
dp2 = (EFI_DEVICE_PATH*) ((char *)dp2 + len2);
}
return 0;
}
/*
* Some UEFI firmwares have a *BROKEN* Unicode collation implementation
* so we must provide our own version of StriCmp for ASCII comparison...
*/
static CHAR16 _tolower(CONST CHAR16 c)
{
if(('A' <= c) && (c <= 'Z'))
return 'a' + (c - 'A');
return c;
}
static INTN _StriCmp(CONST CHAR16 *s1, CONST CHAR16 *s2)
{
while ((*s1 != L'\0') && (_tolower(*s1) == _tolower(*s2)))
s1++, s2++;
return (INTN)(*s1 - *s2);
}
/* Fix the case of a path by looking it up on the file system */
static EFI_STATUS SetPathCase(CONST EFI_FILE_HANDLE Root, CHAR16* Path)
{
EFI_FILE_HANDLE FileHandle = NULL;
EFI_FILE_INFO* FileInfo;
UINTN i, Len;
UINTN Size;
EFI_STATUS Status;
if ((Root == NULL) || (Path == NULL) || (Path[0] != L'\\'))
return EFI_INVALID_PARAMETER;
FileInfo = (EFI_FILE_INFO*)AllocatePool(FILE_INFO_SIZE);
if (FileInfo == NULL)
return EFI_OUT_OF_RESOURCES;
Len = StrLen(Path);
// Find the last backslash in the path
for (i = Len-1; (i != 0) && (Path[i] != L'\\'); i--);
if (i != 0) {
Path[i] = 0;
// Recursively fix the case
Status = SetPathCase(Root, Path);
if (EFI_ERROR(Status))
goto out;
}
Status = Root->Open(Root, &FileHandle, (i==0)?L"\\":Path, EFI_FILE_MODE_READ, 0);
if (EFI_ERROR(Status))
goto out;
do {
Size = FILE_INFO_SIZE;
ZeroMem(FileInfo, Size);
Status = FileHandle->Read(FileHandle, &Size, (VOID*)FileInfo);
if (EFI_ERROR(Status))
goto out;
if (_StriCmp(&Path[i+1], FileInfo->FileName) == 0) {
StrCpy(&Path[i+1], FileInfo->FileName);
Status = EFI_SUCCESS;
goto out;
}
Status = EFI_NOT_FOUND;
} while (Size != 0);
out:
Path[i] = L'\\';
if (FileHandle != NULL)
FileHandle->Close(FileHandle);
FreePool((VOID*)FileInfo);
return Status;
}
/* Get the driver name from a driver handle */
static CHAR16* GetDriverName(CONST EFI_HANDLE DriverHandle)
{
CHAR16 *DriverName;
EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2;
// Try EFI_COMPONENT_NAME2 protocol first
if ( (gBS->OpenProtocol(DriverHandle, &ComponentName2Protocol, (VOID**)&ComponentName2,
MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL) == EFI_SUCCESS) &&
(ComponentName2->GetDriverName(ComponentName2, (CHAR8*)"", &DriverName) == EFI_SUCCESS) )
return DriverName;
// Fallback to EFI_COMPONENT_NAME if that didn't work
if ( (gBS->OpenProtocol(DriverHandle, &ComponentNameProtocol, (VOID**)&ComponentName,
MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL) == EFI_SUCCESS) &&
(ComponentName->GetDriverName(ComponentName, (CHAR8*)"", &DriverName) == EFI_SUCCESS) )
return DriverName;
return L"(unknown driver)";
}
/*
* Some UEFI firmwares (like HPQ EFI from HP notebooks) have DiskIo protocols
* opened BY_DRIVER (by Partition driver in HP's case) even when no file system
* is produced from this DiskIo. This then blocks our FS driver from connecting
* and producing file systems.
* To fix it we disconnect drivers that connected to DiskIo BY_DRIVER if this
* is a partition volume and if those drivers did not produce file system.
*/
static VOID DisconnectBlockingDrivers(VOID) {
EFI_STATUS Status;
UINTN HandleCount = 0, Index, OpenInfoIndex, OpenInfoCount;
EFI_HANDLE *Handles = NULL;
CHAR16 *DevicePathString;
EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume;
EFI_BLOCK_IO_PROTOCOL *BlockIo;
EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo;
// Get all DiskIo handles
Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiDiskIoProtocolGuid, NULL, &HandleCount, &Handles);
if (EFI_ERROR(Status) || (HandleCount == 0))
return;
// Check every DiskIo handle
for (Index = 0; Index < HandleCount; Index++) {
// If this is not partition - skip it.
// This is then whole disk and DiskIo
// should be opened here BY_DRIVER by Partition driver
// to produce partition volumes.
Status = gBS->OpenProtocol(Handles[Index], &gEfiBlockIoProtocolGuid, (VOID**)&BlockIo,
MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (EFI_ERROR(Status))
continue;
if ((BlockIo->Media == NULL) || (!BlockIo->Media->LogicalPartition))
continue;
// If SimpleFileSystem is already produced - skip it, this is ok
Status = gBS->OpenProtocol(Handles[Index], &gEfiSimpleFileSystemProtocolGuid, (VOID**)&Volume,
MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (Status == EFI_SUCCESS)
continue;
DevicePathString = DevicePathToStr(DevicePathFromHandle(Handles[Index]));
// If no SimpleFileSystem on this handle but DiskIo is opened BY_DRIVER
// then disconnect this connection
Status = gBS->OpenProtocolInformation(Handles[Index], &gEfiDiskIoProtocolGuid, &OpenInfo, &OpenInfoCount);
if (EFI_ERROR(Status)) {
PrintWarning(L" Could not get DiskIo protocol for %s: %r", DevicePathString, Status);
FreePool(DevicePathString);
continue;
}
for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) {
if ((OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) == EFI_OPEN_PROTOCOL_BY_DRIVER) {
Status = gBS->DisconnectController(Handles[Index], OpenInfo[OpenInfoIndex].AgentHandle, NULL);
if (EFI_ERROR(Status)) {
PrintError(L" Could not disconnect '%s' on %s",
GetDriverName(OpenInfo[OpenInfoIndex].AgentHandle), DevicePathString);
} else {
PrintWarning(L" Disconnected '%s' on %s ",
GetDriverName(OpenInfo[OpenInfoIndex].AgentHandle), DevicePathString);
}
}
}
FreePool(DevicePathString);
FreePool(OpenInfo);
}
FreePool(Handles);
}
/*
* Query SMBIOS to display some info about the system hardware and UEFI firmware.
*/
static EFI_STATUS PrintSystemInfo(VOID)
{
EFI_STATUS Status;
SMBIOS_STRUCTURE_POINTER Smbios;
SMBIOS_STRUCTURE_TABLE* SmbiosTable;
SMBIOS3_STRUCTURE_TABLE* Smbios3Table;
UINT8 Found = 0, *Raw;
UINTN MaximumSize, ProcessedSize = 0;
PrintInfo(L"UEFI v%d.%d (%s, 0x%08X)", gST->Hdr.Revision >> 16, gST->Hdr.Revision & 0xFFFF,
gST->FirmwareVendor, gST->FirmwareRevision);
Status = LibGetSystemConfigurationTable(&SMBIOS3TableGuid, (VOID**)&Smbios3Table);
if (Status == EFI_SUCCESS) {
Smbios.Hdr = (SMBIOS_HEADER*)Smbios3Table->TableAddress;
MaximumSize = (UINTN)Smbios3Table->TableMaximumSize;
} else {
Status = LibGetSystemConfigurationTable(&SMBIOSTableGuid, (VOID**)&SmbiosTable);
if (EFI_ERROR(Status))
return EFI_NOT_FOUND;
Smbios.Hdr = (SMBIOS_HEADER*)(UINTN)SmbiosTable->TableAddress;
MaximumSize = (UINTN)SmbiosTable->TableLength;
}
while ((Smbios.Hdr->Type != 0x7F) && (Found < 2)) {
Raw = Smbios.Raw;
if (Smbios.Hdr->Type == 0) {
PrintInfo(L"%a %a", LibGetSmbiosString(&Smbios, Smbios.Type0->Vendor),
LibGetSmbiosString(&Smbios, Smbios.Type0->BiosVersion));
Found++;
}
if (Smbios.Hdr->Type == 1) {
PrintInfo(L"%a %a", LibGetSmbiosString(&Smbios, Smbios.Type1->Manufacturer),
LibGetSmbiosString(&Smbios, Smbios.Type1->ProductName));
Found++;
}
LibGetSmbiosString(&Smbios, -1);
ProcessedSize += (UINTN)Smbios.Raw - (UINTN)Raw;
if (ProcessedSize > MaximumSize) {
PrintWarning(L"Aborting system report due to noncompliant SMBIOS");
return EFI_ABORTED;
}
}
return EFI_SUCCESS;
}
/*
* Application entry-point
* NB: This must be set to 'efi_main' for gnu-efi crt0 compatibility
*/
EFI_STATUS efi_main(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
{
CONST CHAR16* FsName[] = { L"NTFS", L"exFAT" };
CONST CHAR16* DriverName[] = { L"ntfs", L"exfat" };
CHAR16 DriverPath[64], LoaderPath[64];
EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
EFI_STATUS Status;
EFI_DEVICE_PATH *DevicePath, *ParentDevicePath = NULL, *BootDiskPath = NULL;
EFI_DEVICE_PATH *BootPartitionPath = NULL;
EFI_HANDLE *Handles = NULL, DriverHandle, DriverHandleList[2];
EFI_SIMPLE_FILE_SYSTEM_PROTOCOL* Volume;
EFI_FILE_SYSTEM_VOLUME_LABEL_INFO* VolumeInfo;
EFI_FILE_HANDLE Root;
EFI_BLOCK_IO_PROTOCOL *BlockIo;
CHAR8* Buffer, FsMagic[2][8] = {
{ 'N', 'T', 'F', 'S', ' ', ' ', ' ', ' '} ,
{ 'E', 'X', 'F', 'A', 'T', ' ', ' ', ' '} };
UINTN Index, FsType = 0, Try, Event, HandleCount = 0;
BOOLEAN SameDevice;
MainImageHandle = ImageHandle;
InitializeLib(ImageHandle, SystemTable);
Print(L"\n%H*** UEFI:NTFS (%s) ***%N\n\n", Arch);
PrintSystemInfo();
Status = gBS->OpenProtocol(MainImageHandle, &gEfiLoadedImageProtocolGuid,
(VOID**)&LoadedImage, MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (EFI_ERROR(Status)) {
PrintError(L"Unable to access boot image interface");
goto out;
}
PrintInfo(L"Disconnecting potentially blocking drivers");
DisconnectBlockingDrivers();
// Identify our boot partition and disk
BootPartitionPath = DevicePathFromHandle(LoadedImage->DeviceHandle);
BootDiskPath = GetParentDevice(BootPartitionPath);
PrintInfo(L"Searching for target partition on boot disk:");
PrintInfo(L" %D", BootDiskPath);
// Enumerate all disk handles
Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiDiskIoProtocolGuid,
NULL, &HandleCount, &Handles);
if (EFI_ERROR(Status)) {
PrintError(L" Failed to list disks");
goto out;
}
// Go through the partitions and find the one that has the USB Disk we booted from
// as parent and that isn't the FAT32 boot partition
for (Index = 0; Index < HandleCount; Index++) {
// Note: The Device Path obtained from DevicePathFromHandle() should NOT be freed!
DevicePath = DevicePathFromHandle(Handles[Index]);
// Eliminate the partition we booted from
if (CompareDevicePaths(DevicePath, BootPartitionPath) == 0)
continue;
// Ensure that we look for the NTFS/exFAT partition on the same device.
ParentDevicePath = GetParentDevice(DevicePath);
SameDevice = (CompareDevicePaths(BootDiskPath, ParentDevicePath) == 0);
SafeFree(ParentDevicePath);
// The check breaks QEMU testing (since we can't easily emulate
// a multipart device on the fly) so only do it for release.
#if !defined(_DEBUG)
if (!SameDevice)
continue;
#else
(VOID)SameDevice; // Silence a MinGW warning
#endif
// Read the first block of the partition and look for the FS magic in the OEM ID
Status = gBS->OpenProtocol(Handles[Index], &gEfiBlockIoProtocolGuid,
(VOID**)&BlockIo, MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (EFI_ERROR(Status))
continue;
Buffer = (CHAR8*)AllocatePool(BlockIo->Media->BlockSize);
if (Buffer == NULL)
continue;
Status = BlockIo->ReadBlocks(BlockIo, BlockIo->Media->MediaId, 0, BlockIo->Media->BlockSize, Buffer);
for (FsType = 0; (FsType < ARRAY_SIZE(FsName)) &&
(CompareMem(&Buffer[3], FsMagic[FsType], sizeof(FsMagic[FsType])) != 0); FsType++);
FreePool(Buffer);
if (EFI_ERROR(Status))
continue;
if (FsType < ARRAY_SIZE(FsName))
break;
}
if (Index >= HandleCount) {
Status = EFI_NOT_FOUND;
PrintError(L" Could not locate target partition");
goto out;
}
PrintInfo(L"Found %s target partition:", FsName[FsType]);
PrintInfo(L" %D", DevicePath);
PrintInfo(L"Checking if target partition needs the %s service", FsName[FsType]);
// Test for presence of file system protocol (to see if there already is
// a filesystem driver servicing this partition)
Status = gBS->OpenProtocol(Handles[Index], &gEfiSimpleFileSystemProtocolGuid,
(VOID**)&Volume, MainImageHandle, NULL, EFI_OPEN_PROTOCOL_TEST_PROTOCOL);
if (Status == EFI_SUCCESS) {
// A filesystem driver is already set => no need to start ours
PrintWarning(L" An %s service is already loaded", FsName[FsType]);
} else if (Status == EFI_UNSUPPORTED) {
// Partition is not being serviced by a file system driver yet => start ours
PrintInfo(L"Starting %s partition service:", FsName[FsType]);
// Use 'rufus' in the driver path, so that we don't accidentally latch onto a user driver
SPrint(DriverPath, ARRAY_SIZE(DriverPath), L"\\efi\\rufus\\%s_%s.efi", DriverName[FsType], Arch);
DevicePath = FileDevicePath(LoadedImage->DeviceHandle, DriverPath);
if (DevicePath == NULL) {
Status = EFI_DEVICE_ERROR;
PrintError(L" Unable to set path for '%s'", DriverPath);
goto out;
}
// Attempt to load the driver.
Status = gBS->LoadImage(FALSE, MainImageHandle, DevicePath, NULL, 0, &DriverHandle);
SafeFree(DevicePath);
if (EFI_ERROR(Status)) {
PrintError(L" Unable to load driver '%s'", DriverPath);
goto out;
}
// NB: Some HP firmwares refuse to start drivers that are not of type 'EFI Boot
// System Driver'. For instance, a driver of type 'EFI Runtime Driver' produces
// a 'Load Error' on StartImage() with these firmwares => check the type.
Status = gBS->OpenProtocol(DriverHandle, &gEfiLoadedImageProtocolGuid,
(VOID**)&LoadedImage, MainImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (EFI_ERROR(Status)) {
PrintError(L" Unable to access driver interface");
goto out;
}
if (LoadedImage->ImageCodeType != EfiBootServicesCode) {
Status = EFI_LOAD_ERROR;
PrintError(L" '%s' is not a Boot System Driver", DriverPath);
goto out;
}
// Load was a success - attempt to start the driver
Status = gBS->StartImage(DriverHandle, NULL, NULL);
if (EFI_ERROR(Status)) {
PrintError(L" Unable to start driver");
goto out;
}
PrintInfo(L" %s", GetDriverName(DriverHandle));
// Calling ConnectController() on a handle, with a NULL-terminated list of
// drivers will start all the drivers from the list that can service it
DriverHandleList[0] = DriverHandle;
DriverHandleList[1] = NULL;
Status = gBS->ConnectController(Handles[Index], DriverHandleList, NULL, TRUE);
if (EFI_ERROR(Status)) {
PrintError(L" Could not start %s partition service", FsName[FsType]);
goto out;
}
} else {
PrintError(L" Could not check for %s service", FsName[FsType]);
goto out;
}
// Our target file system is case sensitive, so we need to figure out the
// case sensitive version of the following
SPrint(LoaderPath, ARRAY_SIZE(LoaderPath), L"\\efi\\boot\\boot%s.efi", Arch);
PrintInfo(L"Opening target %s partition:", FsName[FsType]);
// Open the the volume, with retry, as we may need to wait before poking
// at the FS content, in case the system is slow to start our service...
for (Try = 0; ; Try++) {
Status = gBS->OpenProtocol(Handles[Index], &gEfiSimpleFileSystemProtocolGuid,
(VOID**)&Volume, MainImageHandle, NULL, EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL);
if (!EFI_ERROR(Status))
break;
PrintError(L" Could not open partition");
if (Try >= NUM_RETRIES)
goto out;
PrintWarning(L" Waiting %d seconds before retrying...", DELAY);
gBS->Stall(DELAY * 1000000);
}
// Open the root directory
Root = NULL;
Status = Volume->OpenVolume(Volume, &Root);
if ((EFI_ERROR(Status)) || (Root == NULL)) {
PrintError(L" Could not open Root directory");
goto out;
}
// Get the volume label while we're at it
VolumeInfo = LibFileSystemVolumeLabelInfo(Root);
if ((VolumeInfo->VolumeLabel != NULL) && (VolumeInfo->VolumeLabel[0] != 0))
PrintInfo(L" Volume label is '%s'", VolumeInfo->VolumeLabel);
PrintInfo(L"This system uses %s UEFI => searching for %s EFI bootloader", ArchName, Arch);
// This next call corrects the casing to the required one
Status = SetPathCase(Root, LoaderPath);
if (EFI_ERROR(Status)) {
PrintError(L" Could not locate '%s'", &LoaderPath[1]);
goto out;
}
// At this stage, our DevicePath is the partition we are after
PrintInfo(L"Launching '%s'...", &LoaderPath[1]);
// Now attempt to chain load bootx64.efi on the target partition
DevicePath = FileDevicePath(Handles[Index], LoaderPath);
if (DevicePath == NULL) {
Status = EFI_DEVICE_ERROR;
PrintError(L" Could not create path");
goto out;
}
Status = gBS->LoadImage(FALSE, ImageHandle, DevicePath, NULL, 0, &DriverHandle);
SafeFree(DevicePath);
if (EFI_ERROR(Status)) {
PrintError(L" Load failure");
goto out;
}
Status = gBS->StartImage(DriverHandle, NULL, NULL);
if (EFI_ERROR(Status))
PrintError(L" Start failure");
out:
SafeFree(ParentDevicePath);
SafeFree(BootDiskPath);
SafeFree(Handles);
// Wait for a keystroke on error
if (EFI_ERROR(Status)) {
Print(L"%H\nPress any key to exit.%N\n");
gST->ConIn->Reset(gST->ConIn, FALSE);
gST->BootServices->WaitForEvent(1, &gST->ConIn->WaitForKey, &Event);
}
return Status;
}