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
67 // "Magic" signatures for various filesystems
68 #define FAT_MAGIC 0xAA55
69 #define EXT2_SUPER_MAGIC 0xEF53
70 #define HFSPLUS_MAGIC1 0x2B48
71 #define HFSPLUS_MAGIC2 0x5848
72 #define REISERFS_SUPER_MAGIC 0x52654973
73 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
74 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
78 EFI_HANDLE SelfImageHandle
;
79 EFI_LOADED_IMAGE
*SelfLoadedImage
;
80 EFI_FILE
*SelfRootDir
;
84 REFIT_VOLUME
*SelfVolume
= NULL
;
85 REFIT_VOLUME
**Volumes
= NULL
;
86 UINTN VolumesCount
= 0;
88 // Maximum size for disk sectors
89 #define SECTOR_SIZE 4096
91 // Default names for volume badges (mini-icon to define disk type) and icons
92 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
93 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
97 static EFI_STATUS
FinishInitRefitLib(VOID
);
99 static VOID
UninitVolumes(VOID
);
102 // self recognition stuff
105 // Converts forward slashes to backslashes, removes duplicate slashes, and
106 // removes slashes from both the start and end of the pathname.
107 // Necessary because some (buggy?) EFI implementations produce "\/" strings
108 // in pathnames, because some user inputs can produce duplicate directory
109 // separators, and because we want consistent start and end slashes for
110 // directory comparisons. A special case: If the PathName refers to root,
111 // return "/", since some firmware implementations flake out if this
113 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
115 UINTN i
, FinalChar
= 0;
116 BOOLEAN LastWasSlash
= FALSE
;
118 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 2));
119 if (NewName
!= NULL
) {
120 for (i
= 0; i
< StrLen(PathName
); i
++) {
121 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
122 if ((!LastWasSlash
) && (FinalChar
!= 0))
123 NewName
[FinalChar
++] = L
'\\';
126 NewName
[FinalChar
++] = PathName
[i
];
127 LastWasSlash
= FALSE
;
130 NewName
[FinalChar
] = 0;
131 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
132 NewName
[--FinalChar
] = 0;
133 if (FinalChar
== 0) {
137 // Copy the transformed name back....
138 StrCpy(PathName
, NewName
);
140 } // if allocation OK
141 } // CleanUpPathNameSlashes()
143 // Splits an EFI device path into device and filename components. For instance, if InString is
144 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
145 // this function will truncate that input to
146 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
147 // and return bzImage-3.5.1.efi as its return value.
148 // It does this by searching for the last ")" character in InString, copying everything
149 // after that string (after some cleanup) as the return value, and truncating the original
151 // If InString contains no ")" character, this function leaves the original input string
152 // unmodified and also returns that string.
153 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
155 CHAR16
*FileName
= NULL
;
156 BOOLEAN Found
= FALSE
;
158 i
= StrLen(InString
) - 1;
159 while ((i
>= 0) && (!Found
)) {
160 if (InString
[i
] == L
')') {
162 FileName
= StrDuplicate(&InString
[i
+ 1]);
163 CleanUpPathNameSlashes(FileName
);
164 InString
[i
+ 1] = '\0';
168 if (FileName
== NULL
)
169 FileName
= StrDuplicate(InString
);
171 } // static CHAR16* SplitDeviceString()
173 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
176 CHAR16
*DevicePathAsString
, *Temp
;
178 SelfImageHandle
= ImageHandle
;
179 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
180 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
181 return EFI_LOAD_ERROR
;
183 // find the current directory
184 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
185 CleanUpPathNameSlashes(DevicePathAsString
);
186 MyFreePool(SelfDirPath
);
187 Temp
= FindPath(DevicePathAsString
);
188 SelfDirPath
= SplitDeviceString(Temp
);
189 MyFreePool(DevicePathAsString
);
192 return FinishInitRefitLib();
195 // called before running external programs to close open file handles
196 VOID
UninitRefitLib(VOID
)
200 if (SelfDir
!= NULL
) {
201 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
205 if (SelfRootDir
!= NULL
) {
206 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
211 // called after running external programs to re-open file handles
212 EFI_STATUS
ReinitRefitLib(VOID
)
216 if ((ST
->Hdr
.Revision
>> 16) == 1) {
217 // Below two lines were in rEFIt, but seem to cause system crashes or
218 // reboots when launching OSes after returning from programs on most
219 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
220 // installation volume" (see the next function) when returning from
221 // programs when these two lines are removed, and it often crashes
222 // when returning from a program or when launching a second program
223 // with these lines removed. Therefore, the preceding if() statement
224 // executes these lines only on EFIs with a major version number of 1
225 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
226 // of hardware on which to test is limited, though, so this may be the
227 // wrong test, or there may be a better way to fix this problem.
228 // TODO: Figure out cause of above weirdness and fix it more
230 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
231 SelfRootDir
= SelfVolume
->RootDir
;
234 return FinishInitRefitLib();
237 static EFI_STATUS
FinishInitRefitLib(VOID
)
241 if (SelfRootDir
== NULL
) {
242 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
243 if (SelfRootDir
== NULL
) {
244 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
245 return EFI_LOAD_ERROR
;
249 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
250 if (CheckFatalError(Status
, L
"while opening our installation directory"))
251 return EFI_LOAD_ERROR
;
260 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
264 *ElementCount
= InitialElementCount
;
265 if (*ElementCount
> 0) {
266 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
267 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
273 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
277 if ((*ElementCount
& 7) == 0) {
278 AllocateCount
= *ElementCount
+ 8;
279 if (*ElementCount
== 0)
280 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
282 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
284 (*ListPtr
)[*ElementCount
] = NewElement
;
286 } /* VOID AddListElement() */
288 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
292 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
293 for (i
= 0; i
< *ElementCount
; i
++) {
294 // TODO: call a user-provided routine for each element here
295 MyFreePool((*ListPtr
)[i
]);
297 MyFreePool(*ListPtr
);
302 // firmware device path discovery
305 static UINT8 LegacyLoaderMediaPathData
[] = {
306 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
307 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
308 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
310 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
312 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
315 UINTN HandleCount
= 0;
316 UINTN HandleIndex
, HardcodedIndex
;
321 EFI_LOADED_IMAGE
*LoadedImage
;
322 EFI_DEVICE_PATH
*DevicePath
;
325 MaxPaths
--; // leave space for the terminating NULL pointer
327 // get all LoadedImage handles
328 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
329 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
330 if (HardcodedPathList
) {
331 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
332 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
334 PathList
[PathCount
] = NULL
;
337 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
338 Handle
= Handles
[HandleIndex
];
340 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
341 if (EFI_ERROR(Status
))
342 continue; // This can only happen if the firmware scewed up, ignore it.
344 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
345 if (EFI_ERROR(Status
))
346 continue; // This happens, ignore it.
348 // Only grab memory range nodes
349 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
352 // Check if we have this device path in the list already
353 // WARNING: This assumes the first node in the device path is unique!
355 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
356 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
358 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
366 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
370 if (HardcodedPathList
) {
371 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
372 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
374 PathList
[PathCount
] = NULL
;
381 // Return a pointer to a string containing a filesystem type name. If the
382 // filesystem type is unknown, a blank (but non-null) string is returned.
383 // The returned variable is a constant that should NOT be freed.
384 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
385 CHAR16
*retval
= NULL
;
391 case FS_TYPE_HFSPLUS
:
403 case FS_TYPE_REISERFS
:
404 retval
= L
" ReiserFS";
406 case FS_TYPE_ISO9660
:
407 retval
= L
" ISO-9660";
414 } // CHAR16 *FSTypeName()
416 // Identify the filesystem type, if possible. Expects a Buffer containing
417 // the first few (normally 4096) bytes of the filesystem, and outputs a
418 // code representing the identified filesystem type.
419 static UINT32
IdentifyFilesystemType(IN UINT8
*Buffer
, IN UINTN BufferSize
) {
420 UINT32 FoundType
= FS_TYPE_UNKNOWN
;
421 UINT32
*Ext2Incompat
, *Ext2Compat
;
424 if (Buffer
!= NULL
) {
426 if (BufferSize
>= (1024 + 100)) {
427 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
428 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
429 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
430 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
431 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
433 } else if (*Ext2Compat
& 0x0004) { // check for journal
435 } else { // none of these features; presume it's ext2...
439 } // search for ext2/3/4 magic
441 if (BufferSize
>= 512) {
442 Magic16
= (UINT16
*) (Buffer
+ 510);
443 if (*Magic16
== FAT_MAGIC
)
445 } // search for FAT magic
447 if (BufferSize
>= (1024 + 2)) {
448 Magic16
= (UINT16
*) (Buffer
+ 1024);
449 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
450 return FS_TYPE_HFSPLUS
;
452 } // search for HFS+ magic
453 } // if (Buffer != NULL)
458 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
461 UINT8 SectorBuffer
[SECTOR_SIZE
];
463 MBR_PARTITION_INFO
*MbrTable
;
464 BOOLEAN MbrTableFound
;
466 Volume
->HasBootCode
= FALSE
;
467 Volume
->OSIconName
= NULL
;
468 Volume
->OSName
= NULL
;
471 if (Volume
->BlockIO
== NULL
)
473 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
474 return; // our buffer is too small...
476 // look at the boot sector (this is used for both hard disks and El Torito images!)
477 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
478 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
479 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
480 if (!EFI_ERROR(Status
)) {
482 Volume
->FSType
= IdentifyFilesystemType(SectorBuffer
, SECTOR_SIZE
);
483 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
485 Volume
->HasBootCode
= TRUE
;
488 // detect specific boot codes
489 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
490 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
491 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
492 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
493 Volume
->HasBootCode
= TRUE
;
494 Volume
->OSIconName
= L
"linux";
495 Volume
->OSName
= L
"Linux";
497 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
498 Volume
->HasBootCode
= TRUE
;
499 Volume
->OSIconName
= L
"grub,linux";
500 Volume
->OSName
= L
"Linux";
502 // // Below doesn't produce a bootable entry, so commented out for the moment....
503 // // GRUB in BIOS boot partition:
504 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
505 // Volume->HasBootCode = TRUE;
506 // Volume->OSIconName = L"grub,linux";
507 // Volume->OSName = L"Linux";
508 // Volume->VolName = L"BIOS Boot Partition";
511 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
512 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
513 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
514 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
515 Volume
->HasBootCode
= TRUE
;
516 Volume
->OSIconName
= L
"freebsd";
517 Volume
->OSName
= L
"FreeBSD";
519 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
520 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
521 Volume
->HasBootCode
= TRUE
;
522 Volume
->OSIconName
= L
"openbsd";
523 Volume
->OSName
= L
"OpenBSD";
525 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
526 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
527 Volume
->HasBootCode
= TRUE
;
528 Volume
->OSIconName
= L
"netbsd";
529 Volume
->OSName
= L
"NetBSD";
531 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
532 Volume
->HasBootCode
= TRUE
;
533 Volume
->OSIconName
= L
"win";
534 Volume
->OSName
= L
"Windows";
536 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
537 Volume
->HasBootCode
= TRUE
;
538 Volume
->OSIconName
= L
"winvista,win";
539 Volume
->OSName
= L
"Windows";
541 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
542 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
543 Volume
->HasBootCode
= TRUE
;
544 Volume
->OSIconName
= L
"freedos";
545 Volume
->OSName
= L
"FreeDOS";
547 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
548 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
549 Volume
->HasBootCode
= TRUE
;
550 Volume
->OSIconName
= L
"ecomstation";
551 Volume
->OSName
= L
"eComStation";
553 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
554 Volume
->HasBootCode
= TRUE
;
555 Volume
->OSIconName
= L
"beos";
556 Volume
->OSName
= L
"BeOS";
558 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
559 Volume
->HasBootCode
= TRUE
;
560 Volume
->OSIconName
= L
"zeta,beos";
561 Volume
->OSName
= L
"ZETA";
563 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
564 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
565 Volume
->HasBootCode
= TRUE
;
566 Volume
->OSIconName
= L
"haiku,beos";
567 Volume
->OSName
= L
"Haiku";
571 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
572 // need to fix AddLegacyEntry in main.c.
575 Print(L
" Result of bootcode detection: %s %s (%s)\n",
576 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
577 Volume
->OSName
, Volume
->OSIconName
);
580 // dummy FAT boot sector (created by OS X's newfs_msdos)
581 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
582 Volume
->HasBootCode
= FALSE
;
584 // dummy FAT boot sector (created by Linux's mkdosfs)
585 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
586 Volume
->HasBootCode
= FALSE
;
588 // dummy FAT boot sector (created by Windows)
589 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
590 Volume
->HasBootCode
= FALSE
;
592 // check for MBR partition table
593 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
594 MbrTableFound
= FALSE
;
595 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
596 for (i
= 0; i
< 4; i
++)
597 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
598 MbrTableFound
= TRUE
;
599 for (i
= 0; i
< 4; i
++)
600 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
601 MbrTableFound
= FALSE
;
603 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
604 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
610 CheckError(Status
, L
"while reading boot sector");
615 // default volume badge icon based on disk kind
616 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
618 switch (Volume
->DiskKind
) {
619 case DISK_KIND_INTERNAL
:
620 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
622 case DISK_KIND_EXTERNAL
:
623 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
625 case DISK_KIND_OPTICAL
:
626 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
631 // Return a string representing the input size in IEEE-1541 units.
632 // The calling function is responsible for freeing the allocated memory.
633 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
636 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
639 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 80);
640 if (TheValue
!= NULL
) {
641 SizeInIeee
= (float) SizeInBytes
;
642 while ((SizeInIeee
> 1024.0) && (Index
< (StrLen(Prefixes
) - 1))) {
644 SizeInIeee
/= 1024.0;
646 if (Prefixes
[Index
] == ' ') {
647 Units
= StrDuplicate(L
"-byte");
649 Units
= StrDuplicate(L
" iB");
650 Units
[1] = Prefixes
[Index
];
652 SPrint(TheValue
, 79, L
"%d%s", (UINTN
) SizeInIeee
, Units
);
655 } // CHAR16 *SizeInSIUnits()
657 // Return a name for the volume. Ideally this should be the label for the
658 // filesystem it contains, but this function falls back to describing the
659 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
660 // this information can be extracted.
661 // The calling function is responsible for freeing the memory allocated
662 // for the name string.
663 static CHAR16
*GetVolumeName(IN REFIT_VOLUME
*Volume
) {
664 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
665 CHAR16
*FoundName
= NULL
;
666 CHAR16
*SISize
, *TypeName
;
668 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
669 if (FileSystemInfoPtr
!= NULL
) {
670 if ((FileSystemInfoPtr
->VolumeLabel
!= NULL
) && (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
671 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
674 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
675 // this so that we can build a new name that includes the size....
676 if ((FoundName
!= NULL
) && (StrCmp(FoundName
, L
"HFS+ volume") == 0) && (Volume
->FSType
== FS_TYPE_HFSPLUS
)) {
677 MyFreePool(FoundName
);
679 } // if rEFInd HFS+ driver suspected
681 if (FoundName
== NULL
) { // filesystem has no name....
682 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
683 if (FoundName
!= NULL
) {
684 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
685 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
687 } // if allocated memory OK
688 } // if (FoundName == NULL)
690 FreePool(FileSystemInfoPtr
);
693 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
694 if (FoundName
!= NULL
) {
695 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; fn returns constant
696 if (StrLen(TypeName
) > 0)
697 SPrint(FoundName
, 255, L
"%s volume", FSTypeName(Volume
->FSType
));
699 SPrint(FoundName
, 255, L
"unknown volume");
700 } // if allocated memory OK
703 // TODO: Above could be improved/extended, in case filesystem name is not found,
705 // - use partition label
706 // - use or add disk/partition number (e.g., "(hd0,2)")
708 // Desperate fallback name....
709 if (FoundName
== NULL
) {
710 FoundName
= StrDuplicate(L
"unknown volume");
713 } // static CHAR16 *GetVolumeName()
715 VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
718 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
719 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
720 EFI_HANDLE WholeDiskHandle
;
725 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
727 if (Volume
->DevicePath
!= NULL
) {
728 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
730 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
735 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
738 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
739 if (EFI_ERROR(Status
)) {
740 Volume
->BlockIO
= NULL
;
741 Print(L
"Warning: Can't get BlockIO protocol.\n");
743 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
744 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
747 // scan for bootcode and MBR table
749 ScanVolumeBootcode(Volume
, &Bootable
);
751 // detect device type
752 DevicePath
= Volume
->DevicePath
;
753 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
754 NextDevicePath
= NextDevicePathNode(DevicePath
);
756 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
757 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
758 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
759 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
760 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
761 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
762 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
763 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
764 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
768 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
769 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
770 // TODO: also check for Boot Camp GUID
771 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
774 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
775 // make a device path for the whole device
776 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
777 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
778 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
779 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
781 // get the handle for that path
782 RemainingDevicePath
= DiskDevicePath
;
783 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
784 FreePool(DiskDevicePath
);
786 if (!EFI_ERROR(Status
)) {
787 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
789 // get the device path for later
790 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
791 if (!EFI_ERROR(Status
)) {
792 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
795 // look at the BlockIO protocol
796 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
797 if (!EFI_ERROR(Status
)) {
799 // check the media block size
800 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
801 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
804 Volume
->WholeDiskBlockIO
= NULL
;
805 //CheckError(Status, L"from HandleProtocol");
808 // CheckError(Status, L"from LocateDevicePath");
811 DevicePath
= NextDevicePath
;
816 if (Volume
->HasBootCode
)
817 Print(L
" Volume considered non-bootable, but boot code is present\n");
819 Volume
->HasBootCode
= FALSE
;
822 // default volume icon based on disk kind
823 ScanVolumeDefaultIcon(Volume
);
825 // open the root directory of the volume
826 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
827 if (Volume
->RootDir
== NULL
) {
828 Volume
->IsReadable
= FALSE
;
831 Volume
->IsReadable
= TRUE
;
834 Volume
->VolName
= GetVolumeName(Volume
);
836 // get custom volume icon if present
837 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
838 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
839 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
840 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
844 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
847 REFIT_VOLUME
*Volume
;
848 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
850 UINTN LogicalPartitionIndex
= 4;
851 UINT8 SectorBuffer
[512];
853 MBR_PARTITION_INFO
*EMbrTable
;
855 ExtBase
= MbrEntry
->StartLBA
;
857 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
859 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
860 WholeDiskVolume
->BlockIO
,
861 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
862 ExtCurrent
, 512, SectorBuffer
);
863 if (EFI_ERROR(Status
))
865 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
867 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
869 // scan logical partitions in this EMBR
871 for (i
= 0; i
< 4; i
++) {
872 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
873 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
875 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
876 // set next ExtCurrent
877 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
881 // found a logical partition
882 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
883 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
884 Volume
->IsMbrPartition
= TRUE
;
885 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
886 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
887 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
888 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
889 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
890 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
893 ScanVolumeBootcode(Volume
, &Bootable
);
895 Volume
->HasBootCode
= FALSE
;
897 ScanVolumeDefaultIcon(Volume
);
899 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
906 VOID
ScanVolumes(VOID
)
909 UINTN HandleCount
= 0;
912 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
913 UINTN VolumeIndex
, VolumeIndex2
;
914 MBR_PARTITION_INFO
*MbrTable
;
915 UINTN PartitionIndex
;
916 UINT8
*SectorBuffer1
, *SectorBuffer2
;
923 // get all filesystem handles
924 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
925 // was: &FileSystemProtocol
926 if (Status
== EFI_NOT_FOUND
) {
927 return; // no filesystems. strange, but true...
929 if (CheckError(Status
, L
"while listing all file systems"))
932 // first pass: collect information about all handles
933 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
934 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
935 Volume
->DeviceHandle
= Handles
[HandleIndex
];
938 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
940 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
945 if (SelfVolume
== NULL
)
946 Print(L
"WARNING: SelfVolume not found");
948 // second pass: relate partitions and whole disk devices
949 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
950 Volume
= Volumes
[VolumeIndex
];
951 // check MBR partition table for extended partitions
952 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
953 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
954 Volume
->MbrPartitionTable
!= NULL
) {
955 MbrTable
= Volume
->MbrPartitionTable
;
956 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
957 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
958 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
963 // search for corresponding whole disk volume entry
964 WholeDiskVolume
= NULL
;
965 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
966 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
967 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
968 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
969 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
970 WholeDiskVolume
= Volumes
[VolumeIndex2
];
974 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
975 // check if this volume is one of the partitions in the table
976 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
977 SectorBuffer1
= AllocatePool(512);
978 SectorBuffer2
= AllocatePool(512);
979 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
981 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
984 // compare boot sector read through offset vs. directly
985 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
986 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
987 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
988 if (EFI_ERROR(Status
))
990 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
991 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
992 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
993 if (EFI_ERROR(Status
))
995 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
998 for (i
= 0; i
< 512; i
++)
999 SectorSum
+= SectorBuffer1
[i
];
1000 if (SectorSum
< 1000)
1003 // TODO: mark entry as non-bootable if it is an extended partition
1005 // now we're reasonably sure the association is correct...
1006 Volume
->IsMbrPartition
= TRUE
;
1007 Volume
->MbrPartitionIndex
= PartitionIndex
;
1008 if (Volume
->VolName
== NULL
) {
1009 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1010 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1015 MyFreePool(SectorBuffer1
);
1016 MyFreePool(SectorBuffer2
);
1020 } /* VOID ScanVolumes() */
1022 static VOID
UninitVolumes(VOID
)
1024 REFIT_VOLUME
*Volume
;
1027 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1028 Volume
= Volumes
[VolumeIndex
];
1030 if (Volume
->RootDir
!= NULL
) {
1031 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
1032 Volume
->RootDir
= NULL
;
1035 Volume
->DeviceHandle
= NULL
;
1036 Volume
->BlockIO
= NULL
;
1037 Volume
->WholeDiskBlockIO
= NULL
;
1041 VOID
ReinitVolumes(VOID
)
1044 REFIT_VOLUME
*Volume
;
1046 EFI_DEVICE_PATH
*RemainingDevicePath
;
1047 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
1049 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1050 Volume
= Volumes
[VolumeIndex
];
1052 if (Volume
->DevicePath
!= NULL
) {
1053 // get the handle for that path
1054 RemainingDevicePath
= Volume
->DevicePath
;
1055 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
1057 if (!EFI_ERROR(Status
)) {
1058 Volume
->DeviceHandle
= DeviceHandle
;
1060 // get the root directory
1061 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1064 CheckError(Status
, L
"from LocateDevicePath");
1067 if (Volume
->WholeDiskDevicePath
!= NULL
) {
1068 // get the handle for that path
1069 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
1070 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
1072 if (!EFI_ERROR(Status
)) {
1073 // get the BlockIO protocol
1074 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
1075 if (EFI_ERROR(Status
)) {
1076 Volume
->WholeDiskBlockIO
= NULL
;
1077 CheckError(Status
, L
"from HandleProtocol");
1080 CheckError(Status
, L
"from LocateDevicePath");
1086 // file and dir functions
1089 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1092 EFI_FILE_HANDLE TestFile
;
1094 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1095 if (Status
== EFI_SUCCESS
) {
1096 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1102 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1106 UINTN LastBufferSize
, BufferSize
;
1111 // free pointer from last call
1112 if (*DirEntry
!= NULL
) {
1113 FreePool(*DirEntry
);
1117 // read next directory entry
1118 LastBufferSize
= BufferSize
= 256;
1119 Buffer
= AllocatePool(BufferSize
);
1120 for (IterCount
= 0; ; IterCount
++) {
1121 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1122 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1124 if (BufferSize
<= LastBufferSize
) {
1125 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1126 BufferSize
= LastBufferSize
* 2;
1129 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1132 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1133 LastBufferSize
= BufferSize
;
1135 if (EFI_ERROR(Status
)) {
1140 // check for end of listing
1141 if (BufferSize
== 0) { // end of directory listing
1146 // entry is ready to be returned
1147 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1150 if (FilterMode
== 1) { // only return directories
1151 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1153 } else if (FilterMode
== 2) { // only return files
1154 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1156 } else // no filter or unknown filter -> return everything
1163 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1165 if (RelativePath
== NULL
) {
1166 DirIter
->LastStatus
= EFI_SUCCESS
;
1167 DirIter
->DirHandle
= BaseDir
;
1168 DirIter
->CloseDirHandle
= FALSE
;
1170 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1171 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1173 DirIter
->LastFileInfo
= NULL
;
1176 #ifndef __MAKEWITH_GNUEFI
1177 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1180 InitializeUnicodeCollationProtocol (VOID
)
1184 if (mUnicodeCollation
!= NULL
) {
1189 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1190 // instances first and then select one which support English language.
1191 // Current implementation just pick the first instance.
1193 Status
= gBS
->LocateProtocol (
1194 &gEfiUnicodeCollation2ProtocolGuid
,
1196 (VOID
**) &mUnicodeCollation
1198 if (EFI_ERROR(Status
)) {
1199 Status
= gBS
->LocateProtocol (
1200 &gEfiUnicodeCollationProtocolGuid
,
1202 (VOID
**) &mUnicodeCollation
1210 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1212 if (!mUnicodeCollation
) {
1213 InitializeUnicodeCollationProtocol();
1215 if (mUnicodeCollation
)
1216 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1217 return FALSE
; // Shouldn't happen
1220 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1221 if (!mUnicodeCollation
) {
1222 InitializeUnicodeCollationProtocol();
1224 if (mUnicodeCollation
)
1225 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1230 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1231 OUT EFI_FILE_INFO
**DirEntry
)
1233 BOOLEAN KeepGoing
= TRUE
;
1237 if (DirIter
->LastFileInfo
!= NULL
) {
1238 FreePool(DirIter
->LastFileInfo
);
1239 DirIter
->LastFileInfo
= NULL
;
1242 if (EFI_ERROR(DirIter
->LastStatus
))
1243 return FALSE
; // stop iteration
1246 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1247 if (EFI_ERROR(DirIter
->LastStatus
))
1249 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1251 if (FilePattern
!= NULL
) {
1252 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1255 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1256 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1259 // else continue loop
1262 } while (KeepGoing
);
1264 *DirEntry
= DirIter
->LastFileInfo
;
1268 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1270 if (DirIter
->LastFileInfo
!= NULL
) {
1271 FreePool(DirIter
->LastFileInfo
);
1272 DirIter
->LastFileInfo
= NULL
;
1274 if (DirIter
->CloseDirHandle
)
1275 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1276 return DirIter
->LastStatus
;
1280 // file name manipulation
1283 // Returns the filename portion (minus path name) of the
1285 CHAR16
* Basename(IN CHAR16
*Path
)
1293 for (i
= StrLen(Path
); i
> 0; i
--) {
1294 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1295 FileName
= Path
+ i
;
1304 // Replaces a filename extension of ".efi" with the specified string
1305 // (Extension). If the input Path doesn't end in ".efi", Extension
1306 // is added to the existing filename.
1307 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1311 PathLen
= StrLen(Path
);
1312 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1313 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1314 Path
[PathLen
- 4] = 0;
1316 StrCat(Path
, Extension
);
1317 } // VOID ReplaceEfiExtension()
1320 // memory string search
1323 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1329 BufferLength
-= SearchStringLength
;
1330 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1331 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1332 return (INTN
)Offset
;
1338 // Performs a case-insensitive search of BigStr for SmallStr.
1339 // Returns TRUE if found, FALSE if not.
1340 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1341 CHAR16
*SmallCopy
, *BigCopy
;
1342 BOOLEAN Found
= FALSE
;
1343 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1345 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1346 SmallCopy
= StrDuplicate(SmallStr
);
1347 BigCopy
= StrDuplicate(BigStr
);
1350 SmallLen
= StrLen(SmallCopy
);
1351 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1352 while ((!Found
) && (StartPoint
< NumCompares
)) {
1353 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1355 MyFreePool(SmallCopy
);
1356 MyFreePool(BigCopy
);
1360 } // BOOLEAN StriSubCmp()
1362 // Merges two strings, creating a new one and returning a pointer to it.
1363 // If AddChar != 0, the specified character is placed between the two original
1364 // strings (unless the first string is NULL). The original input string
1365 // *First is de-allocated and replaced by the new merged string.
1366 // This is similar to StrCat, but safer and more flexible because
1367 // MergeStrings allocates memory that's the correct size for the
1368 // new merged string, so it can take a NULL *First and it cleans
1369 // up the old memory. It should *NOT* be used with a constant
1370 // *First, though....
1371 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1372 UINTN Length1
= 0, Length2
= 0;
1376 Length1
= StrLen(*First
);
1378 Length2
= StrLen(Second
);
1379 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1380 if (NewString
!= NULL
) {
1381 NewString
[0] = L
'\0';
1382 if (*First
!= NULL
) {
1383 StrCat(NewString
, *First
);
1385 NewString
[Length1
] = AddChar
;
1386 NewString
[Length1
+ 1] = '\0';
1388 } // if (*First != NULL)
1390 StrCat(NewString
, Second
);
1394 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1396 } // static CHAR16* MergeStrings()
1398 // Takes an input pathname (*Path) and returns the part of the filename from
1399 // the final dot onwards, converted to lowercase. If the filename includes
1400 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1401 // The calling function is responsible for freeing the memory associated with
1402 // the return value.
1403 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1405 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1408 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1411 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1412 if (Path
[i
] == L
'.')
1414 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1420 MergeStrings(&Extension
, &Path
[i
], 0);
1425 } // CHAR16 *FindExtension
1427 // Takes an input pathname (*Path) and locates the final directory component
1428 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1429 // function returns the string 'foo'.
1430 // Assumes the pathname is separated with backslashes.
1431 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1432 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1433 CHAR16
*Found
= NULL
;
1435 PathLength
= StrLen(Path
);
1436 // Find start & end of target element
1437 for (i
= 0; i
< PathLength
; i
++) {
1438 if (Path
[i
] == '\\') {
1439 StartOfElement
= EndOfElement
;
1443 // Extract the target element
1444 if (EndOfElement
> 0) {
1445 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1449 if (EndOfElement
>= StartOfElement
) {
1450 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1451 Found
= StrDuplicate(&Path
[StartOfElement
]);
1453 Found
[CopyLength
] = 0;
1454 } // if (EndOfElement >= StartOfElement)
1455 } // if (EndOfElement > 0)
1457 } // CHAR16 *FindLastDirName
1459 // Returns the directory portion of a pathname. For instance,
1460 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1461 // string 'EFI\foo'. The calling function is responsible for
1462 // freeing the returned string's memory.
1463 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1464 UINTN i
, LastBackslash
= 0;
1467 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1468 if (FullPath
[i
] == '\\')
1471 PathOnly
= StrDuplicate(FullPath
);
1472 PathOnly
[LastBackslash
] = 0;
1476 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1477 // DeviceVolume, and returns that and the filename (*loader).
1478 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1479 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1481 BOOLEAN Found
= FALSE
;
1483 MyFreePool(*loader
);
1484 MyFreePool(*DeviceVolume
);
1485 *DeviceVolume
= NULL
;
1486 DeviceString
= DevicePathToStr(loadpath
);
1487 *loader
= SplitDeviceString(DeviceString
);
1489 while ((i
< VolumesCount
) && (!Found
)) {
1490 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1491 Temp
= SplitDeviceString(VolumeDeviceString
);
1492 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1494 *DeviceVolume
= Volumes
[i
];
1497 MyFreePool(VolumeDeviceString
);
1501 MyFreePool(DeviceString
);
1502 } // VOID FindVolumeAndFilename()
1504 // Returns all the digits in the input string, including intervening
1505 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1506 // this function returns "3.3.4-7". If InString contains no digits,
1507 // the return value is NULL.
1508 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1509 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1510 CHAR16
*Found
= NULL
;
1512 InLength
= StartOfElement
= StrLen(InString
);
1513 // Find start & end of target element
1514 for (i
= 0; i
< InLength
; i
++) {
1515 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1516 if (StartOfElement
> i
)
1518 if (EndOfElement
< i
)
1522 // Extract the target element
1523 if (EndOfElement
> 0) {
1524 if (EndOfElement
>= StartOfElement
) {
1525 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1526 Found
= StrDuplicate(&InString
[StartOfElement
]);
1528 Found
[CopyLength
] = 0;
1529 } // if (EndOfElement >= StartOfElement)
1530 } // if (EndOfElement > 0)
1532 } // CHAR16 *FindNumbers()
1534 // Find the #Index element (numbered from 0) in a comma-delimited string
1536 // Returns the found element, or NULL if Index is out of range or InString
1537 // is NULL. Note that the calling function is responsible for freeing the
1538 // memory associated with the returned string pointer.
1539 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1540 UINTN StartPos
= 0, CurPos
= 0;
1541 BOOLEAN Found
= FALSE
;
1542 CHAR16
*FoundString
= NULL
;
1544 if (InString
!= NULL
) {
1545 // After while() loop, StartPos marks start of item #Index
1546 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1547 if (InString
[CurPos
] == L
',') {
1549 StartPos
= CurPos
+ 1;
1553 // After while() loop, CurPos is one past the end of the element
1554 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1555 if (InString
[CurPos
] == L
',')
1561 FoundString
= StrDuplicate(&InString
[StartPos
]);
1562 if (FoundString
!= NULL
)
1563 FoundString
[CurPos
- StartPos
] = 0;
1565 return (FoundString
);
1566 } // CHAR16 *FindCommaDelimited()
1568 // Returns TRUE if SmallString is an element in the comma-delimited List,
1569 // FALSE otherwise. Performs comparison case-insensitively (except on
1570 // buggy EFIs with case-sensitive StriCmp() functions).
1571 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1573 BOOLEAN Found
= FALSE
;
1576 if (SmallString
&& List
) {
1577 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1578 if (StriCmp(OneElement
, SmallString
) == 0)
1585 // Implement FreePool the way it should have been done to begin with, so that
1586 // it doesn't throw an ASSERT message if fed a NULL pointer....
1587 VOID
MyFreePool(IN OUT VOID
*Pointer
) {
1588 if (Pointer
!= NULL
)
1592 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1594 // Eject all removable media.
1595 // Returns TRUE if any media were ejected, FALSE otherwise.
1596 BOOLEAN
EjectMedia(VOID
) {
1598 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1599 EFI_HANDLE
*Handles
, Handle
;
1600 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1602 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1603 if (EFI_ERROR(Status
) || HandleCount
== 0)
1604 return (FALSE
); // probably not an Apple system
1606 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1607 Handle
= Handles
[HandleIndex
];
1608 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1609 if (EFI_ERROR(Status
))
1611 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1612 if (!EFI_ERROR(Status
))
1615 MyFreePool(Handles
);
1616 return (Ejected
> 0);
1617 } // VOID EjectMedia()
1620 // // Return the GUID as a string, suitable for display to the user. Note that the calling
1621 // // function is responsible for freeing the allocated memory.
1622 // CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1623 // CHAR16 *TheString;
1625 // TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1626 // if (TheString != 0) {
1627 // SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1628 // (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1629 // (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1630 // (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1631 // (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1633 // return TheString;
1634 // } // GuidAsString(EFI_GUID *GuidData)