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 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
104 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
106 UINTN i
, FinalChar
= 0;
107 BOOLEAN LastWasSlash
= FALSE
;
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
'\\';
117 if (FinalChar
== 0) {
118 NewName
[FinalChar
++] = L
'\\';
120 NewName
[FinalChar
++] = PathName
[i
];
121 LastWasSlash
= FALSE
;
124 NewName
[FinalChar
] = 0;
125 if ((FinalChar
> 1) && (NewName
[FinalChar
- 1] == L
'\\'))
126 NewName
[--FinalChar
] = 0;
127 if (FinalChar
== 0) {
131 // Copy the transformed name back....
132 StrCpy(PathName
, NewName
);
134 } // if allocation OK
135 } // CleanUpPathNameSlashes()
137 // Splits an EFI device path into device and filename components. For instance, if InString is
138 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
139 // this function will truncate that input to
140 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
141 // and return bzImage-3.5.1.efi as its return value.
142 // It does this by searching for the last ")" character in InString, copying everything
143 // after that string (after some cleanup) as the return value, and truncating the original
145 // If InString contains no ")" character, this function leaves the original input string
146 // unmodified and also returns that string.
147 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
149 CHAR16
*FileName
= NULL
;
150 BOOLEAN Found
= FALSE
;
152 i
= StrLen(InString
) - 1;
153 while ((i
>= 0) && (!Found
)) {
154 if (InString
[i
] == L
')') {
156 FileName
= StrDuplicate(&InString
[i
+ 1]);
157 CleanUpPathNameSlashes(FileName
);
158 InString
[i
+ 1] = '\0';
162 if (FileName
== NULL
)
163 FileName
= StrDuplicate(InString
);
165 } // static CHAR16* SplitDeviceString()
167 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
170 CHAR16
*DevicePathAsString
, *Temp
;
172 SelfImageHandle
= ImageHandle
;
173 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
174 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
175 return EFI_LOAD_ERROR
;
177 // find the current directory
178 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
179 CleanUpPathNameSlashes(DevicePathAsString
);
180 MyFreePool(SelfDirPath
);
181 Temp
= FindPath(DevicePathAsString
);
182 SelfDirPath
= SplitDeviceString(Temp
);
183 MyFreePool(DevicePathAsString
);
186 return FinishInitRefitLib();
189 // called before running external programs to close open file handles
190 VOID
UninitRefitLib(VOID
)
194 if (SelfDir
!= NULL
) {
195 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
199 if (SelfRootDir
!= NULL
) {
200 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
205 // called after running external programs to re-open file handles
206 EFI_STATUS
ReinitRefitLib(VOID
)
210 if ((ST
->Hdr
.Revision
>> 16) == 1) {
211 // Below two lines were in rEFIt, but seem to cause system crashes or
212 // reboots when launching OSes after returning from programs on most
213 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
214 // installation volume" (see the next function) when returning from
215 // programs when these two lines are removed, and it often crashes
216 // when returning from a program or when launching a second program
217 // with these lines removed. Therefore, the preceding if() statement
218 // executes these lines only on EFIs with a major version number of 1
219 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
220 // of hardware on which to test is limited, though, so this may be the
221 // wrong test, or there may be a better way to fix this problem.
222 // TODO: Figure out cause of above weirdness and fix it more
224 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
225 SelfRootDir
= SelfVolume
->RootDir
;
228 return FinishInitRefitLib();
231 static EFI_STATUS
FinishInitRefitLib(VOID
)
235 if (SelfRootDir
== NULL
) {
236 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
237 if (SelfRootDir
== NULL
) {
238 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
239 return EFI_LOAD_ERROR
;
243 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
244 if (CheckFatalError(Status
, L
"while opening our installation directory"))
245 return EFI_LOAD_ERROR
;
254 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
258 *ElementCount
= InitialElementCount
;
259 if (*ElementCount
> 0) {
260 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
261 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
267 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
271 if ((*ElementCount
& 7) == 0) {
272 AllocateCount
= *ElementCount
+ 8;
273 if (*ElementCount
== 0)
274 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
276 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
278 (*ListPtr
)[*ElementCount
] = NewElement
;
280 } /* VOID AddListElement() */
282 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
286 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
287 for (i
= 0; i
< *ElementCount
; i
++) {
288 // TODO: call a user-provided routine for each element here
289 MyFreePool((*ListPtr
)[i
]);
291 MyFreePool(*ListPtr
);
296 // firmware device path discovery
299 static UINT8 LegacyLoaderMediaPathData
[] = {
300 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
301 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
302 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
304 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
306 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
309 UINTN HandleCount
= 0;
310 UINTN HandleIndex
, HardcodedIndex
;
315 EFI_LOADED_IMAGE
*LoadedImage
;
316 EFI_DEVICE_PATH
*DevicePath
;
319 MaxPaths
--; // leave space for the terminating NULL pointer
321 // get all LoadedImage handles
322 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
323 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
324 if (HardcodedPathList
) {
325 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
326 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
328 PathList
[PathCount
] = NULL
;
331 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
332 Handle
= Handles
[HandleIndex
];
334 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
335 if (EFI_ERROR(Status
))
336 continue; // This can only happen if the firmware scewed up, ignore it.
338 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
339 if (EFI_ERROR(Status
))
340 continue; // This happens, ignore it.
342 // Only grab memory range nodes
343 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
346 // Check if we have this device path in the list already
347 // WARNING: This assumes the first node in the device path is unique!
349 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
350 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
352 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
360 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
364 if (HardcodedPathList
) {
365 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
366 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
368 PathList
[PathCount
] = NULL
;
375 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
378 UINT8 SectorBuffer
[SECTOR_SIZE
];
380 MBR_PARTITION_INFO
*MbrTable
;
381 BOOLEAN MbrTableFound
;
383 Volume
->HasBootCode
= FALSE
;
384 Volume
->OSIconName
= NULL
;
385 Volume
->OSName
= NULL
;
388 if (Volume
->BlockIO
== NULL
)
390 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
391 return; // our buffer is too small...
393 // look at the boot sector (this is used for both hard disks and El Torito images!)
394 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
395 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
396 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
397 if (!EFI_ERROR(Status
)) {
399 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
401 Volume
->HasBootCode
= TRUE
;
404 // detect specific boot codes
405 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
406 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
407 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
408 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
409 Volume
->HasBootCode
= TRUE
;
410 Volume
->OSIconName
= L
"linux";
411 Volume
->OSName
= L
"Linux";
413 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
414 Volume
->HasBootCode
= TRUE
;
415 Volume
->OSIconName
= L
"grub,linux";
416 Volume
->OSName
= L
"Linux";
418 // // Below doesn't produce a bootable entry, so commented out for the moment....
419 // // GRUB in BIOS boot partition:
420 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
421 // Volume->HasBootCode = TRUE;
422 // Volume->OSIconName = L"grub,linux";
423 // Volume->OSName = L"Linux";
424 // Volume->VolName = L"BIOS Boot Partition";
427 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
428 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
429 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
430 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
431 Volume
->HasBootCode
= TRUE
;
432 Volume
->OSIconName
= L
"freebsd";
433 Volume
->OSName
= L
"FreeBSD";
435 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
436 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
437 Volume
->HasBootCode
= TRUE
;
438 Volume
->OSIconName
= L
"openbsd";
439 Volume
->OSName
= L
"OpenBSD";
441 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
442 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
443 Volume
->HasBootCode
= TRUE
;
444 Volume
->OSIconName
= L
"netbsd";
445 Volume
->OSName
= L
"NetBSD";
447 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
448 Volume
->HasBootCode
= TRUE
;
449 Volume
->OSIconName
= L
"win";
450 Volume
->OSName
= L
"Windows";
452 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
453 Volume
->HasBootCode
= TRUE
;
454 Volume
->OSIconName
= L
"winvista,win";
455 Volume
->OSName
= L
"Windows";
457 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
458 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
459 Volume
->HasBootCode
= TRUE
;
460 Volume
->OSIconName
= L
"freedos";
461 Volume
->OSName
= L
"FreeDOS";
463 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
464 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
465 Volume
->HasBootCode
= TRUE
;
466 Volume
->OSIconName
= L
"ecomstation";
467 Volume
->OSName
= L
"eComStation";
469 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
470 Volume
->HasBootCode
= TRUE
;
471 Volume
->OSIconName
= L
"beos";
472 Volume
->OSName
= L
"BeOS";
474 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
475 Volume
->HasBootCode
= TRUE
;
476 Volume
->OSIconName
= L
"zeta,beos";
477 Volume
->OSName
= L
"ZETA";
479 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
480 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
481 Volume
->HasBootCode
= TRUE
;
482 Volume
->OSIconName
= L
"haiku,beos";
483 Volume
->OSName
= L
"Haiku";
487 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
488 // need to fix AddLegacyEntry in main.c.
491 Print(L
" Result of bootcode detection: %s %s (%s)\n",
492 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
493 Volume
->OSName
, Volume
->OSIconName
);
496 // dummy FAT boot sector (created by OS X's newfs_msdos)
497 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
498 Volume
->HasBootCode
= FALSE
;
500 // dummy FAT boot sector (created by Linux's mkdosfs)
501 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
502 Volume
->HasBootCode
= FALSE
;
504 // dummy FAT boot sector (created by Windows)
505 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
506 Volume
->HasBootCode
= FALSE
;
508 // check for MBR partition table
509 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
510 MbrTableFound
= FALSE
;
511 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
512 for (i
= 0; i
< 4; i
++)
513 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
514 MbrTableFound
= TRUE
;
515 for (i
= 0; i
< 4; i
++)
516 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
517 MbrTableFound
= FALSE
;
519 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
520 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
526 CheckError(Status
, L
"while reading boot sector");
531 // default volume badge icon based on disk kind
532 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
534 switch (Volume
->DiskKind
) {
535 case DISK_KIND_INTERNAL
:
536 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
538 case DISK_KIND_EXTERNAL
:
539 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
541 case DISK_KIND_OPTICAL
:
542 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
547 VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
550 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
551 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
552 EFI_HANDLE WholeDiskHandle
;
554 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
558 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
560 if (Volume
->DevicePath
!= NULL
) {
561 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
563 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
568 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
571 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
572 if (EFI_ERROR(Status
)) {
573 Volume
->BlockIO
= NULL
;
574 Print(L
"Warning: Can't get BlockIO protocol.\n");
576 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
577 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
580 // scan for bootcode and MBR table
582 ScanVolumeBootcode(Volume
, &Bootable
);
584 // detect device type
585 DevicePath
= Volume
->DevicePath
;
586 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
587 NextDevicePath
= NextDevicePathNode(DevicePath
);
589 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
590 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
591 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
592 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
593 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
594 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
595 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
596 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
597 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
601 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
602 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
603 // TODO: also check for Boot Camp GUID
604 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
607 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
608 // make a device path for the whole device
609 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
610 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
611 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
612 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
614 // get the handle for that path
615 RemainingDevicePath
= DiskDevicePath
;
616 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
617 FreePool(DiskDevicePath
);
619 if (!EFI_ERROR(Status
)) {
620 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
622 // get the device path for later
623 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
624 if (!EFI_ERROR(Status
)) {
625 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
628 // look at the BlockIO protocol
629 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
630 if (!EFI_ERROR(Status
)) {
632 // check the media block size
633 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
634 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
637 Volume
->WholeDiskBlockIO
= NULL
;
638 //CheckError(Status, L"from HandleProtocol");
641 // CheckError(Status, L"from LocateDevicePath");
644 DevicePath
= NextDevicePath
;
649 if (Volume
->HasBootCode
)
650 Print(L
" Volume considered non-bootable, but boot code is present\n");
652 Volume
->HasBootCode
= FALSE
;
655 // default volume icon based on disk kind
656 ScanVolumeDefaultIcon(Volume
);
658 // open the root directory of the volume
659 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
660 if (Volume
->RootDir
== NULL
) {
661 Volume
->IsReadable
= FALSE
;
664 Volume
->IsReadable
= TRUE
;
668 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
669 if (FileSystemInfoPtr
!= NULL
) {
670 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
671 FreePool(FileSystemInfoPtr
);
674 if (Volume
->VolName
== NULL
) {
675 Volume
->VolName
= StrDuplicate(L
"Unknown");
677 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
678 // - name from bytes 3 to 10 of the boot sector
679 // - partition number
680 // - name derived from file system type or partition type
682 // get custom volume icon if present
683 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
684 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
685 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
686 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
690 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
693 REFIT_VOLUME
*Volume
;
694 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
696 UINTN LogicalPartitionIndex
= 4;
697 UINT8 SectorBuffer
[512];
699 MBR_PARTITION_INFO
*EMbrTable
;
701 ExtBase
= MbrEntry
->StartLBA
;
703 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
705 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
706 WholeDiskVolume
->BlockIO
,
707 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
708 ExtCurrent
, 512, SectorBuffer
);
709 if (EFI_ERROR(Status
))
711 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
713 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
715 // scan logical partitions in this EMBR
717 for (i
= 0; i
< 4; i
++) {
718 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
719 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
721 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
722 // set next ExtCurrent
723 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
727 // found a logical partition
728 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
729 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
730 Volume
->IsMbrPartition
= TRUE
;
731 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
732 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
733 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
734 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
735 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
736 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
739 ScanVolumeBootcode(Volume
, &Bootable
);
741 Volume
->HasBootCode
= FALSE
;
743 ScanVolumeDefaultIcon(Volume
);
745 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
752 VOID
ScanVolumes(VOID
)
755 UINTN HandleCount
= 0;
758 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
759 UINTN VolumeIndex
, VolumeIndex2
;
760 MBR_PARTITION_INFO
*MbrTable
;
761 UINTN PartitionIndex
;
762 UINT8
*SectorBuffer1
, *SectorBuffer2
;
769 // get all filesystem handles
770 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
771 // was: &FileSystemProtocol
772 if (Status
== EFI_NOT_FOUND
) {
773 return; // no filesystems. strange, but true...
775 if (CheckError(Status
, L
"while listing all file systems"))
778 // first pass: collect information about all handles
779 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
780 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
781 Volume
->DeviceHandle
= Handles
[HandleIndex
];
784 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
786 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
791 if (SelfVolume
== NULL
)
792 Print(L
"WARNING: SelfVolume not found");
794 // second pass: relate partitions and whole disk devices
795 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
796 Volume
= Volumes
[VolumeIndex
];
797 // check MBR partition table for extended partitions
798 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
799 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
800 Volume
->MbrPartitionTable
!= NULL
) {
801 MbrTable
= Volume
->MbrPartitionTable
;
802 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
803 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
804 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
809 // search for corresponding whole disk volume entry
810 WholeDiskVolume
= NULL
;
811 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
812 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
813 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
814 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
815 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
816 WholeDiskVolume
= Volumes
[VolumeIndex2
];
820 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
821 // check if this volume is one of the partitions in the table
822 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
823 SectorBuffer1
= AllocatePool(512);
824 SectorBuffer2
= AllocatePool(512);
825 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
827 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
830 // compare boot sector read through offset vs. directly
831 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
832 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
833 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
834 if (EFI_ERROR(Status
))
836 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
837 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
838 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
839 if (EFI_ERROR(Status
))
841 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
844 for (i
= 0; i
< 512; i
++)
845 SectorSum
+= SectorBuffer1
[i
];
846 if (SectorSum
< 1000)
849 // TODO: mark entry as non-bootable if it is an extended partition
851 // now we're reasonably sure the association is correct...
852 Volume
->IsMbrPartition
= TRUE
;
853 Volume
->MbrPartitionIndex
= PartitionIndex
;
854 if (Volume
->VolName
== NULL
) {
855 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
856 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
861 MyFreePool(SectorBuffer1
);
862 MyFreePool(SectorBuffer2
);
866 } /* VOID ScanVolumes() */
868 static VOID
UninitVolumes(VOID
)
870 REFIT_VOLUME
*Volume
;
873 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
874 Volume
= Volumes
[VolumeIndex
];
876 if (Volume
->RootDir
!= NULL
) {
877 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
878 Volume
->RootDir
= NULL
;
881 Volume
->DeviceHandle
= NULL
;
882 Volume
->BlockIO
= NULL
;
883 Volume
->WholeDiskBlockIO
= NULL
;
887 VOID
ReinitVolumes(VOID
)
890 REFIT_VOLUME
*Volume
;
892 EFI_DEVICE_PATH
*RemainingDevicePath
;
893 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
895 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
896 Volume
= Volumes
[VolumeIndex
];
898 if (Volume
->DevicePath
!= NULL
) {
899 // get the handle for that path
900 RemainingDevicePath
= Volume
->DevicePath
;
901 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
903 if (!EFI_ERROR(Status
)) {
904 Volume
->DeviceHandle
= DeviceHandle
;
906 // get the root directory
907 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
910 CheckError(Status
, L
"from LocateDevicePath");
913 if (Volume
->WholeDiskDevicePath
!= NULL
) {
914 // get the handle for that path
915 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
916 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
918 if (!EFI_ERROR(Status
)) {
919 // get the BlockIO protocol
920 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
921 if (EFI_ERROR(Status
)) {
922 Volume
->WholeDiskBlockIO
= NULL
;
923 CheckError(Status
, L
"from HandleProtocol");
926 CheckError(Status
, L
"from LocateDevicePath");
932 // file and dir functions
935 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
938 EFI_FILE_HANDLE TestFile
;
940 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
941 if (Status
== EFI_SUCCESS
) {
942 refit_call1_wrapper(TestFile
->Close
, TestFile
);
948 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
952 UINTN LastBufferSize
, BufferSize
;
957 // free pointer from last call
958 if (*DirEntry
!= NULL
) {
963 // read next directory entry
964 LastBufferSize
= BufferSize
= 256;
965 Buffer
= AllocatePool(BufferSize
);
966 for (IterCount
= 0; ; IterCount
++) {
967 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
968 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
970 if (BufferSize
<= LastBufferSize
) {
971 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
972 BufferSize
= LastBufferSize
* 2;
975 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
978 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
979 LastBufferSize
= BufferSize
;
981 if (EFI_ERROR(Status
)) {
986 // check for end of listing
987 if (BufferSize
== 0) { // end of directory listing
992 // entry is ready to be returned
993 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
996 if (FilterMode
== 1) { // only return directories
997 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
999 } else if (FilterMode
== 2) { // only return files
1000 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1002 } else // no filter or unknown filter -> return everything
1009 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1011 if (RelativePath
== NULL
) {
1012 DirIter
->LastStatus
= EFI_SUCCESS
;
1013 DirIter
->DirHandle
= BaseDir
;
1014 DirIter
->CloseDirHandle
= FALSE
;
1016 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1017 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1019 DirIter
->LastFileInfo
= NULL
;
1022 #ifndef __MAKEWITH_GNUEFI
1023 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1026 InitializeUnicodeCollationProtocol (VOID
)
1030 if (mUnicodeCollation
!= NULL
) {
1035 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1036 // instances first and then select one which support English language.
1037 // Current implementation just pick the first instance.
1039 Status
= gBS
->LocateProtocol (
1040 &gEfiUnicodeCollation2ProtocolGuid
,
1042 (VOID
**) &mUnicodeCollation
1044 if (EFI_ERROR(Status
)) {
1045 Status
= gBS
->LocateProtocol (
1046 &gEfiUnicodeCollationProtocolGuid
,
1048 (VOID
**) &mUnicodeCollation
1056 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1058 if (!mUnicodeCollation
) {
1059 InitializeUnicodeCollationProtocol();
1061 if (mUnicodeCollation
)
1062 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1063 return FALSE
; // Shouldn't happen
1066 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1067 if (!mUnicodeCollation
) {
1068 InitializeUnicodeCollationProtocol();
1070 if (mUnicodeCollation
)
1071 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1076 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1077 OUT EFI_FILE_INFO
**DirEntry
)
1079 BOOLEAN KeepGoing
= TRUE
;
1083 if (DirIter
->LastFileInfo
!= NULL
) {
1084 FreePool(DirIter
->LastFileInfo
);
1085 DirIter
->LastFileInfo
= NULL
;
1088 if (EFI_ERROR(DirIter
->LastStatus
))
1089 return FALSE
; // stop iteration
1092 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1093 if (EFI_ERROR(DirIter
->LastStatus
))
1095 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1097 if (FilePattern
!= NULL
) {
1098 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1101 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1102 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1105 // else continue loop
1108 } while (KeepGoing
);
1110 *DirEntry
= DirIter
->LastFileInfo
;
1114 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1116 if (DirIter
->LastFileInfo
!= NULL
) {
1117 FreePool(DirIter
->LastFileInfo
);
1118 DirIter
->LastFileInfo
= NULL
;
1120 if (DirIter
->CloseDirHandle
)
1121 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1122 return DirIter
->LastStatus
;
1126 // file name manipulation
1129 // Returns the filename portion (minus path name) of the
1131 CHAR16
* Basename(IN CHAR16
*Path
)
1139 for (i
= StrLen(Path
); i
> 0; i
--) {
1140 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1141 FileName
= Path
+ i
;
1150 // Replaces a filename extension of ".efi" with the specified string
1151 // (Extension). If the input Path doesn't end in ".efi", Extension
1152 // is added to the existing filename.
1153 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1157 PathLen
= StrLen(Path
);
1158 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1159 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1160 Path
[PathLen
- 4] = 0;
1162 StrCat(Path
, Extension
);
1163 } // VOID ReplaceEfiExtension()
1166 // memory string search
1169 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1175 BufferLength
-= SearchStringLength
;
1176 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1177 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1178 return (INTN
)Offset
;
1184 // Performs a case-insensitive search of BigStr for SmallStr.
1185 // Returns TRUE if found, FALSE if not.
1186 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1187 CHAR16
*SmallCopy
, *BigCopy
;
1188 BOOLEAN Found
= FALSE
;
1189 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1191 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1192 SmallCopy
= StrDuplicate(SmallStr
);
1193 BigCopy
= StrDuplicate(BigStr
);
1196 SmallLen
= StrLen(SmallCopy
);
1197 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1198 while ((!Found
) && (StartPoint
< NumCompares
)) {
1199 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1201 MyFreePool(SmallCopy
);
1202 MyFreePool(BigCopy
);
1206 } // BOOLEAN StriSubCmp()
1208 // Merges two strings, creating a new one and returning a pointer to it.
1209 // If AddChar != 0, the specified character is placed between the two original
1210 // strings (unless the first string is NULL). The original input string
1211 // *First is de-allocated and replaced by the new merged string.
1212 // This is similar to StrCat, but safer and more flexible because
1213 // MergeStrings allocates memory that's the correct size for the
1214 // new merged string, so it can take a NULL *First and it cleans
1215 // up the old memory. It should *NOT* be used with a constant
1216 // *First, though....
1217 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1218 UINTN Length1
= 0, Length2
= 0;
1222 Length1
= StrLen(*First
);
1224 Length2
= StrLen(Second
);
1225 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1226 if (NewString
!= NULL
) {
1227 NewString
[0] = L
'\0';
1228 if (*First
!= NULL
) {
1229 StrCat(NewString
, *First
);
1231 NewString
[Length1
] = AddChar
;
1232 NewString
[Length1
+ 1] = 0;
1234 } // if (*First != NULL)
1236 StrCat(NewString
, Second
);
1240 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1242 } // static CHAR16* MergeStrings()
1244 // Takes an input pathname (*Path) and returns the part of the filename from
1245 // the final dot onwards, converted to lowercase. If the filename includes
1246 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1247 // The calling function is responsible for freeing the memory associated with
1248 // the return value.
1249 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1251 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1254 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1257 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1258 if (Path
[i
] == L
'.')
1260 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1266 MergeStrings(&Extension
, &Path
[i
], 0);
1271 } // CHAR16 *FindExtension
1273 // Takes an input pathname (*Path) and locates the final directory component
1274 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1275 // function returns the string 'foo'.
1276 // Assumes the pathname is separated with backslashes.
1277 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1278 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1279 CHAR16
*Found
= NULL
;
1281 PathLength
= StrLen(Path
);
1282 // Find start & end of target element
1283 for (i
= 0; i
< PathLength
; i
++) {
1284 if (Path
[i
] == '\\') {
1285 StartOfElement
= EndOfElement
;
1289 // Extract the target element
1290 if (EndOfElement
> 0) {
1291 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1295 if (EndOfElement
>= StartOfElement
) {
1296 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1297 Found
= StrDuplicate(&Path
[StartOfElement
]);
1299 Found
[CopyLength
] = 0;
1300 } // if (EndOfElement >= StartOfElement)
1301 } // if (EndOfElement > 0)
1303 } // CHAR16 *FindLastDirName
1305 // Returns the directory portion of a pathname. For instance,
1306 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1307 // string 'EFI\foo'. The calling function is responsible for
1308 // freeing the returned string's memory.
1309 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1310 UINTN i
, LastBackslash
= 0;
1313 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1314 if (FullPath
[i
] == '\\')
1317 PathOnly
= StrDuplicate(FullPath
);
1318 PathOnly
[LastBackslash
] = 0;
1322 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1323 // DeviceVolume, and returns that and the filename (*loader).
1324 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1325 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1327 BOOLEAN Found
= FALSE
;
1329 MyFreePool(*loader
);
1330 MyFreePool(*DeviceVolume
);
1331 *DeviceVolume
= NULL
;
1332 DeviceString
= DevicePathToStr(loadpath
);
1333 *loader
= SplitDeviceString(DeviceString
);
1335 while ((i
< VolumesCount
) && (!Found
)) {
1336 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1337 Temp
= SplitDeviceString(VolumeDeviceString
);
1338 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1340 *DeviceVolume
= Volumes
[i
];
1343 MyFreePool(VolumeDeviceString
);
1347 MyFreePool(DeviceString
);
1348 } // VOID FindVolumeAndFilename()
1350 // Returns all the digits in the input string, including intervening
1351 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1352 // this function returns "3.3.4-7". If InString contains no digits,
1353 // the return value is NULL.
1354 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1355 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1356 CHAR16
*Found
= NULL
;
1358 InLength
= StartOfElement
= StrLen(InString
);
1359 // Find start & end of target element
1360 for (i
= 0; i
< InLength
; i
++) {
1361 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1362 if (StartOfElement
> i
)
1364 if (EndOfElement
< i
)
1368 // Extract the target element
1369 if (EndOfElement
> 0) {
1370 if (EndOfElement
>= StartOfElement
) {
1371 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1372 Found
= StrDuplicate(&InString
[StartOfElement
]);
1374 Found
[CopyLength
] = 0;
1375 } // if (EndOfElement >= StartOfElement)
1376 } // if (EndOfElement > 0)
1378 } // CHAR16 *FindNumbers()
1380 // Find the #Index element (numbered from 0) in a comma-delimited string
1382 // Returns the found element, or NULL if Index is out of range or InString
1383 // is NULL. Note that the calling function is responsible for freeing the
1384 // memory associated with the returned string pointer.
1385 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1386 UINTN StartPos
= 0, CurPos
= 0;
1387 BOOLEAN Found
= FALSE
;
1388 CHAR16
*FoundString
= NULL
;
1390 if (InString
!= NULL
) {
1391 // After while() loop, StartPos marks start of item #Index
1392 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1393 if (InString
[CurPos
] == L
',') {
1395 StartPos
= CurPos
+ 1;
1399 // After while() loop, CurPos is one past the end of the element
1400 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1401 if (InString
[CurPos
] == L
',')
1407 FoundString
= StrDuplicate(&InString
[StartPos
]);
1408 if (FoundString
!= NULL
)
1409 FoundString
[CurPos
- StartPos
] = 0;
1411 return (FoundString
);
1412 } // CHAR16 *FindCommaDelimited()
1414 // Returns TRUE if SmallString is an element in the comma-delimited List,
1415 // FALSE otherwise. Performs comparison case-insensitively (except on
1416 // buggy EFIs with case-sensitive StriCmp() functions).
1417 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1419 BOOLEAN Found
= FALSE
;
1422 if (SmallString
&& List
) {
1423 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1424 if (StriCmp(OneElement
, SmallString
) == 0)
1431 // Implement FreePool the way it should have been done to begin with, so that
1432 // it doesn't throw an ASSERT message if fed a NULL pointer....
1433 VOID
MyFreePool(IN OUT VOID
*Pointer
) {
1434 if (Pointer
!= NULL
)
1438 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1440 // Eject all removable media.
1441 // Returns TRUE if any media were ejected, FALSE otherwise.
1442 BOOLEAN
EjectMedia(VOID
) {
1444 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1445 EFI_HANDLE
*Handles
, Handle
;
1446 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1448 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1449 if (EFI_ERROR(Status
) || HandleCount
== 0)
1450 return (FALSE
); // probably not an Apple system
1452 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1453 Handle
= Handles
[HandleIndex
];
1454 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1455 if (EFI_ERROR(Status
))
1457 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1458 if (!EFI_ERROR(Status
))
1461 MyFreePool(Handles
);
1462 return (Ejected
> 0);
1463 } // VOID EjectMedia()
1466 // Return the GUID as a string, suitable for display to the user. Note that the calling
1467 // function is responsible for freeing the allocated memory.
1468 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
1471 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
1472 if (TheString
!= 0) {
1473 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1474 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
1475 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
1476 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
1477 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
1480 } // GuidAsString(EFI_GUID *GuidData)