3 * General library functions
5 * Copyright (c) 2006-2009 Christoph Pfisterer
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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.
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.
37 * Modifications copyright (c) 2012 Roderick W. Smith
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.
49 #include "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
52 #ifdef __MAKEWITH_GNUEFI
53 #define EfiReallocatePool ReallocatePool
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}}
64 //#define EndDevicePath DevicePath
69 EFI_HANDLE SelfImageHandle
;
70 EFI_LOADED_IMAGE
*SelfLoadedImage
;
71 EFI_FILE
*SelfRootDir
;
75 REFIT_VOLUME
*SelfVolume
= NULL
;
76 REFIT_VOLUME
**Volumes
= NULL
;
77 UINTN VolumesCount
= 0;
79 // Maximum size for disk sectors
80 #define SECTOR_SIZE 4096
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"
88 static EFI_STATUS
FinishInitRefitLib(VOID
);
90 static VOID
UninitVolumes(VOID
);
93 // self recognition stuff
96 // Converts forward slashes to backslashes, removes duplicate slashes, and
97 // removes slashes from both the start and 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
104 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
106 UINTN i
, FinalChar
= 0;
107 BOOLEAN LastWasSlash
= FALSE
;
109 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 2));
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
'\\';
117 NewName
[FinalChar
++] = PathName
[i
];
118 LastWasSlash
= FALSE
;
121 NewName
[FinalChar
] = 0;
122 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
123 NewName
[--FinalChar
] = 0;
124 if (FinalChar
== 0) {
128 // Copy the transformed name back....
129 StrCpy(PathName
, NewName
);
131 } // if allocation OK
132 } // CleanUpPathNameSlashes()
134 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
137 CHAR16
*DevicePathAsString
;
139 SelfImageHandle
= ImageHandle
;
140 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
141 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
142 return EFI_LOAD_ERROR
;
144 // find the current directory
145 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
146 CleanUpPathNameSlashes(DevicePathAsString
);
147 if (SelfDirPath
!= NULL
)
148 FreePool(SelfDirPath
);
149 SelfDirPath
= FindPath(DevicePathAsString
);
150 FreePool(DevicePathAsString
);
152 return FinishInitRefitLib();
155 // called before running external programs to close open file handles
156 VOID
UninitRefitLib(VOID
)
160 if (SelfDir
!= NULL
) {
161 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
165 if (SelfRootDir
!= NULL
) {
166 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
171 // called after running external programs to re-open file handles
172 EFI_STATUS
ReinitRefitLib(VOID
)
176 if ((ST
->Hdr
.Revision
>> 16) == 1) {
177 // Below two lines were in rEFIt, but seem to cause system crashes or
178 // reboots when launching OSes after returning from programs on most
179 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
180 // installation volume" (see the next function) when returning from
181 // programs when these two lines are removed, and it often crashes
182 // when returning from a program or when launching a second program
183 // with these lines removed. Therefore, the preceding if() statement
184 // executes these lines only on EFIs with a major version number of 1
185 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
186 // of hardware on which to test is limited, though, so this may be the
187 // wrong test, or there may be a better way to fix this problem.
188 // TODO: Figure out cause of above weirdness and fix it more
190 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
191 SelfRootDir
= SelfVolume
->RootDir
;
194 return FinishInitRefitLib();
197 static EFI_STATUS
FinishInitRefitLib(VOID
)
201 if (SelfRootDir
== NULL
) {
202 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
203 if (SelfRootDir
== NULL
) {
204 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
205 return EFI_LOAD_ERROR
;
209 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
210 if (CheckFatalError(Status
, L
"while opening our installation directory"))
211 return EFI_LOAD_ERROR
;
220 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
224 *ElementCount
= InitialElementCount
;
225 if (*ElementCount
> 0) {
226 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
227 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
233 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
237 if ((*ElementCount
& 7) == 0) {
238 AllocateCount
= *ElementCount
+ 8;
239 if (*ElementCount
== 0)
240 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
242 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
244 (*ListPtr
)[*ElementCount
] = NewElement
;
246 } /* VOID AddListElement() */
248 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
252 if (*ElementCount
> 0) {
253 for (i
= 0; i
< *ElementCount
; i
++) {
254 // TODO: call a user-provided routine for each element here
255 FreePool((*ListPtr
)[i
]);
262 // firmware device path discovery
265 static UINT8 LegacyLoaderMediaPathData
[] = {
266 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
267 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
268 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
270 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
272 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
275 UINTN HandleCount
= 0;
276 UINTN HandleIndex
, HardcodedIndex
;
281 EFI_LOADED_IMAGE
*LoadedImage
;
282 EFI_DEVICE_PATH
*DevicePath
;
285 MaxPaths
--; // leave space for the terminating NULL pointer
287 // get all LoadedImage handles
288 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
289 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
290 if (HardcodedPathList
) {
291 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
292 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
294 PathList
[PathCount
] = NULL
;
297 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
298 Handle
= Handles
[HandleIndex
];
300 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
301 if (EFI_ERROR(Status
))
302 continue; // This can only happen if the firmware scewed up, ignore it.
304 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
305 if (EFI_ERROR(Status
))
306 continue; // This happens, ignore it.
308 // Only grab memory range nodes
309 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
312 // Check if we have this device path in the list already
313 // WARNING: This assumes the first node in the device path is unique!
315 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
316 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
318 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
326 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
330 if (HardcodedPathList
) {
331 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
332 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
334 PathList
[PathCount
] = NULL
;
341 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
344 UINT8 SectorBuffer
[SECTOR_SIZE
];
346 MBR_PARTITION_INFO
*MbrTable
;
347 BOOLEAN MbrTableFound
;
349 Volume
->HasBootCode
= FALSE
;
350 Volume
->OSIconName
= NULL
;
351 Volume
->OSName
= NULL
;
354 if (Volume
->BlockIO
== NULL
)
356 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
357 return; // our buffer is too small...
359 // look at the boot sector (this is used for both hard disks and El Torito images!)
360 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
361 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
362 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
363 if (!EFI_ERROR(Status
)) {
365 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
367 Volume
->HasBootCode
= TRUE
;
370 // detect specific boot codes
371 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
372 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
373 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
374 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
375 Volume
->HasBootCode
= TRUE
;
376 Volume
->OSIconName
= L
"linux";
377 Volume
->OSName
= L
"Linux";
379 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
380 Volume
->HasBootCode
= TRUE
;
381 Volume
->OSIconName
= L
"grub,linux";
382 Volume
->OSName
= L
"Linux";
384 // // Below doesn't produce a bootable entry, so commented out for the moment....
385 // // GRUB in BIOS boot partition:
386 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
387 // Volume->HasBootCode = TRUE;
388 // Volume->OSIconName = L"grub,linux";
389 // Volume->OSName = L"Linux";
390 // Volume->VolName = L"BIOS Boot Partition";
393 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
394 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
395 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
396 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
397 Volume
->HasBootCode
= TRUE
;
398 Volume
->OSIconName
= L
"freebsd";
399 Volume
->OSName
= L
"FreeBSD";
401 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
402 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
403 Volume
->HasBootCode
= TRUE
;
404 Volume
->OSIconName
= L
"openbsd";
405 Volume
->OSName
= L
"OpenBSD";
407 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
408 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
409 Volume
->HasBootCode
= TRUE
;
410 Volume
->OSIconName
= L
"netbsd";
411 Volume
->OSName
= L
"NetBSD";
413 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
414 Volume
->HasBootCode
= TRUE
;
415 Volume
->OSIconName
= L
"win";
416 Volume
->OSName
= L
"Windows";
418 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
419 Volume
->HasBootCode
= TRUE
;
420 Volume
->OSIconName
= L
"winvista,win";
421 Volume
->OSName
= L
"Windows";
423 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
424 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
425 Volume
->HasBootCode
= TRUE
;
426 Volume
->OSIconName
= L
"freedos";
427 Volume
->OSName
= L
"FreeDOS";
429 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
430 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
431 Volume
->HasBootCode
= TRUE
;
432 Volume
->OSIconName
= L
"ecomstation";
433 Volume
->OSName
= L
"eComStation";
435 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
436 Volume
->HasBootCode
= TRUE
;
437 Volume
->OSIconName
= L
"beos";
438 Volume
->OSName
= L
"BeOS";
440 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
441 Volume
->HasBootCode
= TRUE
;
442 Volume
->OSIconName
= L
"zeta,beos";
443 Volume
->OSName
= L
"ZETA";
445 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
446 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
447 Volume
->HasBootCode
= TRUE
;
448 Volume
->OSIconName
= L
"haiku,beos";
449 Volume
->OSName
= L
"Haiku";
453 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
454 // need to fix AddLegacyEntry in main.c.
457 Print(L
" Result of bootcode detection: %s %s (%s)\n",
458 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
459 Volume
->OSName
, Volume
->OSIconName
);
462 // dummy FAT boot sector (created by OS X's newfs_msdos)
463 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
464 Volume
->HasBootCode
= FALSE
;
466 // dummy FAT boot sector (created by Linux's mkdosfs)
467 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
468 Volume
->HasBootCode
= FALSE
;
470 // dummy FAT boot sector (created by Windows)
471 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
472 Volume
->HasBootCode
= FALSE
;
474 // check for MBR partition table
475 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
476 MbrTableFound
= FALSE
;
477 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
478 for (i
= 0; i
< 4; i
++)
479 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
480 MbrTableFound
= TRUE
;
481 for (i
= 0; i
< 4; i
++)
482 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
483 MbrTableFound
= FALSE
;
485 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
486 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
492 CheckError(Status
, L
"while reading boot sector");
497 // default volume badge icon based on disk kind
498 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
500 switch (Volume
->DiskKind
) {
501 case DISK_KIND_INTERNAL
:
502 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
504 case DISK_KIND_EXTERNAL
:
505 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
507 case DISK_KIND_OPTICAL
:
508 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
513 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
516 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
517 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
518 EFI_HANDLE WholeDiskHandle
;
520 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
524 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
526 if (Volume
->DevicePath
!= NULL
) {
527 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
529 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
534 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
537 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
538 if (EFI_ERROR(Status
)) {
539 Volume
->BlockIO
= NULL
;
540 Print(L
"Warning: Can't get BlockIO protocol.\n");
542 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
543 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
546 // scan for bootcode and MBR table
548 ScanVolumeBootcode(Volume
, &Bootable
);
550 // detect device type
551 DevicePath
= Volume
->DevicePath
;
552 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
553 NextDevicePath
= NextDevicePathNode(DevicePath
);
555 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
556 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
557 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
558 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
559 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
560 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
561 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
562 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
563 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
567 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
568 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
569 // TODO: also check for Boot Camp GUID
570 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
573 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
574 // make a device path for the whole device
575 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
576 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
577 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
578 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
580 // get the handle for that path
581 RemainingDevicePath
= DiskDevicePath
;
582 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
583 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
584 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
585 FreePool(DiskDevicePath
);
587 if (!EFI_ERROR(Status
)) {
588 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
590 // get the device path for later
591 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
592 if (!EFI_ERROR(Status
)) {
593 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
596 // look at the BlockIO protocol
597 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
598 if (!EFI_ERROR(Status
)) {
600 // check the media block size
601 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
602 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
605 Volume
->WholeDiskBlockIO
= NULL
;
606 //CheckError(Status, L"from HandleProtocol");
609 // CheckError(Status, L"from LocateDevicePath");
612 DevicePath
= NextDevicePath
;
617 if (Volume
->HasBootCode
)
618 Print(L
" Volume considered non-bootable, but boot code is present\n");
620 Volume
->HasBootCode
= FALSE
;
623 // default volume icon based on disk kind
624 ScanVolumeDefaultIcon(Volume
);
626 // open the root directory of the volume
627 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
628 if (Volume
->RootDir
== NULL
) {
629 Volume
->IsReadable
= FALSE
;
632 Volume
->IsReadable
= TRUE
;
636 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
637 if (FileSystemInfoPtr
!= NULL
) {
638 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
639 FreePool(FileSystemInfoPtr
);
642 if (Volume
->VolName
== NULL
) {
643 Volume
->VolName
= StrDuplicate(L
"Unknown");
645 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
646 // - name from bytes 3 to 10 of the boot sector
647 // - partition number
648 // - name derived from file system type or partition type
650 // get custom volume icon if present
651 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
652 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
653 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
654 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
658 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
661 REFIT_VOLUME
*Volume
;
662 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
664 UINTN LogicalPartitionIndex
= 4;
665 UINT8 SectorBuffer
[512];
667 MBR_PARTITION_INFO
*EMbrTable
;
669 ExtBase
= MbrEntry
->StartLBA
;
671 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
673 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
674 WholeDiskVolume
->BlockIO
,
675 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
676 ExtCurrent
, 512, SectorBuffer
);
677 if (EFI_ERROR(Status
))
679 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
681 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
683 // scan logical partitions in this EMBR
685 for (i
= 0; i
< 4; i
++) {
686 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
687 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
689 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
690 // set next ExtCurrent
691 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
695 // found a logical partition
696 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
697 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
698 Volume
->IsMbrPartition
= TRUE
;
699 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
700 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
701 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
702 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
703 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
704 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
707 ScanVolumeBootcode(Volume
, &Bootable
);
709 Volume
->HasBootCode
= FALSE
;
711 ScanVolumeDefaultIcon(Volume
);
713 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
720 VOID
ScanVolumes(VOID
)
723 UINTN HandleCount
= 0;
726 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
727 UINTN VolumeIndex
, VolumeIndex2
;
728 MBR_PARTITION_INFO
*MbrTable
;
729 UINTN PartitionIndex
;
730 UINT8
*SectorBuffer1
, *SectorBuffer2
;
737 // get all filesystem handles
738 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
739 // was: &FileSystemProtocol
740 if (Status
== EFI_NOT_FOUND
) {
741 return; // no filesystems. strange, but true...
743 if (CheckError(Status
, L
"while listing all file systems"))
746 // first pass: collect information about all handles
747 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
748 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
749 Volume
->DeviceHandle
= Handles
[HandleIndex
];
752 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
754 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
759 if (SelfVolume
== NULL
)
760 Print(L
"WARNING: SelfVolume not found");
762 // second pass: relate partitions and whole disk devices
763 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
764 Volume
= Volumes
[VolumeIndex
];
765 // check MBR partition table for extended partitions
766 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
767 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
768 Volume
->MbrPartitionTable
!= NULL
) {
769 MbrTable
= Volume
->MbrPartitionTable
;
770 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
771 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
772 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
777 // search for corresponding whole disk volume entry
778 WholeDiskVolume
= NULL
;
779 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
780 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
781 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
782 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
783 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
784 WholeDiskVolume
= Volumes
[VolumeIndex2
];
788 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
789 // check if this volume is one of the partitions in the table
790 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
791 SectorBuffer1
= AllocatePool(512);
792 SectorBuffer2
= AllocatePool(512);
793 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
795 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
798 // compare boot sector read through offset vs. directly
799 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
800 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
801 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
802 if (EFI_ERROR(Status
))
804 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
805 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
806 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
807 if (EFI_ERROR(Status
))
809 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
812 for (i
= 0; i
< 512; i
++)
813 SectorSum
+= SectorBuffer1
[i
];
814 if (SectorSum
< 1000)
817 // TODO: mark entry as non-bootable if it is an extended partition
819 // now we're reasonably sure the association is correct...
820 Volume
->IsMbrPartition
= TRUE
;
821 Volume
->MbrPartitionIndex
= PartitionIndex
;
822 if (Volume
->VolName
== NULL
) {
823 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
824 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
829 FreePool(SectorBuffer1
);
830 FreePool(SectorBuffer2
);
834 } /* VOID ScanVolumes() */
836 static VOID
UninitVolumes(VOID
)
838 REFIT_VOLUME
*Volume
;
841 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
842 Volume
= Volumes
[VolumeIndex
];
844 if (Volume
->RootDir
!= NULL
) {
845 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
846 Volume
->RootDir
= NULL
;
849 Volume
->DeviceHandle
= NULL
;
850 Volume
->BlockIO
= NULL
;
851 Volume
->WholeDiskBlockIO
= NULL
;
855 VOID
ReinitVolumes(VOID
)
858 REFIT_VOLUME
*Volume
;
860 EFI_DEVICE_PATH
*RemainingDevicePath
;
861 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
863 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
864 Volume
= Volumes
[VolumeIndex
];
866 if (Volume
->DevicePath
!= NULL
) {
867 // get the handle for that path
868 RemainingDevicePath
= Volume
->DevicePath
;
869 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
871 if (!EFI_ERROR(Status
)) {
872 Volume
->DeviceHandle
= DeviceHandle
;
874 // get the root directory
875 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
878 CheckError(Status
, L
"from LocateDevicePath");
881 if (Volume
->WholeDiskDevicePath
!= NULL
) {
882 // get the handle for that path
883 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
884 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
886 if (!EFI_ERROR(Status
)) {
887 // get the BlockIO protocol
888 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
889 if (EFI_ERROR(Status
)) {
890 Volume
->WholeDiskBlockIO
= NULL
;
891 CheckError(Status
, L
"from HandleProtocol");
894 CheckError(Status
, L
"from LocateDevicePath");
900 // file and dir functions
903 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
906 EFI_FILE_HANDLE TestFile
;
908 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
909 if (Status
== EFI_SUCCESS
) {
910 refit_call1_wrapper(TestFile
->Close
, TestFile
);
916 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
920 UINTN LastBufferSize
, BufferSize
;
925 // free pointer from last call
926 if (*DirEntry
!= NULL
) {
931 // read next directory entry
932 LastBufferSize
= BufferSize
= 256;
933 Buffer
= AllocatePool(BufferSize
);
934 for (IterCount
= 0; ; IterCount
++) {
935 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
936 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
938 if (BufferSize
<= LastBufferSize
) {
939 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
940 BufferSize
= LastBufferSize
* 2;
943 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
946 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
947 LastBufferSize
= BufferSize
;
949 if (EFI_ERROR(Status
)) {
954 // check for end of listing
955 if (BufferSize
== 0) { // end of directory listing
960 // entry is ready to be returned
961 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
964 if (FilterMode
== 1) { // only return directories
965 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
967 } else if (FilterMode
== 2) { // only return files
968 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
970 } else // no filter or unknown filter -> return everything
977 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
979 if (RelativePath
== NULL
) {
980 DirIter
->LastStatus
= EFI_SUCCESS
;
981 DirIter
->DirHandle
= BaseDir
;
982 DirIter
->CloseDirHandle
= FALSE
;
984 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
985 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
987 DirIter
->LastFileInfo
= NULL
;
990 #ifndef __MAKEWITH_GNUEFI
991 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
994 InitializeUnicodeCollationProtocol (VOID
)
998 if (mUnicodeCollation
!= NULL
) {
1003 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1004 // instances first and then select one which support English language.
1005 // Current implementation just pick the first instance.
1007 Status
= gBS
->LocateProtocol (
1008 &gEfiUnicodeCollation2ProtocolGuid
,
1010 (VOID
**) &mUnicodeCollation
1012 if (EFI_ERROR(Status
)) {
1013 Status
= gBS
->LocateProtocol (
1014 &gEfiUnicodeCollationProtocolGuid
,
1016 (VOID
**) &mUnicodeCollation
1024 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1026 if (!mUnicodeCollation
) {
1027 InitializeUnicodeCollationProtocol();
1029 if (mUnicodeCollation
)
1030 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1031 return FALSE
; // Shouldn't happen
1034 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1035 if (!mUnicodeCollation
) {
1036 InitializeUnicodeCollationProtocol();
1038 if (mUnicodeCollation
)
1039 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1044 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1045 OUT EFI_FILE_INFO
**DirEntry
)
1047 BOOLEAN KeepGoing
= TRUE
;
1051 if (DirIter
->LastFileInfo
!= NULL
) {
1052 FreePool(DirIter
->LastFileInfo
);
1053 DirIter
->LastFileInfo
= NULL
;
1056 if (EFI_ERROR(DirIter
->LastStatus
))
1057 return FALSE
; // stop iteration
1060 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1061 if (EFI_ERROR(DirIter
->LastStatus
))
1063 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1065 if (FilePattern
!= NULL
) {
1066 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1069 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1070 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1073 // else continue loop
1076 } while (KeepGoing
);
1078 *DirEntry
= DirIter
->LastFileInfo
;
1082 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1084 if (DirIter
->LastFileInfo
!= NULL
) {
1085 FreePool(DirIter
->LastFileInfo
);
1086 DirIter
->LastFileInfo
= NULL
;
1088 if (DirIter
->CloseDirHandle
)
1089 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1090 return DirIter
->LastStatus
;
1094 // file name manipulation
1097 // Returns the filename portion (minus path name) of the
1099 CHAR16
* Basename(IN CHAR16
*Path
)
1107 for (i
= StrLen(Path
); i
> 0; i
--) {
1108 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1109 FileName
= Path
+ i
;
1118 // Replaces a filename extension of ".efi" with the specified string
1119 // (Extension). If the input Path doesn't end in ".efi", Extension
1120 // is added to the existing filename.
1121 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1125 PathLen
= StrLen(Path
);
1126 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1127 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1128 Path
[PathLen
- 4] = 0;
1130 StrCat(Path
, Extension
);
1131 } // VOID ReplaceEfiExtension()
1134 // memory string search
1137 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1143 BufferLength
-= SearchStringLength
;
1144 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1145 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1146 return (INTN
)Offset
;
1152 // Performs a case-insensitive search of BigStr for SmallStr.
1153 // Returns TRUE if found, FALSE if not.
1154 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1155 CHAR16
*SmallCopy
, *BigCopy
;
1156 BOOLEAN Found
= FALSE
;
1157 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1159 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1160 SmallCopy
= StrDuplicate(SmallStr
);
1161 BigCopy
= StrDuplicate(BigStr
);
1164 SmallLen
= StrLen(SmallCopy
);
1165 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1166 while ((!Found
) && (StartPoint
< NumCompares
)) {
1167 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1169 FreePool(SmallCopy
);
1174 } // BOOLEAN StriSubCmp()
1176 // Merges two strings, creating a new one and returning a pointer to it.
1177 // If AddChar != 0, the specified character is placed between the two original
1178 // strings (unless the first string is NULL). The original input string
1179 // *First is de-allocated and replaced by the new merged string.
1180 // This is similar to StrCat, but safer and more flexible because
1181 // MergeStrings allocates memory that's the correct size for the
1182 // new merged string, so it can take a NULL *First and it cleans
1183 // up the old memory. It should *NOT* be used with a constant
1184 // *First, though....
1185 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1186 UINTN Length1
= 0, Length2
= 0;
1190 Length1
= StrLen(*First
);
1192 Length2
= StrLen(Second
);
1193 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1194 if (NewString
!= NULL
) {
1195 NewString
[0] = L
'\0';
1196 if (*First
!= NULL
) {
1197 StrCat(NewString
, *First
);
1199 NewString
[Length1
] = AddChar
;
1200 NewString
[Length1
+ 1] = 0;
1202 } // if (*First != NULL)
1204 StrCat(NewString
, Second
);
1208 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1210 } // static CHAR16* MergeStrings()
1212 // Takes an input pathname (*Path) and returns the part of the filename from
1213 // the final dot onwards, converted to lowercase. If the filename includes
1214 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1215 // The calling function is responsible for freeing the memory associated with
1216 // the return value.
1217 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1219 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1222 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1225 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1226 if (Path
[i
] == L
'.')
1228 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1234 MergeStrings(&Extension
, &Path
[i
], 0);
1239 } // CHAR16 *FindExtension
1241 // Takes an input pathname (*Path) and locates the final directory component
1242 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1243 // function returns the string 'foo'.
1244 // Assumes the pathname is separated with backslashes.
1245 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1246 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1247 CHAR16
*Found
= NULL
;
1249 PathLength
= StrLen(Path
);
1250 // Find start & end of target element
1251 for (i
= 0; i
< PathLength
; i
++) {
1252 if (Path
[i
] == '\\') {
1253 StartOfElement
= EndOfElement
;
1257 // Extract the target element
1258 if (EndOfElement
> 0) {
1259 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1263 if (EndOfElement
>= StartOfElement
) {
1264 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1265 Found
= StrDuplicate(&Path
[StartOfElement
]);
1267 Found
[CopyLength
] = 0;
1268 } // if (EndOfElement >= StartOfElement)
1269 } // if (EndOfElement > 0)
1271 } // CHAR16 *FindLastDirName
1273 // Returns the directory portion of a pathname. For instance,
1274 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1275 // string 'EFI\foo'. The calling function is responsible for
1276 // freeing the returned string's memory.
1277 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1278 UINTN i
, LastBackslash
= 0;
1281 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1282 if (FullPath
[i
] == '\\')
1285 PathOnly
= StrDuplicate(FullPath
);
1286 PathOnly
[LastBackslash
] = 0;
1290 // Returns all the digits in the input string, including intervening
1291 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1292 // this function returns "3.3.4-7". If InString contains no digits,
1293 // the return value is NULL.
1294 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1295 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1296 CHAR16
*Found
= NULL
;
1298 InLength
= StartOfElement
= StrLen(InString
);
1299 // Find start & end of target element
1300 for (i
= 0; i
< InLength
; i
++) {
1301 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1302 if (StartOfElement
> i
)
1304 if (EndOfElement
< i
)
1308 // Extract the target element
1309 if (EndOfElement
> 0) {
1310 if (EndOfElement
>= StartOfElement
) {
1311 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1312 Found
= StrDuplicate(&InString
[StartOfElement
]);
1314 Found
[CopyLength
] = 0;
1315 } // if (EndOfElement >= StartOfElement)
1316 } // if (EndOfElement > 0)
1318 } // CHAR16 *FindNumbers()
1320 // Find the #Index element (numbered from 0) in a comma-delimited string
1322 // Returns the found element, or NULL if Index is out of range or InString
1323 // is NULL. Note that the calling function is responsible for freeing the
1324 // memory associated with the returned string pointer.
1325 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1326 UINTN StartPos
= 0, CurPos
= 0;
1327 BOOLEAN Found
= FALSE
;
1328 CHAR16
*FoundString
= NULL
;
1330 if (InString
!= NULL
) {
1331 // After while() loop, StartPos marks start of item #Index
1332 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1333 if (InString
[CurPos
] == L
',') {
1335 StartPos
= CurPos
+ 1;
1339 // After while() loop, CurPos is one past the end of the element
1340 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1341 if (InString
[CurPos
] == L
',')
1347 FoundString
= StrDuplicate(&InString
[StartPos
]);
1348 if (FoundString
!= NULL
)
1349 FoundString
[CurPos
- StartPos
] = 0;
1351 return (FoundString
);
1352 } // CHAR16 *FindCommaDelimited()
1354 // Returns TRUE if SmallString is an element in the comma-delimited List,
1355 // FALSE otherwise. Performs comparison case-insensitively (except on
1356 // buggy EFIs with case-sensitive StriCmp() functions).
1357 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1359 BOOLEAN Found
= FALSE
;
1362 if (SmallString
&& List
) {
1363 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1364 if (StriCmp(OneElement
, SmallString
) == 0)
1371 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1373 // Eject all removable media.
1374 // Returns TRUE if any media were ejected, FALSE otherwise.
1375 BOOLEAN
EjectMedia(VOID
) {
1377 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1378 EFI_HANDLE
*Handles
, Handle
;
1379 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1381 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1382 if (EFI_ERROR(Status
) || HandleCount
== 0)
1383 return (FALSE
); // probably not an Apple system
1385 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1386 Handle
= Handles
[HandleIndex
];
1387 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1388 if (EFI_ERROR(Status
))
1390 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1391 if (!EFI_ERROR(Status
))
1395 return (Ejected
> 0);
1396 } // VOID EjectMedia()