]> code.delx.au - refind/blob - refind/lib.c
Version supports Secure Boot/MOK verification of binaries.
[refind] / refind / lib.c
1 /*
2 * refit/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), a copy of which must be distributed
41 * with this source code or binaries made from it.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
51
52 #ifdef __MAKEWITH_GNUEFI
53 #define EfiReallocatePool ReallocatePool
54 #else
55 #define LibLocateHandle gBS->LocateHandleBuffer
56 #define DevicePathProtocol gEfiDevicePathProtocolGuid
57 #define BlockIoProtocol gEfiBlockIoProtocolGuid
58 #define LibFileSystemInfo EfiLibFileSystemInfo
59 #define LibOpenRoot EfiLibOpenRoot
60 EFI_DEVICE_PATH EndDevicePath[] = {
61 {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
62 };
63
64 //#define EndDevicePath DevicePath
65 #endif
66
67 // variables
68
69 EFI_HANDLE SelfImageHandle;
70 EFI_LOADED_IMAGE *SelfLoadedImage;
71 EFI_FILE *SelfRootDir;
72 EFI_FILE *SelfDir;
73 CHAR16 *SelfDirPath;
74
75 REFIT_VOLUME *SelfVolume = NULL;
76 REFIT_VOLUME **Volumes = NULL;
77 UINTN VolumesCount = 0;
78
79 // Maximum size for disk sectors
80 #define SECTOR_SIZE 4096
81
82 // Default names for volume badges (mini-icon to define disk type) and icons
83 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
84 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
85
86 // functions
87
88 static EFI_STATUS FinishInitRefitLib(VOID);
89
90 static VOID UninitVolumes(VOID);
91
92 //
93 // self recognition stuff
94 //
95
96 // Converts forward slashes to backslashes, removes duplicate slashes, and
97 // removes slashes from the end of the pathname.
98 // Necessary because some (buggy?) EFI implementations produce "\/" strings
99 // in pathnames, because some user inputs can produce duplicate directory
100 // separators, and because we want consistent start and end slashes for
101 // directory comparisons. A special case: If the PathName refers to root,
102 // return "/", since some firmware implementations flake out if this
103 // isn't present.
104 VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
105 CHAR16 *NewName;
106 UINTN i, FinalChar = 0;
107 BOOLEAN LastWasSlash = FALSE;
108
109 NewName = AllocateZeroPool(sizeof(CHAR16) * (StrLen(PathName) + 4));
110 if (NewName != NULL) {
111 for (i = 0; i < StrLen(PathName); i++) {
112 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
113 if ((!LastWasSlash) /* && (FinalChar != 0) */)
114 NewName[FinalChar++] = L'\\';
115 LastWasSlash = TRUE;
116 } else {
117 if (FinalChar == 0) {
118 NewName[FinalChar++] = L'\\';
119 }
120 NewName[FinalChar++] = PathName[i];
121 LastWasSlash = FALSE;
122 } // if/else
123 } // for
124 NewName[FinalChar] = 0;
125 if ((FinalChar > 1) && (NewName[FinalChar - 1] == L'\\'))
126 NewName[--FinalChar] = 0;
127 if (FinalChar == 0) {
128 NewName[0] = L'\\';
129 NewName[1] = 0;
130 }
131 // Copy the transformed name back....
132 StrCpy(PathName, NewName);
133 FreePool(NewName);
134 } // if allocation OK
135 } // CleanUpPathNameSlashes()
136
137 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
138 {
139 EFI_STATUS Status;
140 CHAR16 *DevicePathAsString;
141
142 SelfImageHandle = ImageHandle;
143 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
144 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
145 return EFI_LOAD_ERROR;
146
147 // find the current directory
148 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
149 CleanUpPathNameSlashes(DevicePathAsString);
150 MyFreePool(SelfDirPath);
151 SelfDirPath = FindPath(DevicePathAsString);
152 MyFreePool(DevicePathAsString);
153
154 return FinishInitRefitLib();
155 }
156
157 // called before running external programs to close open file handles
158 VOID UninitRefitLib(VOID)
159 {
160 UninitVolumes();
161
162 if (SelfDir != NULL) {
163 refit_call1_wrapper(SelfDir->Close, SelfDir);
164 SelfDir = NULL;
165 }
166
167 if (SelfRootDir != NULL) {
168 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
169 SelfRootDir = NULL;
170 }
171 }
172
173 // called after running external programs to re-open file handles
174 EFI_STATUS ReinitRefitLib(VOID)
175 {
176 ReinitVolumes();
177
178 if ((ST->Hdr.Revision >> 16) == 1) {
179 // Below two lines were in rEFIt, but seem to cause system crashes or
180 // reboots when launching OSes after returning from programs on most
181 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
182 // installation volume" (see the next function) when returning from
183 // programs when these two lines are removed, and it often crashes
184 // when returning from a program or when launching a second program
185 // with these lines removed. Therefore, the preceding if() statement
186 // executes these lines only on EFIs with a major version number of 1
187 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
188 // of hardware on which to test is limited, though, so this may be the
189 // wrong test, or there may be a better way to fix this problem.
190 // TODO: Figure out cause of above weirdness and fix it more
191 // reliably!
192 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
193 SelfRootDir = SelfVolume->RootDir;
194 } // if
195
196 return FinishInitRefitLib();
197 }
198
199 static EFI_STATUS FinishInitRefitLib(VOID)
200 {
201 EFI_STATUS Status;
202
203 if (SelfRootDir == NULL) {
204 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
205 if (SelfRootDir == NULL) {
206 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
207 return EFI_LOAD_ERROR;
208 }
209 }
210
211 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
212 if (CheckFatalError(Status, L"while opening our installation directory"))
213 return EFI_LOAD_ERROR;
214
215 return EFI_SUCCESS;
216 }
217
218 //
219 // list functions
220 //
221
222 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
223 {
224 UINTN AllocateCount;
225
226 *ElementCount = InitialElementCount;
227 if (*ElementCount > 0) {
228 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
229 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
230 } else {
231 *ListPtr = NULL;
232 }
233 }
234
235 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
236 {
237 UINTN AllocateCount;
238
239 if ((*ElementCount & 7) == 0) {
240 AllocateCount = *ElementCount + 8;
241 if (*ElementCount == 0)
242 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
243 else
244 *ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
245 }
246 (*ListPtr)[*ElementCount] = NewElement;
247 (*ElementCount)++;
248 } /* VOID AddListElement() */
249
250 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
251 {
252 UINTN i;
253
254 if ((*ElementCount > 0) && (**ListPtr != NULL)) {
255 for (i = 0; i < *ElementCount; i++) {
256 // TODO: call a user-provided routine for each element here
257 MyFreePool((*ListPtr)[i]);
258 }
259 MyFreePool(*ListPtr);
260 }
261 } // VOID FreeList()
262
263 //
264 // firmware device path discovery
265 //
266
267 static UINT8 LegacyLoaderMediaPathData[] = {
268 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
269 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
270 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
271 };
272 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
273
274 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
275 {
276 EFI_STATUS Status;
277 UINTN HandleCount = 0;
278 UINTN HandleIndex, HardcodedIndex;
279 EFI_HANDLE *Handles;
280 EFI_HANDLE Handle;
281 UINTN PathCount = 0;
282 UINTN PathIndex;
283 EFI_LOADED_IMAGE *LoadedImage;
284 EFI_DEVICE_PATH *DevicePath;
285 BOOLEAN Seen;
286
287 MaxPaths--; // leave space for the terminating NULL pointer
288
289 // get all LoadedImage handles
290 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL, &HandleCount, &Handles);
291 if (CheckError(Status, L"while listing LoadedImage handles")) {
292 if (HardcodedPathList) {
293 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
294 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
295 }
296 PathList[PathCount] = NULL;
297 return;
298 }
299 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
300 Handle = Handles[HandleIndex];
301
302 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
303 if (EFI_ERROR(Status))
304 continue; // This can only happen if the firmware scewed up, ignore it.
305
306 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
307 if (EFI_ERROR(Status))
308 continue; // This happens, ignore it.
309
310 // Only grab memory range nodes
311 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
312 continue;
313
314 // Check if we have this device path in the list already
315 // WARNING: This assumes the first node in the device path is unique!
316 Seen = FALSE;
317 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
318 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
319 continue;
320 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
321 Seen = TRUE;
322 break;
323 }
324 }
325 if (Seen)
326 continue;
327
328 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
329 }
330 MyFreePool(Handles);
331
332 if (HardcodedPathList) {
333 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
334 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
335 }
336 PathList[PathCount] = NULL;
337 }
338
339 //
340 // volume functions
341 //
342
343 static VOID ScanVolumeBootcode(IN OUT REFIT_VOLUME *Volume, OUT BOOLEAN *Bootable)
344 {
345 EFI_STATUS Status;
346 UINT8 SectorBuffer[SECTOR_SIZE];
347 UINTN i;
348 MBR_PARTITION_INFO *MbrTable;
349 BOOLEAN MbrTableFound;
350
351 Volume->HasBootCode = FALSE;
352 Volume->OSIconName = NULL;
353 Volume->OSName = NULL;
354 *Bootable = FALSE;
355
356 if (Volume->BlockIO == NULL)
357 return;
358 if (Volume->BlockIO->Media->BlockSize > SECTOR_SIZE)
359 return; // our buffer is too small...
360
361 // look at the boot sector (this is used for both hard disks and El Torito images!)
362 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
363 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
364 Volume->BlockIOOffset, SECTOR_SIZE, SectorBuffer);
365 if (!EFI_ERROR(Status)) {
366
367 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55 && SectorBuffer[0] != 0) {
368 *Bootable = TRUE;
369 Volume->HasBootCode = TRUE;
370 }
371
372 // detect specific boot codes
373 if (CompareMem(SectorBuffer + 2, "LILO", 4) == 0 ||
374 CompareMem(SectorBuffer + 6, "LILO", 4) == 0 ||
375 CompareMem(SectorBuffer + 3, "SYSLINUX", 8) == 0 ||
376 FindMem(SectorBuffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
377 Volume->HasBootCode = TRUE;
378 Volume->OSIconName = L"linux";
379 Volume->OSName = L"Linux";
380
381 } else if (FindMem(SectorBuffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
382 Volume->HasBootCode = TRUE;
383 Volume->OSIconName = L"grub,linux";
384 Volume->OSName = L"Linux";
385
386 // // Below doesn't produce a bootable entry, so commented out for the moment....
387 // // GRUB in BIOS boot partition:
388 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
389 // Volume->HasBootCode = TRUE;
390 // Volume->OSIconName = L"grub,linux";
391 // Volume->OSName = L"Linux";
392 // Volume->VolName = L"BIOS Boot Partition";
393 // *Bootable = TRUE;
394
395 } else if ((*((UINT32 *)(SectorBuffer + 502)) == 0 &&
396 *((UINT32 *)(SectorBuffer + 506)) == 50000 &&
397 *((UINT16 *)(SectorBuffer + 510)) == 0xaa55) ||
398 FindMem(SectorBuffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
399 Volume->HasBootCode = TRUE;
400 Volume->OSIconName = L"freebsd";
401 Volume->OSName = L"FreeBSD";
402
403 } else if (FindMem(SectorBuffer, 512, "!Loading", 8) >= 0 ||
404 FindMem(SectorBuffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
405 Volume->HasBootCode = TRUE;
406 Volume->OSIconName = L"openbsd";
407 Volume->OSName = L"OpenBSD";
408
409 } else if (FindMem(SectorBuffer, 512, "Not a bootxx image", 18) >= 0 ||
410 *((UINT32 *)(SectorBuffer + 1028)) == 0x7886b6d1) {
411 Volume->HasBootCode = TRUE;
412 Volume->OSIconName = L"netbsd";
413 Volume->OSName = L"NetBSD";
414
415 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
416 Volume->HasBootCode = TRUE;
417 Volume->OSIconName = L"win";
418 Volume->OSName = L"Windows";
419
420 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
421 Volume->HasBootCode = TRUE;
422 Volume->OSIconName = L"winvista,win";
423 Volume->OSName = L"Windows";
424
425 } else if (FindMem(SectorBuffer, 512, "CPUBOOT SYS", 11) >= 0 ||
426 FindMem(SectorBuffer, 512, "KERNEL SYS", 11) >= 0) {
427 Volume->HasBootCode = TRUE;
428 Volume->OSIconName = L"freedos";
429 Volume->OSName = L"FreeDOS";
430
431 } else if (FindMem(SectorBuffer, 512, "OS2LDR", 6) >= 0 ||
432 FindMem(SectorBuffer, 512, "OS2BOOT", 7) >= 0) {
433 Volume->HasBootCode = TRUE;
434 Volume->OSIconName = L"ecomstation";
435 Volume->OSName = L"eComStation";
436
437 } else if (FindMem(SectorBuffer, 512, "Be Boot Loader", 14) >= 0) {
438 Volume->HasBootCode = TRUE;
439 Volume->OSIconName = L"beos";
440 Volume->OSName = L"BeOS";
441
442 } else if (FindMem(SectorBuffer, 512, "yT Boot Loader", 14) >= 0) {
443 Volume->HasBootCode = TRUE;
444 Volume->OSIconName = L"zeta,beos";
445 Volume->OSName = L"ZETA";
446
447 } else if (FindMem(SectorBuffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
448 FindMem(SectorBuffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
449 Volume->HasBootCode = TRUE;
450 Volume->OSIconName = L"haiku,beos";
451 Volume->OSName = L"Haiku";
452
453 }
454
455 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
456 // need to fix AddLegacyEntry in main.c.
457
458 #if REFIT_DEBUG > 0
459 Print(L" Result of bootcode detection: %s %s (%s)\n",
460 Volume->HasBootCode ? L"bootable" : L"non-bootable",
461 Volume->OSName, Volume->OSIconName);
462 #endif
463
464 // dummy FAT boot sector (created by OS X's newfs_msdos)
465 if (FindMem(SectorBuffer, 512, "Non-system disk", 15) >= 0)
466 Volume->HasBootCode = FALSE;
467
468 // dummy FAT boot sector (created by Linux's mkdosfs)
469 if (FindMem(SectorBuffer, 512, "This is not a bootable disk", 27) >= 0)
470 Volume->HasBootCode = FALSE;
471
472 // dummy FAT boot sector (created by Windows)
473 if (FindMem(SectorBuffer, 512, "Press any key to restart", 24) >= 0)
474 Volume->HasBootCode = FALSE;
475
476 // check for MBR partition table
477 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55) {
478 MbrTableFound = FALSE;
479 MbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
480 for (i = 0; i < 4; i++)
481 if (MbrTable[i].StartLBA && MbrTable[i].Size)
482 MbrTableFound = TRUE;
483 for (i = 0; i < 4; i++)
484 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
485 MbrTableFound = FALSE;
486 if (MbrTableFound) {
487 Volume->MbrPartitionTable = AllocatePool(4 * 16);
488 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
489 }
490 }
491
492 } else {
493 #if REFIT_DEBUG > 0
494 CheckError(Status, L"while reading boot sector");
495 #endif
496 }
497 }
498
499 // default volume badge icon based on disk kind
500 static VOID ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME *Volume)
501 {
502 switch (Volume->DiskKind) {
503 case DISK_KIND_INTERNAL:
504 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
505 break;
506 case DISK_KIND_EXTERNAL:
507 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
508 break;
509 case DISK_KIND_OPTICAL:
510 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
511 break;
512 } // switch()
513 }
514
515 VOID ScanVolume(IN OUT REFIT_VOLUME *Volume)
516 {
517 EFI_STATUS Status;
518 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
519 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
520 EFI_HANDLE WholeDiskHandle;
521 UINTN PartialLength;
522 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
523 BOOLEAN Bootable;
524
525 // get device path
526 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
527 #if REFIT_DEBUG > 0
528 if (Volume->DevicePath != NULL) {
529 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
530 #if REFIT_DEBUG >= 2
531 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
532 #endif
533 }
534 #endif
535
536 Volume->DiskKind = DISK_KIND_INTERNAL; // default
537
538 // get block i/o
539 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
540 if (EFI_ERROR(Status)) {
541 Volume->BlockIO = NULL;
542 Print(L"Warning: Can't get BlockIO protocol.\n");
543 } else {
544 if (Volume->BlockIO->Media->BlockSize == 2048)
545 Volume->DiskKind = DISK_KIND_OPTICAL;
546 }
547
548 // scan for bootcode and MBR table
549 Bootable = FALSE;
550 ScanVolumeBootcode(Volume, &Bootable);
551
552 // detect device type
553 DevicePath = Volume->DevicePath;
554 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
555 NextDevicePath = NextDevicePathNode(DevicePath);
556
557 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
558 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
559 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
560 DevicePathSubType(DevicePath) == MSG_1394_DP ||
561 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
562 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
563 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
564 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
565 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
566 Bootable = TRUE;
567 }
568
569 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
570 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
571 // TODO: also check for Boot Camp GUID
572 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
573 }
574
575 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
576 // make a device path for the whole device
577 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
578 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
579 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
580 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
581
582 // get the handle for that path
583 RemainingDevicePath = DiskDevicePath;
584 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
585 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
586 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
587 FreePool(DiskDevicePath);
588
589 if (!EFI_ERROR(Status)) {
590 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
591
592 // get the device path for later
593 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
594 if (!EFI_ERROR(Status)) {
595 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
596 }
597
598 // look at the BlockIO protocol
599 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
600 if (!EFI_ERROR(Status)) {
601
602 // check the media block size
603 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
604 Volume->DiskKind = DISK_KIND_OPTICAL;
605
606 } else {
607 Volume->WholeDiskBlockIO = NULL;
608 //CheckError(Status, L"from HandleProtocol");
609 }
610 } //else
611 // CheckError(Status, L"from LocateDevicePath");
612 }
613
614 DevicePath = NextDevicePath;
615 } // while
616
617 if (!Bootable) {
618 #if REFIT_DEBUG > 0
619 if (Volume->HasBootCode)
620 Print(L" Volume considered non-bootable, but boot code is present\n");
621 #endif
622 Volume->HasBootCode = FALSE;
623 }
624
625 // default volume icon based on disk kind
626 ScanVolumeDefaultIcon(Volume);
627
628 // open the root directory of the volume
629 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
630 if (Volume->RootDir == NULL) {
631 Volume->IsReadable = FALSE;
632 return;
633 } else {
634 Volume->IsReadable = TRUE;
635 }
636
637 // get volume name
638 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
639 if (FileSystemInfoPtr != NULL) {
640 Volume->VolName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
641 FreePool(FileSystemInfoPtr);
642 }
643
644 if (Volume->VolName == NULL) {
645 Volume->VolName = StrDuplicate(L"Unknown");
646 }
647 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
648 // - name from bytes 3 to 10 of the boot sector
649 // - partition number
650 // - name derived from file system type or partition type
651
652 // get custom volume icon if present
653 if (FileExists(Volume->RootDir, VOLUME_BADGE_NAME))
654 Volume->VolBadgeImage = LoadIcns(Volume->RootDir, VOLUME_BADGE_NAME, 32);
655 if (FileExists(Volume->RootDir, VOLUME_ICON_NAME)) {
656 Volume->VolIconImage = LoadIcns(Volume->RootDir, VOLUME_ICON_NAME, 128);
657 }
658 } // ScanVolume()
659
660 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
661 {
662 EFI_STATUS Status;
663 REFIT_VOLUME *Volume;
664 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
665 UINTN i;
666 UINTN LogicalPartitionIndex = 4;
667 UINT8 SectorBuffer[512];
668 BOOLEAN Bootable;
669 MBR_PARTITION_INFO *EMbrTable;
670
671 ExtBase = MbrEntry->StartLBA;
672
673 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
674 // read current EMBR
675 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
676 WholeDiskVolume->BlockIO,
677 WholeDiskVolume->BlockIO->Media->MediaId,
678 ExtCurrent, 512, SectorBuffer);
679 if (EFI_ERROR(Status))
680 break;
681 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
682 break;
683 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
684
685 // scan logical partitions in this EMBR
686 NextExtCurrent = 0;
687 for (i = 0; i < 4; i++) {
688 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
689 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
690 break;
691 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
692 // set next ExtCurrent
693 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
694 break;
695 } else {
696
697 // found a logical partition
698 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
699 Volume->DiskKind = WholeDiskVolume->DiskKind;
700 Volume->IsMbrPartition = TRUE;
701 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
702 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
703 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
704 Volume->BlockIO = WholeDiskVolume->BlockIO;
705 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
706 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
707
708 Bootable = FALSE;
709 ScanVolumeBootcode(Volume, &Bootable);
710 if (!Bootable)
711 Volume->HasBootCode = FALSE;
712
713 ScanVolumeDefaultIcon(Volume);
714
715 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
716
717 }
718 }
719 }
720 }
721
722 VOID ScanVolumes(VOID)
723 {
724 EFI_STATUS Status;
725 UINTN HandleCount = 0;
726 UINTN HandleIndex;
727 EFI_HANDLE *Handles;
728 REFIT_VOLUME *Volume, *WholeDiskVolume;
729 UINTN VolumeIndex, VolumeIndex2;
730 MBR_PARTITION_INFO *MbrTable;
731 UINTN PartitionIndex;
732 UINT8 *SectorBuffer1, *SectorBuffer2;
733 UINTN SectorSum, i;
734
735 MyFreePool(Volumes);
736 Volumes = NULL;
737 VolumesCount = 0;
738
739 // get all filesystem handles
740 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
741 // was: &FileSystemProtocol
742 if (Status == EFI_NOT_FOUND) {
743 return; // no filesystems. strange, but true...
744 }
745 if (CheckError(Status, L"while listing all file systems"))
746 return;
747
748 // first pass: collect information about all handles
749 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
750 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
751 Volume->DeviceHandle = Handles[HandleIndex];
752 ScanVolume(Volume);
753
754 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
755
756 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
757 SelfVolume = Volume;
758 }
759 MyFreePool(Handles);
760
761 if (SelfVolume == NULL)
762 Print(L"WARNING: SelfVolume not found");
763
764 // second pass: relate partitions and whole disk devices
765 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
766 Volume = Volumes[VolumeIndex];
767 // check MBR partition table for extended partitions
768 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
769 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
770 Volume->MbrPartitionTable != NULL) {
771 MbrTable = Volume->MbrPartitionTable;
772 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
773 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
774 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
775 }
776 }
777 }
778
779 // search for corresponding whole disk volume entry
780 WholeDiskVolume = NULL;
781 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
782 Volume->BlockIO != Volume->WholeDiskBlockIO) {
783 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
784 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
785 Volumes[VolumeIndex2]->BlockIOOffset == 0)
786 WholeDiskVolume = Volumes[VolumeIndex2];
787 }
788 }
789
790 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
791 // check if this volume is one of the partitions in the table
792 MbrTable = WholeDiskVolume->MbrPartitionTable;
793 SectorBuffer1 = AllocatePool(512);
794 SectorBuffer2 = AllocatePool(512);
795 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
796 // check size
797 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
798 continue;
799
800 // compare boot sector read through offset vs. directly
801 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
802 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
803 Volume->BlockIOOffset, 512, SectorBuffer1);
804 if (EFI_ERROR(Status))
805 break;
806 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
807 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
808 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
809 if (EFI_ERROR(Status))
810 break;
811 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
812 continue;
813 SectorSum = 0;
814 for (i = 0; i < 512; i++)
815 SectorSum += SectorBuffer1[i];
816 if (SectorSum < 1000)
817 continue;
818
819 // TODO: mark entry as non-bootable if it is an extended partition
820
821 // now we're reasonably sure the association is correct...
822 Volume->IsMbrPartition = TRUE;
823 Volume->MbrPartitionIndex = PartitionIndex;
824 if (Volume->VolName == NULL) {
825 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
826 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
827 }
828 break;
829 }
830
831 MyFreePool(SectorBuffer1);
832 MyFreePool(SectorBuffer2);
833 }
834
835 }
836 } /* VOID ScanVolumes() */
837
838 static VOID UninitVolumes(VOID)
839 {
840 REFIT_VOLUME *Volume;
841 UINTN VolumeIndex;
842
843 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
844 Volume = Volumes[VolumeIndex];
845
846 if (Volume->RootDir != NULL) {
847 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
848 Volume->RootDir = NULL;
849 }
850
851 Volume->DeviceHandle = NULL;
852 Volume->BlockIO = NULL;
853 Volume->WholeDiskBlockIO = NULL;
854 }
855 }
856
857 VOID ReinitVolumes(VOID)
858 {
859 EFI_STATUS Status;
860 REFIT_VOLUME *Volume;
861 UINTN VolumeIndex;
862 EFI_DEVICE_PATH *RemainingDevicePath;
863 EFI_HANDLE DeviceHandle, WholeDiskHandle;
864
865 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
866 Volume = Volumes[VolumeIndex];
867
868 if (Volume->DevicePath != NULL) {
869 // get the handle for that path
870 RemainingDevicePath = Volume->DevicePath;
871 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
872
873 if (!EFI_ERROR(Status)) {
874 Volume->DeviceHandle = DeviceHandle;
875
876 // get the root directory
877 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
878
879 } else
880 CheckError(Status, L"from LocateDevicePath");
881 }
882
883 if (Volume->WholeDiskDevicePath != NULL) {
884 // get the handle for that path
885 RemainingDevicePath = Volume->WholeDiskDevicePath;
886 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
887
888 if (!EFI_ERROR(Status)) {
889 // get the BlockIO protocol
890 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
891 if (EFI_ERROR(Status)) {
892 Volume->WholeDiskBlockIO = NULL;
893 CheckError(Status, L"from HandleProtocol");
894 }
895 } else
896 CheckError(Status, L"from LocateDevicePath");
897 }
898 }
899 }
900
901 //
902 // file and dir functions
903 //
904
905 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
906 {
907 EFI_STATUS Status;
908 EFI_FILE_HANDLE TestFile;
909
910 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
911 if (Status == EFI_SUCCESS) {
912 refit_call1_wrapper(TestFile->Close, TestFile);
913 return TRUE;
914 }
915 return FALSE;
916 }
917
918 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
919 {
920 EFI_STATUS Status;
921 VOID *Buffer;
922 UINTN LastBufferSize, BufferSize;
923 INTN IterCount;
924
925 for (;;) {
926
927 // free pointer from last call
928 if (*DirEntry != NULL) {
929 FreePool(*DirEntry);
930 *DirEntry = NULL;
931 }
932
933 // read next directory entry
934 LastBufferSize = BufferSize = 256;
935 Buffer = AllocatePool(BufferSize);
936 for (IterCount = 0; ; IterCount++) {
937 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
938 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
939 break;
940 if (BufferSize <= LastBufferSize) {
941 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
942 BufferSize = LastBufferSize * 2;
943 #if REFIT_DEBUG > 0
944 } else {
945 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
946 #endif
947 }
948 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
949 LastBufferSize = BufferSize;
950 }
951 if (EFI_ERROR(Status)) {
952 FreePool(Buffer);
953 break;
954 }
955
956 // check for end of listing
957 if (BufferSize == 0) { // end of directory listing
958 FreePool(Buffer);
959 break;
960 }
961
962 // entry is ready to be returned
963 *DirEntry = (EFI_FILE_INFO *)Buffer;
964
965 // filter results
966 if (FilterMode == 1) { // only return directories
967 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
968 break;
969 } else if (FilterMode == 2) { // only return files
970 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
971 break;
972 } else // no filter or unknown filter -> return everything
973 break;
974
975 }
976 return Status;
977 }
978
979 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
980 {
981 if (RelativePath == NULL) {
982 DirIter->LastStatus = EFI_SUCCESS;
983 DirIter->DirHandle = BaseDir;
984 DirIter->CloseDirHandle = FALSE;
985 } else {
986 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
987 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
988 }
989 DirIter->LastFileInfo = NULL;
990 }
991
992 #ifndef __MAKEWITH_GNUEFI
993 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
994
995 static EFI_STATUS
996 InitializeUnicodeCollationProtocol (VOID)
997 {
998 EFI_STATUS Status;
999
1000 if (mUnicodeCollation != NULL) {
1001 return EFI_SUCCESS;
1002 }
1003
1004 //
1005 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1006 // instances first and then select one which support English language.
1007 // Current implementation just pick the first instance.
1008 //
1009 Status = gBS->LocateProtocol (
1010 &gEfiUnicodeCollation2ProtocolGuid,
1011 NULL,
1012 (VOID **) &mUnicodeCollation
1013 );
1014 if (EFI_ERROR(Status)) {
1015 Status = gBS->LocateProtocol (
1016 &gEfiUnicodeCollationProtocolGuid,
1017 NULL,
1018 (VOID **) &mUnicodeCollation
1019 );
1020
1021 }
1022 return Status;
1023 }
1024
1025 static BOOLEAN
1026 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1027 {
1028 if (!mUnicodeCollation) {
1029 InitializeUnicodeCollationProtocol();
1030 }
1031 if (mUnicodeCollation)
1032 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1033 return FALSE; // Shouldn't happen
1034 }
1035
1036 static VOID StrLwr (IN OUT CHAR16 *Str) {
1037 if (!mUnicodeCollation) {
1038 InitializeUnicodeCollationProtocol();
1039 }
1040 if (mUnicodeCollation)
1041 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1042 }
1043
1044 #endif
1045
1046 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1047 OUT EFI_FILE_INFO **DirEntry)
1048 {
1049 BOOLEAN KeepGoing = TRUE;
1050 UINTN i;
1051 CHAR16 *OnePattern;
1052
1053 if (DirIter->LastFileInfo != NULL) {
1054 FreePool(DirIter->LastFileInfo);
1055 DirIter->LastFileInfo = NULL;
1056 }
1057
1058 if (EFI_ERROR(DirIter->LastStatus))
1059 return FALSE; // stop iteration
1060
1061 do {
1062 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1063 if (EFI_ERROR(DirIter->LastStatus))
1064 return FALSE;
1065 if (DirIter->LastFileInfo == NULL) // end of listing
1066 return FALSE;
1067 if (FilePattern != NULL) {
1068 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1069 KeepGoing = FALSE;
1070 i = 0;
1071 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1072 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1073 KeepGoing = FALSE;
1074 } // while
1075 // else continue loop
1076 } else
1077 break;
1078 } while (KeepGoing);
1079
1080 *DirEntry = DirIter->LastFileInfo;
1081 return TRUE;
1082 }
1083
1084 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1085 {
1086 if (DirIter->LastFileInfo != NULL) {
1087 FreePool(DirIter->LastFileInfo);
1088 DirIter->LastFileInfo = NULL;
1089 }
1090 if (DirIter->CloseDirHandle)
1091 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1092 return DirIter->LastStatus;
1093 }
1094
1095 //
1096 // file name manipulation
1097 //
1098
1099 // Returns the filename portion (minus path name) of the
1100 // specified file
1101 CHAR16 * Basename(IN CHAR16 *Path)
1102 {
1103 CHAR16 *FileName;
1104 UINTN i;
1105
1106 FileName = Path;
1107
1108 if (Path != NULL) {
1109 for (i = StrLen(Path); i > 0; i--) {
1110 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1111 FileName = Path + i;
1112 break;
1113 }
1114 }
1115 }
1116
1117 return FileName;
1118 }
1119
1120 // Replaces a filename extension of ".efi" with the specified string
1121 // (Extension). If the input Path doesn't end in ".efi", Extension
1122 // is added to the existing filename.
1123 VOID ReplaceEfiExtension(IN OUT CHAR16 *Path, IN CHAR16 *Extension)
1124 {
1125 UINTN PathLen;
1126
1127 PathLen = StrLen(Path);
1128 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1129 if ((PathLen >= 4) && ((StriCmp(&Path[PathLen - 4], L".efi") == 0) || (StriCmp(&Path[PathLen - 4], L".EFI") == 0))) {
1130 Path[PathLen - 4] = 0;
1131 } // if
1132 StrCat(Path, Extension);
1133 } // VOID ReplaceEfiExtension()
1134
1135 //
1136 // memory string search
1137 //
1138
1139 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1140 {
1141 UINT8 *BufferPtr;
1142 UINTN Offset;
1143
1144 BufferPtr = Buffer;
1145 BufferLength -= SearchStringLength;
1146 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1147 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1148 return (INTN)Offset;
1149 }
1150
1151 return -1;
1152 }
1153
1154 // Performs a case-insensitive search of BigStr for SmallStr.
1155 // Returns TRUE if found, FALSE if not.
1156 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1157 CHAR16 *SmallCopy, *BigCopy;
1158 BOOLEAN Found = FALSE;
1159 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1160
1161 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1162 SmallCopy = StrDuplicate(SmallStr);
1163 BigCopy = StrDuplicate(BigStr);
1164 StrLwr(SmallCopy);
1165 StrLwr(BigCopy);
1166 SmallLen = StrLen(SmallCopy);
1167 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1168 while ((!Found) && (StartPoint < NumCompares)) {
1169 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1170 } // while
1171 MyFreePool(SmallCopy);
1172 MyFreePool(BigCopy);
1173 } // if
1174
1175 return (Found);
1176 } // BOOLEAN StriSubCmp()
1177
1178 // Merges two strings, creating a new one and returning a pointer to it.
1179 // If AddChar != 0, the specified character is placed between the two original
1180 // strings (unless the first string is NULL). The original input string
1181 // *First is de-allocated and replaced by the new merged string.
1182 // This is similar to StrCat, but safer and more flexible because
1183 // MergeStrings allocates memory that's the correct size for the
1184 // new merged string, so it can take a NULL *First and it cleans
1185 // up the old memory. It should *NOT* be used with a constant
1186 // *First, though....
1187 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1188 UINTN Length1 = 0, Length2 = 0;
1189 CHAR16* NewString;
1190
1191 if (*First != NULL)
1192 Length1 = StrLen(*First);
1193 if (Second != NULL)
1194 Length2 = StrLen(Second);
1195 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1196 if (NewString != NULL) {
1197 NewString[0] = L'\0';
1198 if (*First != NULL) {
1199 StrCat(NewString, *First);
1200 if (AddChar) {
1201 NewString[Length1] = AddChar;
1202 NewString[Length1 + 1] = 0;
1203 } // if (AddChar)
1204 } // if (*First != NULL)
1205 if (Second != NULL)
1206 StrCat(NewString, Second);
1207 MyFreePool(*First);
1208 *First = NewString;
1209 } else {
1210 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1211 } // if/else
1212 } // static CHAR16* MergeStrings()
1213
1214 // Takes an input pathname (*Path) and returns the part of the filename from
1215 // the final dot onwards, converted to lowercase. If the filename includes
1216 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1217 // The calling function is responsible for freeing the memory associated with
1218 // the return value.
1219 CHAR16 *FindExtension(IN CHAR16 *Path) {
1220 CHAR16 *Extension;
1221 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1222 UINTN i;
1223
1224 Extension = AllocateZeroPool(sizeof(CHAR16));
1225 if (Path) {
1226 i = StrLen(Path);
1227 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1228 if (Path[i] == L'.')
1229 Found = TRUE;
1230 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1231 FoundSlash = TRUE;
1232 if (!Found)
1233 i--;
1234 } // while
1235 if (Found) {
1236 MergeStrings(&Extension, &Path[i], 0);
1237 StrLwr(Extension);
1238 } // if (Found)
1239 } // if
1240 return (Extension);
1241 } // CHAR16 *FindExtension
1242
1243 // Takes an input pathname (*Path) and locates the final directory component
1244 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1245 // function returns the string 'foo'.
1246 // Assumes the pathname is separated with backslashes.
1247 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1248 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1249 CHAR16 *Found = NULL;
1250
1251 PathLength = StrLen(Path);
1252 // Find start & end of target element
1253 for (i = 0; i < PathLength; i++) {
1254 if (Path[i] == '\\') {
1255 StartOfElement = EndOfElement;
1256 EndOfElement = i;
1257 } // if
1258 } // for
1259 // Extract the target element
1260 if (EndOfElement > 0) {
1261 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1262 StartOfElement++;
1263 } // while
1264 EndOfElement--;
1265 if (EndOfElement >= StartOfElement) {
1266 CopyLength = EndOfElement - StartOfElement + 1;
1267 Found = StrDuplicate(&Path[StartOfElement]);
1268 if (Found != NULL)
1269 Found[CopyLength] = 0;
1270 } // if (EndOfElement >= StartOfElement)
1271 } // if (EndOfElement > 0)
1272 return (Found);
1273 } // CHAR16 *FindLastDirName
1274
1275 // Returns the directory portion of a pathname. For instance,
1276 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1277 // string 'EFI\foo'. The calling function is responsible for
1278 // freeing the returned string's memory.
1279 CHAR16 *FindPath(IN CHAR16* FullPath) {
1280 UINTN i, LastBackslash = 0;
1281 CHAR16 *PathOnly;
1282
1283 for (i = 0; i < StrLen(FullPath); i++) {
1284 if (FullPath[i] == '\\')
1285 LastBackslash = i;
1286 } // for
1287 PathOnly = StrDuplicate(FullPath);
1288 PathOnly[LastBackslash] = 0;
1289 return (PathOnly);
1290 }
1291
1292 // Splits an EFI device path into device and filename components. For instance, if InString is
1293 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
1294 // this function will truncate that input to
1295 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
1296 // and return bzImage-3.5.1.efi as its return value.
1297 // It does this by searching for the last ")" character in InString, copying everything
1298 // after that string (after some cleanup) as the return value, and truncating the original
1299 // input value.
1300 // If InString contains no ")" character, this function leaves the original input string
1301 // unmodified and returns a NULL value.
1302 static CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
1303 INTN i;
1304 CHAR16 *FileName = NULL;
1305 BOOLEAN Found = FALSE;
1306
1307 i = StrLen(InString) - 1;
1308 while ((i >= 0) && (!Found)) {
1309 if (InString[i] == L')') {
1310 Found = TRUE;
1311 FileName = StrDuplicate(&InString[i + 1]);
1312 CleanUpPathNameSlashes(FileName);
1313 InString[i + 1] = '\0';
1314 } // if
1315 i--;
1316 } // while
1317 return FileName;
1318 } // static CHAR16* SplitDeviceString()
1319
1320 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1321 // DeviceVolume, and returns that and the filename (*loader).
1322 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1323 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1324 UINTN i = 0;
1325 BOOLEAN Found = FALSE;
1326
1327 MyFreePool(*loader);
1328 MyFreePool(*DeviceVolume);
1329 *DeviceVolume = NULL;
1330 DeviceString = DevicePathToStr(loadpath);
1331 *loader = SplitDeviceString(DeviceString);
1332
1333 while ((i < VolumesCount) && (!Found)) {
1334 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1335 Temp = SplitDeviceString(VolumeDeviceString);
1336 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1337 Found = TRUE;
1338 *DeviceVolume = Volumes[i];
1339 }
1340 MyFreePool(Temp);
1341 MyFreePool(VolumeDeviceString);
1342 i++;
1343 } // while
1344
1345 MyFreePool(DeviceString);
1346 } // VOID FindVolumeAndFilename()
1347
1348 // Returns all the digits in the input string, including intervening
1349 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1350 // this function returns "3.3.4-7". If InString contains no digits,
1351 // the return value is NULL.
1352 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1353 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1354 CHAR16 *Found = NULL;
1355
1356 InLength = StartOfElement = StrLen(InString);
1357 // Find start & end of target element
1358 for (i = 0; i < InLength; i++) {
1359 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1360 if (StartOfElement > i)
1361 StartOfElement = i;
1362 if (EndOfElement < i)
1363 EndOfElement = i;
1364 } // if
1365 } // for
1366 // Extract the target element
1367 if (EndOfElement > 0) {
1368 if (EndOfElement >= StartOfElement) {
1369 CopyLength = EndOfElement - StartOfElement + 1;
1370 Found = StrDuplicate(&InString[StartOfElement]);
1371 if (Found != NULL)
1372 Found[CopyLength] = 0;
1373 } // if (EndOfElement >= StartOfElement)
1374 } // if (EndOfElement > 0)
1375 return (Found);
1376 } // CHAR16 *FindNumbers()
1377
1378 // Find the #Index element (numbered from 0) in a comma-delimited string
1379 // of elements.
1380 // Returns the found element, or NULL if Index is out of range or InString
1381 // is NULL. Note that the calling function is responsible for freeing the
1382 // memory associated with the returned string pointer.
1383 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1384 UINTN StartPos = 0, CurPos = 0;
1385 BOOLEAN Found = FALSE;
1386 CHAR16 *FoundString = NULL;
1387
1388 if (InString != NULL) {
1389 // After while() loop, StartPos marks start of item #Index
1390 while ((Index > 0) && (CurPos < StrLen(InString))) {
1391 if (InString[CurPos] == L',') {
1392 Index--;
1393 StartPos = CurPos + 1;
1394 } // if
1395 CurPos++;
1396 } // while
1397 // After while() loop, CurPos is one past the end of the element
1398 while ((CurPos < StrLen(InString)) && (!Found)) {
1399 if (InString[CurPos] == L',')
1400 Found = TRUE;
1401 else
1402 CurPos++;
1403 } // while
1404 if (Index == 0)
1405 FoundString = StrDuplicate(&InString[StartPos]);
1406 if (FoundString != NULL)
1407 FoundString[CurPos - StartPos] = 0;
1408 } // if
1409 return (FoundString);
1410 } // CHAR16 *FindCommaDelimited()
1411
1412 // Returns TRUE if SmallString is an element in the comma-delimited List,
1413 // FALSE otherwise. Performs comparison case-insensitively (except on
1414 // buggy EFIs with case-sensitive StriCmp() functions).
1415 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1416 UINTN i = 0;
1417 BOOLEAN Found = FALSE;
1418 CHAR16 *OneElement;
1419
1420 if (SmallString && List) {
1421 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1422 if (StriCmp(OneElement, SmallString) == 0)
1423 Found = TRUE;
1424 } // while
1425 } // if
1426 return Found;
1427 } // BOOLEAN IsIn()
1428
1429 // Implement FreePool the way it should have been done to begin with, so that
1430 // it doesn't throw an ASSERT message if fed a NULL pointer....
1431 VOID MyFreePool(IN OUT VOID *Pointer) {
1432 if (Pointer != NULL)
1433 FreePool(Pointer);
1434 }
1435
1436 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1437
1438 // Eject all removable media.
1439 // Returns TRUE if any media were ejected, FALSE otherwise.
1440 BOOLEAN EjectMedia(VOID) {
1441 EFI_STATUS Status;
1442 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1443 EFI_HANDLE *Handles, Handle;
1444 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1445
1446 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1447 if (EFI_ERROR(Status) || HandleCount == 0)
1448 return (FALSE); // probably not an Apple system
1449
1450 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1451 Handle = Handles[HandleIndex];
1452 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1453 if (EFI_ERROR(Status))
1454 continue;
1455 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1456 if (!EFI_ERROR(Status))
1457 Ejected++;
1458 }
1459 MyFreePool(Handles);
1460 return (Ejected > 0);
1461 } // VOID EjectMedia()
1462
1463
1464 // Return the GUID as a string, suitable for display to the user. Note that the calling
1465 // function is responsible for freeing the allocated memory.
1466 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1467 CHAR16 *TheString;
1468
1469 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1470 if (TheString != 0) {
1471 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1472 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1473 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1474 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1475 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1476 }
1477 return TheString;
1478 } // GuidAsString(EFI_GUID *GuidData)