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-2015 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"
53 #include "../EfiLib/LegacyBios.h"
55 #ifdef __MAKEWITH_GNUEFI
56 #define EfiReallocatePool ReallocatePool
58 #define LibLocateHandle gBS->LocateHandleBuffer
59 #define DevicePathProtocol gEfiDevicePathProtocolGuid
60 #define BlockIoProtocol gEfiBlockIoProtocolGuid
61 #define LibFileSystemInfo EfiLibFileSystemInfo
62 #define LibOpenRoot EfiLibOpenRoot
63 EFI_DEVICE_PATH EndDevicePath
[] = {
64 {END_DEVICE_PATH_TYPE
, END_ENTIRE_DEVICE_PATH_SUBTYPE
, {END_DEVICE_PATH_LENGTH
, 0}}
67 //#define EndDevicePath DevicePath
70 // "Magic" signatures for various filesystems
71 #define FAT_MAGIC 0xAA55
72 #define EXT2_SUPER_MAGIC 0xEF53
73 #define HFSPLUS_MAGIC1 0x2B48
74 #define HFSPLUS_MAGIC2 0x5848
75 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
76 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
77 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
78 #define BTRFS_SIGNATURE "_BHRfS_M"
79 #define XFS_SIGNATURE "XFSB"
80 #define NTFS_SIGNATURE "NTFS "
84 EFI_HANDLE SelfImageHandle
;
85 EFI_LOADED_IMAGE
*SelfLoadedImage
;
86 EFI_FILE
*SelfRootDir
;
90 REFIT_VOLUME
*SelfVolume
= NULL
;
91 REFIT_VOLUME
**Volumes
= NULL
;
92 UINTN VolumesCount
= 0;
93 extern GPT_DATA
*gPartitions
;
95 // Maximum size for disk sectors
96 #define SECTOR_SIZE 4096
98 // Number of bytes to read from a partition to determine its filesystem type
99 // and identify its boot loader, and hence probable BIOS-mode OS installation
100 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
105 static EFI_STATUS
FinishInitRefitLib(VOID
);
107 static VOID
UninitVolumes(VOID
);
110 // self recognition stuff
113 // Converts forward slashes to backslashes, removes duplicate slashes, and
114 // removes slashes from both the start and end of the pathname.
115 // Necessary because some (buggy?) EFI implementations produce "\/" strings
116 // in pathnames, because some user inputs can produce duplicate directory
117 // separators, and because we want consistent start and end slashes for
118 // directory comparisons. A special case: If the PathName refers to root,
119 // return "/", since some firmware implementations flake out if this
121 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
123 UINTN i
, Length
, FinalChar
= 0;
124 BOOLEAN LastWasSlash
= FALSE
;
126 Length
= StrLen(PathName
);
127 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (Length
+ 2));
128 if (NewName
!= NULL
) {
129 for (i
= 0; i
< StrLen(PathName
); i
++) {
130 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
131 if ((!LastWasSlash
) && (FinalChar
!= 0))
132 NewName
[FinalChar
++] = L
'\\';
135 NewName
[FinalChar
++] = PathName
[i
];
136 LastWasSlash
= FALSE
;
139 NewName
[FinalChar
] = 0;
140 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
141 NewName
[--FinalChar
] = 0;
142 if (FinalChar
== 0) {
146 // Copy the transformed name back....
147 StrCpy(PathName
, NewName
);
149 } // if allocation OK
150 } // CleanUpPathNameSlashes()
152 // Splits an EFI device path into device and filename components. For instance, if InString is
153 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
154 // this function will truncate that input to
155 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
156 // and return bzImage-3.5.1.efi as its return value.
157 // It does this by searching for the last ")" character in InString, copying everything
158 // after that string (after some cleanup) as the return value, and truncating the original
160 // If InString contains no ")" character, this function leaves the original input string
161 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
162 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
164 CHAR16
*FileName
= NULL
;
165 BOOLEAN Found
= FALSE
;
167 if (InString
!= NULL
) {
168 i
= StrLen(InString
) - 1;
169 while ((i
>= 0) && (!Found
)) {
170 if (InString
[i
] == L
')') {
172 FileName
= StrDuplicate(&InString
[i
+ 1]);
173 CleanUpPathNameSlashes(FileName
);
174 InString
[i
+ 1] = '\0';
178 if (FileName
== NULL
)
179 FileName
= StrDuplicate(InString
);
182 } // static CHAR16* SplitDeviceString()
184 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
187 CHAR16
*DevicePathAsString
, *Temp
;
189 SelfImageHandle
= ImageHandle
;
190 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
191 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
192 return EFI_LOAD_ERROR
;
194 // find the current directory
195 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
196 CleanUpPathNameSlashes(DevicePathAsString
);
197 MyFreePool(SelfDirPath
);
198 Temp
= FindPath(DevicePathAsString
);
199 SelfDirPath
= SplitDeviceString(Temp
);
200 MyFreePool(DevicePathAsString
);
203 return FinishInitRefitLib();
206 // called before running external programs to close open file handles
207 VOID
UninitRefitLib(VOID
)
209 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
210 // See the comment on it there.
211 if(SelfRootDir
== SelfVolume
->RootDir
)
216 if (SelfDir
!= NULL
) {
217 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
221 if (SelfRootDir
!= NULL
) {
222 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
227 // called after running external programs to re-open file handles
228 EFI_STATUS
ReinitRefitLib(VOID
)
232 if ((ST
->Hdr
.Revision
>> 16) == 1) {
233 // Below two lines were in rEFIt, but seem to cause system crashes or
234 // reboots when launching OSes after returning from programs on most
235 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
236 // installation volume" (see the next function) when returning from
237 // programs when these two lines are removed, and it often crashes
238 // when returning from a program or when launching a second program
239 // with these lines removed. Therefore, the preceding if() statement
240 // executes these lines only on EFIs with a major version number of 1
241 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
242 // of hardware on which to test is limited, though, so this may be the
243 // wrong test, or there may be a better way to fix this problem.
244 // TODO: Figure out cause of above weirdness and fix it more
246 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
247 SelfRootDir
= SelfVolume
->RootDir
;
250 return FinishInitRefitLib();
253 static EFI_STATUS
FinishInitRefitLib(VOID
)
257 if (SelfRootDir
== NULL
) {
258 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
259 if (SelfRootDir
== NULL
) {
260 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
261 return EFI_LOAD_ERROR
;
265 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
266 if (CheckFatalError(Status
, L
"while opening our installation directory"))
267 return EFI_LOAD_ERROR
;
273 // EFI variable read and write functions
276 // From gummiboot: Retrieve a raw EFI variable.
277 // Returns EFI status
278 EFI_STATUS
EfivarGetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
**buffer
, UINTN
*size
) {
283 l
= sizeof(CHAR16
*) * EFI_MAXIMUM_VARIABLE_SIZE
;
284 buf
= AllocatePool(l
);
286 return EFI_OUT_OF_RESOURCES
;
288 err
= refit_call5_wrapper(RT
->GetVariable
, name
, vendor
, NULL
, &l
, buf
);
289 if (EFI_ERROR(err
) == EFI_SUCCESS
) {
296 } // EFI_STATUS EfivarGetRaw()
298 // From gummiboot: Set an EFI variable
299 EFI_STATUS
EfivarSetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
*buf
, UINTN size
, BOOLEAN persistent
) {
302 flags
= EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
304 flags
|= EFI_VARIABLE_NON_VOLATILE
;
306 return refit_call5_wrapper(RT
->SetVariable
, name
, vendor
, flags
, size
, buf
);
307 } // EFI_STATUS EfivarSetRaw()
313 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
317 *ElementCount
= InitialElementCount
;
318 if (*ElementCount
> 0) {
319 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
320 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
326 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
330 if ((*ElementCount
& 7) == 0) {
331 AllocateCount
= *ElementCount
+ 8;
332 if (*ElementCount
== 0)
333 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
335 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
337 (*ListPtr
)[*ElementCount
] = NewElement
;
339 } /* VOID AddListElement() */
341 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
345 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
346 for (i
= 0; i
< *ElementCount
; i
++) {
347 // TODO: call a user-provided routine for each element here
348 MyFreePool((*ListPtr
)[i
]);
350 MyFreePool(*ListPtr
);
355 // firmware device path discovery
358 static UINT8 LegacyLoaderMediaPathData
[] = {
359 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
360 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
361 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
363 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
365 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
368 UINTN HandleCount
= 0;
369 UINTN HandleIndex
, HardcodedIndex
;
374 EFI_LOADED_IMAGE
*LoadedImage
;
375 EFI_DEVICE_PATH
*DevicePath
;
378 MaxPaths
--; // leave space for the terminating NULL pointer
380 // get all LoadedImage handles
381 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
382 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
383 if (HardcodedPathList
) {
384 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
385 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
387 PathList
[PathCount
] = NULL
;
390 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
391 Handle
= Handles
[HandleIndex
];
393 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
394 if (EFI_ERROR(Status
))
395 continue; // This can only happen if the firmware scewed up, ignore it.
397 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
398 if (EFI_ERROR(Status
))
399 continue; // This happens, ignore it.
401 // Only grab memory range nodes
402 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
405 // Check if we have this device path in the list already
406 // WARNING: This assumes the first node in the device path is unique!
408 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
409 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
411 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
419 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
423 if (HardcodedPathList
) {
424 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
425 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
427 PathList
[PathCount
] = NULL
;
434 // Return a pointer to a string containing a filesystem type name. If the
435 // filesystem type is unknown, a blank (but non-null) string is returned.
436 // The returned variable is a constant that should NOT be freed.
437 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
438 CHAR16
*retval
= NULL
;
441 case FS_TYPE_WHOLEDISK
:
442 retval
= L
" whole disk";
447 case FS_TYPE_HFSPLUS
:
459 case FS_TYPE_REISERFS
:
460 retval
= L
" ReiserFS";
468 case FS_TYPE_ISO9660
:
469 retval
= L
" ISO-9660";
479 } // CHAR16 *FSTypeName()
481 // Identify the filesystem type and record the filesystem's UUID/serial number,
482 // if possible. Expects a Buffer containing the first few (normally at least
483 // 4096) bytes of the filesystem. Sets the filesystem type code in Volume->FSType
484 // and the UUID/serial number in Volume->VolUuid. Note that the UUID value is
485 // recognized differently for each filesystem, and is currently supported only
486 // for NTFS, ext2/3/4fs, and ReiserFS (and for NTFS it's really a 64-bit serial
487 // number not a UUID or GUID). If the UUID can't be determined, it's set to 0.
488 // Also, the UUID is just read directly into memory; it is *NOT* valid when
489 // displayed by GuidAsString() or used in other GUID/UUID-manipulating
490 // functions. (As I write, it's being used merely to detect partitions that are
491 // part of a RAID 1 array.)
492 static VOID
SetFilesystemData(IN UINT8
*Buffer
, IN UINTN BufferSize
, IN OUT REFIT_VOLUME
*Volume
) {
493 UINT32
*Ext2Incompat
, *Ext2Compat
;
498 if ((Buffer
!= NULL
) && (Volume
!= NULL
)) {
499 SetMem(&(Volume
->VolUuid
), sizeof(EFI_GUID
), 0);
500 Volume
->FSType
= FS_TYPE_UNKNOWN
;
502 if (BufferSize
>= (1024 + 100)) {
503 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
504 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
505 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
506 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
507 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
508 Volume
->FSType
= FS_TYPE_EXT4
;
509 } else if (*Ext2Compat
& 0x0004) { // check for journal
510 Volume
->FSType
= FS_TYPE_EXT3
;
511 } else { // none of these features; presume it's ext2...
512 Volume
->FSType
= FS_TYPE_EXT2
;
514 CopyMem(&(Volume
->VolUuid
), Buffer
+ 1024 + 104, sizeof(EFI_GUID
));
517 } // search for ext2/3/4 magic
519 if (BufferSize
>= (65536 + 100)) {
520 MagicString
= (char*) (Buffer
+ 65536 + 52);
521 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
522 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
523 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
524 Volume
->FSType
= FS_TYPE_REISERFS
;
525 CopyMem(&(Volume
->VolUuid
), Buffer
+ 65536 + 84, sizeof(EFI_GUID
));
528 } // search for ReiserFS magic
530 if (BufferSize
>= (65536 + 64 + 8)) {
531 MagicString
= (char*) (Buffer
+ 65536 + 64);
532 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0) {
533 Volume
->FSType
= FS_TYPE_BTRFS
;
536 } // search for Btrfs magic
538 if (BufferSize
>= 512) {
539 MagicString
= (char*) Buffer
;
540 if (CompareMem(MagicString
, XFS_SIGNATURE
, 4) == 0) {
541 Volume
->FSType
= FS_TYPE_XFS
;
544 } // search for XFS magic
546 if (BufferSize
>= (1024 + 2)) {
547 Magic16
= (UINT16
*) (Buffer
+ 1024);
548 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
549 Volume
->FSType
= FS_TYPE_HFSPLUS
;
552 } // search for HFS+ magic
554 if (BufferSize
>= 512) {
555 // Search for NTFS, FAT, and MBR/EBR.
556 // These all have 0xAA55 at the end of the first sector, but FAT and
557 // MBR/EBR are not easily distinguished. Thus, we first look for NTFS
558 // "magic"; then check to see if the volume can be mounted, thus
559 // relying on the EFI's built-in FAT driver to identify FAT; and then
560 // check to see if the "volume" is in fact a whole-disk device.
561 Magic16
= (UINT16
*) (Buffer
+ 510);
562 if (*Magic16
== FAT_MAGIC
) {
563 MagicString
= (char*) (Buffer
+ 3);
564 if (CompareMem(MagicString
, NTFS_SIGNATURE
, 8) == 0) {
565 Volume
->FSType
= FS_TYPE_NTFS
;
566 CopyMem(&(Volume
->VolUuid
), Buffer
+ 0x48, sizeof(UINT64
));
568 RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
569 if (RootDir
!= NULL
) {
570 Volume
->FSType
= FS_TYPE_FAT
;
571 } else if (!Volume
->BlockIO
->Media
->LogicalPartition
) {
572 Volume
->FSType
= FS_TYPE_WHOLEDISK
;
577 } // search for FAT and NTFS magic
579 // If no other filesystem is identified and block size is right, assume
581 if (Volume
->BlockIO
->Media
->BlockSize
== 2048) {
582 Volume
->FSType
= FS_TYPE_ISO9660
;
586 } // if ((Buffer != NULL) && (Volume != NULL))
588 } // UINT32 SetFilesystemData()
590 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
593 UINT8 Buffer
[SAMPLE_SIZE
];
595 MBR_PARTITION_INFO
*MbrTable
;
596 BOOLEAN MbrTableFound
= FALSE
;
598 Volume
->HasBootCode
= FALSE
;
599 Volume
->OSIconName
= NULL
;
600 Volume
->OSName
= NULL
;
603 if (Volume
->BlockIO
== NULL
)
605 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
606 return; // our buffer is too small...
608 // look at the boot sector (this is used for both hard disks and El Torito images!)
609 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
610 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
611 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
612 if (!EFI_ERROR(Status
)) {
613 SetFilesystemData(Buffer
, SAMPLE_SIZE
, Volume
);
615 if ((Status
== EFI_SUCCESS
) && (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)) {
616 if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) && (FindMem(Buffer
, 512, "EXFAT", 5) == -1)) {
618 Volume
->HasBootCode
= TRUE
;
621 // detect specific boot codes
622 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
623 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
624 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
625 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
626 Volume
->HasBootCode
= TRUE
;
627 Volume
->OSIconName
= L
"linux";
628 Volume
->OSName
= L
"Linux";
630 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
631 Volume
->HasBootCode
= TRUE
;
632 Volume
->OSIconName
= L
"grub,linux";
633 Volume
->OSName
= L
"Linux";
635 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
636 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
637 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
638 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
639 Volume
->HasBootCode
= TRUE
;
640 Volume
->OSIconName
= L
"freebsd";
641 Volume
->OSName
= L
"FreeBSD";
643 // If more differentiation needed, also search for
644 // "Invalid partition table" &/or "Missing boot loader".
645 } else if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55) &&
646 (FindMem(Buffer
, SECTOR_SIZE
, "Boot loader too large", 21) >= 0) &&
647 (FindMem(Buffer
, SECTOR_SIZE
, "I/O error loading boot loader", 29) >= 0)) {
648 Volume
->HasBootCode
= TRUE
;
649 Volume
->OSIconName
= L
"freebsd";
650 Volume
->OSName
= L
"FreeBSD";
652 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
653 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
654 Volume
->HasBootCode
= TRUE
;
655 Volume
->OSIconName
= L
"openbsd";
656 Volume
->OSName
= L
"OpenBSD";
658 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
659 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
660 Volume
->HasBootCode
= TRUE
;
661 Volume
->OSIconName
= L
"netbsd";
662 Volume
->OSName
= L
"NetBSD";
664 // Windows NT/200x/XP
665 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
666 Volume
->HasBootCode
= TRUE
;
667 Volume
->OSIconName
= L
"win";
668 Volume
->OSName
= L
"Windows";
671 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
672 Volume
->HasBootCode
= TRUE
;
673 Volume
->OSIconName
= L
"win8,win";
674 Volume
->OSName
= L
"Windows";
676 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
677 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
678 Volume
->HasBootCode
= TRUE
;
679 Volume
->OSIconName
= L
"freedos";
680 Volume
->OSName
= L
"FreeDOS";
682 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
683 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
684 Volume
->HasBootCode
= TRUE
;
685 Volume
->OSIconName
= L
"ecomstation";
686 Volume
->OSName
= L
"eComStation";
688 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
689 Volume
->HasBootCode
= TRUE
;
690 Volume
->OSIconName
= L
"beos";
691 Volume
->OSName
= L
"BeOS";
693 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
694 Volume
->HasBootCode
= TRUE
;
695 Volume
->OSIconName
= L
"zeta,beos";
696 Volume
->OSName
= L
"ZETA";
698 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
699 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
700 Volume
->HasBootCode
= TRUE
;
701 Volume
->OSIconName
= L
"haiku,beos";
702 Volume
->OSName
= L
"Haiku";
706 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
707 // need to fix AddLegacyEntry in refind/legacy.c.
710 Print(L
" Result of bootcode detection: %s %s (%s)\n",
711 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
712 Volume
->OSName
, Volume
->OSIconName
);
715 // dummy FAT boot sector (created by OS X's newfs_msdos)
716 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
717 Volume
->HasBootCode
= FALSE
;
719 // dummy FAT boot sector (created by Linux's mkdosfs)
720 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
721 Volume
->HasBootCode
= FALSE
;
723 // dummy FAT boot sector (created by Windows)
724 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
725 Volume
->HasBootCode
= FALSE
;
727 // check for MBR partition table
728 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
729 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
730 for (i
= 0; i
< 4; i
++)
731 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
732 MbrTableFound
= TRUE
;
733 for (i
= 0; i
< 4; i
++)
734 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
735 MbrTableFound
= FALSE
;
737 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
738 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
744 CheckError(Status
, L
"while reading boot sector");
747 } /* VOID ScanVolumeBootcode() */
749 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
750 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
752 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_BADGES
)
755 if (Volume
->VolBadgeImage
== NULL
) {
756 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", GlobalConfig
.IconSizes
[ICON_SIZE_BADGE
]);
759 if (Volume
->VolBadgeImage
== NULL
) {
760 switch (Volume
->DiskKind
) {
761 case DISK_KIND_INTERNAL
:
762 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
764 case DISK_KIND_EXTERNAL
:
765 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
767 case DISK_KIND_OPTICAL
:
768 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
771 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
775 } // VOID SetVolumeBadgeIcon()
777 // Return a string representing the input size in IEEE-1541 units.
778 // The calling function is responsible for freeing the allocated memory.
779 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
781 UINTN Index
= 0, NumPrefixes
;
782 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
785 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
786 if (TheValue
!= NULL
) {
787 NumPrefixes
= StrLen(Prefixes
);
788 SizeInIeee
= SizeInBytes
;
789 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
793 if (Prefixes
[Index
] == ' ') {
794 Units
= StrDuplicate(L
"-byte");
796 Units
= StrDuplicate(L
" iB");
797 Units
[1] = Prefixes
[Index
];
799 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
802 } // CHAR16 *SizeInIEEEUnits()
804 // Return a name for the volume. Ideally this should be the label for the
805 // filesystem or volume, but this function falls back to describing the
806 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
807 // this information can be extracted.
808 // The calling function is responsible for freeing the memory allocated
809 // for the name string.
810 static CHAR16
*GetVolumeName(REFIT_VOLUME
*Volume
) {
811 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
= NULL
;
812 CHAR16
*FoundName
= NULL
;
813 CHAR16
*SISize
, *TypeName
;
815 if (Volume
->RootDir
!= NULL
) {
816 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
819 if ((FileSystemInfoPtr
!= NULL
) && (FileSystemInfoPtr
->VolumeLabel
!= NULL
) &&
820 (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
821 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
824 // If no filesystem name, try to use the partition name....
825 if ((FoundName
== NULL
) && (Volume
->PartName
!= NULL
) && (StrLen(Volume
->PartName
) > 0) &&
826 !IsIn(Volume
->PartName
, IGNORE_PARTITION_NAMES
)) {
827 FoundName
= StrDuplicate(Volume
->PartName
);
828 } // if use partition name
830 // No filesystem or acceptable partition name, so use fs type and size
831 if ((FoundName
== NULL
) && (FileSystemInfoPtr
!= NULL
)) {
832 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
833 if (FoundName
!= NULL
) {
834 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
835 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
837 } // if allocated memory OK
838 } // if (FoundName == NULL)
840 MyFreePool(FileSystemInfoPtr
);
842 if (FoundName
== NULL
) {
843 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
844 if (FoundName
!= NULL
) {
845 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
846 if (StrLen(TypeName
) > 0)
847 SPrint(FoundName
, 255, L
"%s volume", TypeName
);
849 SPrint(FoundName
, 255, L
"unknown volume");
850 } // if allocated memory OK
853 // TODO: Above could be improved/extended, in case filesystem name is not found,
855 // - use or add disk/partition number (e.g., "(hd0,2)")
857 // Desperate fallback name....
858 if (FoundName
== NULL
) {
859 FoundName
= StrDuplicate(L
"unknown volume");
862 } // static CHAR16 *GetVolumeName()
864 // Determine the unique GUID and name of the volume and store them.
865 static VOID
SetPartGuidAndName(REFIT_VOLUME
*Volume
, EFI_DEVICE_PATH_PROTOCOL
*DevicePath
) {
866 HARDDRIVE_DEVICE_PATH
*HdDevicePath
;
871 if ((DevicePath
->Type
== MEDIA_DEVICE_PATH
) && (DevicePath
->SubType
== MEDIA_HARDDRIVE_DP
)) {
872 HdDevicePath
= (HARDDRIVE_DEVICE_PATH
*) DevicePath
;
873 if (HdDevicePath
->SignatureType
== SIGNATURE_TYPE_GUID
) {
874 Volume
->PartGuid
= *((EFI_GUID
*) HdDevicePath
->Signature
);
875 Volume
->PartName
= PartNameFromGuid(&(Volume
->PartGuid
));
878 } // VOID SetPartGuid()
880 // Return TRUE if NTFS boot files are found or if Volume is unreadable,
881 // FALSE otherwise. The idea is to weed out non-boot NTFS volumes from
882 // BIOS/legacy boot list on Macs. We can't assume NTFS will be readable,
883 // so return TRUE if it's unreadable; but if it IS readable, return
884 // TRUE only if Windows boot files are found.
885 static BOOLEAN
HasWindowsBiosBootFiles(REFIT_VOLUME
*Volume
) {
886 BOOLEAN FilesFound
= TRUE
;
888 if (Volume
->RootDir
!= NULL
) {
889 FilesFound
= FileExists(Volume
->RootDir
, L
"NTLDR") || // Windows NT/200x/XP boot file
890 FileExists(Volume
->RootDir
, L
"bootmgr"); // Windows Vista/7/8 boot file
893 } // static VOID HasWindowsBiosBootFiles()
895 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
898 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
899 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
900 EFI_HANDLE WholeDiskHandle
;
905 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
907 if (Volume
->DevicePath
!= NULL
) {
908 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
910 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
915 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
918 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
919 if (EFI_ERROR(Status
)) {
920 Volume
->BlockIO
= NULL
;
921 Print(L
"Warning: Can't get BlockIO protocol.\n");
923 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
924 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
927 // scan for bootcode and MBR table
929 ScanVolumeBootcode(Volume
, &Bootable
);
931 // detect device type
932 DevicePath
= Volume
->DevicePath
;
933 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
934 NextDevicePath
= NextDevicePathNode(DevicePath
);
936 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
) {
937 SetPartGuidAndName(Volume
, DevicePath
);
939 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
940 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
941 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
942 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
943 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
944 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
945 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
946 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
947 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
951 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
952 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
953 // TODO: also check for Boot Camp GUID
954 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
957 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
958 // make a device path for the whole device
959 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
960 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
961 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
962 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
964 // get the handle for that path
965 RemainingDevicePath
= DiskDevicePath
;
966 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
967 FreePool(DiskDevicePath
);
969 if (!EFI_ERROR(Status
)) {
970 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
972 // get the device path for later
973 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
974 if (!EFI_ERROR(Status
)) {
975 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
978 // look at the BlockIO protocol
979 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
980 (VOID
**) &Volume
->WholeDiskBlockIO
);
981 if (!EFI_ERROR(Status
)) {
983 // check the media block size
984 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
985 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
988 Volume
->WholeDiskBlockIO
= NULL
;
989 //CheckError(Status, L"from HandleProtocol");
992 // CheckError(Status, L"from LocateDevicePath");
995 DevicePath
= NextDevicePath
;
1000 if (Volume
->HasBootCode
)
1001 Print(L
" Volume considered non-bootable, but boot code is present\n");
1003 Volume
->HasBootCode
= FALSE
;
1006 // open the root directory of the volume
1007 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1009 // Set volume icon based on .VolumeBadge icon or disk kind
1010 SetVolumeBadgeIcon(Volume
);
1012 Volume
->VolName
= GetVolumeName(Volume
);
1014 if (Volume
->RootDir
== NULL
) {
1015 Volume
->IsReadable
= FALSE
;
1018 Volume
->IsReadable
= TRUE
;
1019 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
) && (Volume
->FSType
== FS_TYPE_NTFS
) && Volume
->HasBootCode
) {
1020 // VBR boot code found on NTFS, but volume is not actually bootable
1021 // unless there are actual boot file, so check for them....
1022 Volume
->HasBootCode
= HasWindowsBiosBootFiles(Volume
);
1026 // get custom volume icons if present
1027 if (!Volume
->VolIconImage
) {
1028 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
1032 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
1035 REFIT_VOLUME
*Volume
;
1036 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
1038 UINTN LogicalPartitionIndex
= 4;
1039 UINT8 SectorBuffer
[512];
1041 MBR_PARTITION_INFO
*EMbrTable
;
1043 ExtBase
= MbrEntry
->StartLBA
;
1045 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
1046 // read current EMBR
1047 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
1048 WholeDiskVolume
->BlockIO
,
1049 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
1050 ExtCurrent
, 512, SectorBuffer
);
1051 if (EFI_ERROR(Status
))
1053 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
1055 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
1057 // scan logical partitions in this EMBR
1059 for (i
= 0; i
< 4; i
++) {
1060 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
1061 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
1063 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
1064 // set next ExtCurrent
1065 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
1069 // found a logical partition
1070 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1071 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
1072 Volume
->IsMbrPartition
= TRUE
;
1073 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
1074 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
1075 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
1076 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
1077 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
1078 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
1081 ScanVolumeBootcode(Volume
, &Bootable
);
1083 Volume
->HasBootCode
= FALSE
;
1085 SetVolumeBadgeIcon(Volume
);
1087 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1092 } /* VOID ScanExtendedPartition() */
1094 VOID
ScanVolumes(VOID
)
1097 EFI_HANDLE
*Handles
;
1098 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
1099 MBR_PARTITION_INFO
*MbrTable
;
1100 UINTN HandleCount
= 0;
1102 UINTN VolumeIndex
, VolumeIndex2
;
1103 UINTN PartitionIndex
;
1104 UINTN SectorSum
, i
, VolNumber
= 0;
1105 UINT8
*SectorBuffer1
, *SectorBuffer2
;
1107 EFI_GUID NullUuid
= NULL_GUID_VALUE
;
1109 MyFreePool(Volumes
);
1112 ForgetPartitionTables();
1114 // get all filesystem handles
1115 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
1116 UuidList
= AllocateZeroPool(sizeof(EFI_GUID
) * HandleCount
);
1117 if (Status
== EFI_NOT_FOUND
) {
1118 return; // no filesystems. strange, but true...
1120 if (CheckError(Status
, L
"while listing all file systems"))
1123 // first pass: collect information about all handles
1124 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1125 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1126 Volume
->DeviceHandle
= Handles
[HandleIndex
];
1127 AddPartitionTable(Volume
);
1130 UuidList
[HandleIndex
] = Volume
->VolUuid
;
1131 for (i
= 0; i
< HandleIndex
; i
++) {
1132 if ((CompareMem(&(Volume
->VolUuid
), &(UuidList
[i
]), sizeof(EFI_GUID
)) == 0) &&
1133 (CompareMem(&(Volume
->VolUuid
), &NullUuid
, sizeof(EFI_GUID
)) != 0)) { // Duplicate filesystem UUID
1134 Volume
->IsReadable
= FALSE
;
1138 if (Volume
->IsReadable
)
1139 Volume
->VolNumber
= VolNumber
++;
1141 Volume
->VolNumber
= VOL_UNREADABLE
;
1143 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1145 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
1146 SelfVolume
= Volume
;
1148 MyFreePool(Handles
);
1150 if (SelfVolume
== NULL
)
1151 Print(L
"WARNING: SelfVolume not found");
1153 // second pass: relate partitions and whole disk devices
1154 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1155 Volume
= Volumes
[VolumeIndex
];
1156 // check MBR partition table for extended partitions
1157 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1158 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
1159 Volume
->MbrPartitionTable
!= NULL
) {
1160 MbrTable
= Volume
->MbrPartitionTable
;
1161 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1162 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
1163 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
1168 // search for corresponding whole disk volume entry
1169 WholeDiskVolume
= NULL
;
1170 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1171 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1172 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1173 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1174 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0) {
1175 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1180 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1181 // check if this volume is one of the partitions in the table
1182 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1183 SectorBuffer1
= AllocatePool(512);
1184 SectorBuffer2
= AllocatePool(512);
1185 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1187 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1190 // compare boot sector read through offset vs. directly
1191 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1192 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1193 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1194 if (EFI_ERROR(Status
))
1196 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1197 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1198 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1199 if (EFI_ERROR(Status
))
1201 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1204 for (i
= 0; i
< 512; i
++)
1205 SectorSum
+= SectorBuffer1
[i
];
1206 if (SectorSum
< 1000)
1209 // TODO: mark entry as non-bootable if it is an extended partition
1211 // now we're reasonably sure the association is correct...
1212 Volume
->IsMbrPartition
= TRUE
;
1213 Volume
->MbrPartitionIndex
= PartitionIndex
;
1214 if (Volume
->VolName
== NULL
) {
1215 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1216 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1221 MyFreePool(SectorBuffer1
);
1222 MyFreePool(SectorBuffer2
);
1225 } /* VOID ScanVolumes() */
1227 static VOID
UninitVolumes(VOID
)
1229 REFIT_VOLUME
*Volume
;
1232 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1233 Volume
= Volumes
[VolumeIndex
];
1235 if (Volume
->RootDir
!= NULL
) {
1236 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
1237 Volume
->RootDir
= NULL
;
1240 Volume
->DeviceHandle
= NULL
;
1241 Volume
->BlockIO
= NULL
;
1242 Volume
->WholeDiskBlockIO
= NULL
;
1246 VOID
ReinitVolumes(VOID
)
1249 REFIT_VOLUME
*Volume
;
1251 EFI_DEVICE_PATH
*RemainingDevicePath
;
1252 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
1254 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1255 Volume
= Volumes
[VolumeIndex
];
1257 if (Volume
->DevicePath
!= NULL
) {
1258 // get the handle for that path
1259 RemainingDevicePath
= Volume
->DevicePath
;
1260 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
1262 if (!EFI_ERROR(Status
)) {
1263 Volume
->DeviceHandle
= DeviceHandle
;
1265 // get the root directory
1266 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1269 CheckError(Status
, L
"from LocateDevicePath");
1272 if (Volume
->WholeDiskDevicePath
!= NULL
) {
1273 // get the handle for that path
1274 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
1275 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
1277 if (!EFI_ERROR(Status
)) {
1278 // get the BlockIO protocol
1279 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
1280 (VOID
**) &Volume
->WholeDiskBlockIO
);
1281 if (EFI_ERROR(Status
)) {
1282 Volume
->WholeDiskBlockIO
= NULL
;
1283 CheckError(Status
, L
"from HandleProtocol");
1286 CheckError(Status
, L
"from LocateDevicePath");
1292 // file and dir functions
1295 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1298 EFI_FILE_HANDLE TestFile
;
1300 if (BaseDir
!= NULL
) {
1301 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1302 if (Status
== EFI_SUCCESS
) {
1303 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1310 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1314 UINTN LastBufferSize
, BufferSize
;
1319 // free pointer from last call
1320 if (*DirEntry
!= NULL
) {
1321 FreePool(*DirEntry
);
1325 // read next directory entry
1326 LastBufferSize
= BufferSize
= 256;
1327 Buffer
= AllocatePool(BufferSize
);
1328 for (IterCount
= 0; ; IterCount
++) {
1329 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1330 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1332 if (BufferSize
<= LastBufferSize
) {
1333 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1334 BufferSize
= LastBufferSize
* 2;
1337 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1340 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1341 LastBufferSize
= BufferSize
;
1343 if (EFI_ERROR(Status
)) {
1349 // check for end of listing
1350 if (BufferSize
== 0) { // end of directory listing
1356 // entry is ready to be returned
1357 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1360 if (FilterMode
== 1) { // only return directories
1361 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1363 } else if (FilterMode
== 2) { // only return files
1364 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1366 } else // no filter or unknown filter -> return everything
1373 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1375 if (RelativePath
== NULL
) {
1376 DirIter
->LastStatus
= EFI_SUCCESS
;
1377 DirIter
->DirHandle
= BaseDir
;
1378 DirIter
->CloseDirHandle
= FALSE
;
1380 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1381 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1383 DirIter
->LastFileInfo
= NULL
;
1386 #ifndef __MAKEWITH_GNUEFI
1387 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1390 InitializeUnicodeCollationProtocol (VOID
)
1394 if (mUnicodeCollation
!= NULL
) {
1399 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1400 // instances first and then select one which support English language.
1401 // Current implementation just pick the first instance.
1403 Status
= gBS
->LocateProtocol (
1404 &gEfiUnicodeCollation2ProtocolGuid
,
1406 (VOID
**) &mUnicodeCollation
1408 if (EFI_ERROR(Status
)) {
1409 Status
= gBS
->LocateProtocol (
1410 &gEfiUnicodeCollationProtocolGuid
,
1412 (VOID
**) &mUnicodeCollation
1420 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1422 if (!mUnicodeCollation
) {
1423 InitializeUnicodeCollationProtocol();
1425 if (mUnicodeCollation
)
1426 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1427 return FALSE
; // Shouldn't happen
1430 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1431 if (!mUnicodeCollation
) {
1432 InitializeUnicodeCollationProtocol();
1434 if (mUnicodeCollation
)
1435 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1440 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1441 OUT EFI_FILE_INFO
**DirEntry
)
1443 BOOLEAN KeepGoing
= TRUE
;
1447 if (DirIter
->LastFileInfo
!= NULL
) {
1448 FreePool(DirIter
->LastFileInfo
);
1449 DirIter
->LastFileInfo
= NULL
;
1452 if (EFI_ERROR(DirIter
->LastStatus
))
1453 return FALSE
; // stop iteration
1456 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1457 if (EFI_ERROR(DirIter
->LastStatus
))
1459 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1461 if (FilePattern
!= NULL
) {
1462 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1465 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1466 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1469 // else continue loop
1472 } while (KeepGoing
&& FilePattern
);
1474 *DirEntry
= DirIter
->LastFileInfo
;
1478 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1480 if (DirIter
->LastFileInfo
!= NULL
) {
1481 FreePool(DirIter
->LastFileInfo
);
1482 DirIter
->LastFileInfo
= NULL
;
1484 if (DirIter
->CloseDirHandle
)
1485 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1486 return DirIter
->LastStatus
;
1490 // file name manipulation
1493 // Returns the filename portion (minus path name) of the
1495 CHAR16
* Basename(IN CHAR16
*Path
)
1503 for (i
= StrLen(Path
); i
> 0; i
--) {
1504 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1505 FileName
= Path
+ i
;
1514 // Remove the .efi extension from FileName -- for instance, if FileName is
1515 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1516 // returns a copy of the original input.
1517 CHAR16
* StripEfiExtension(CHAR16
*FileName
) {
1519 CHAR16
*Copy
= NULL
;
1521 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1522 Length
= StrLen(Copy
);
1523 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1524 if ((Length
>= 4) && ((StriCmp(&Copy
[Length
- 4], L
".efi") == 0) || (StriCmp(&Copy
[Length
- 4], L
".EFI") == 0))) {
1525 Copy
[Length
- 4] = 0;
1529 } // CHAR16 * StripExtension()
1532 // memory string search
1535 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1541 BufferLength
-= SearchStringLength
;
1542 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1543 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1544 return (INTN
)Offset
;
1550 // Performs a case-insensitive search of BigStr for SmallStr.
1551 // Returns TRUE if found, FALSE if not.
1552 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1553 CHAR16
*SmallCopy
, *BigCopy
;
1554 BOOLEAN Found
= FALSE
;
1555 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1557 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1558 SmallCopy
= StrDuplicate(SmallStr
);
1559 BigCopy
= StrDuplicate(BigStr
);
1562 SmallLen
= StrLen(SmallCopy
);
1563 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1564 while ((!Found
) && (StartPoint
< NumCompares
)) {
1565 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1567 MyFreePool(SmallCopy
);
1568 MyFreePool(BigCopy
);
1572 } // BOOLEAN StriSubCmp()
1574 // Merges two strings, creating a new one and returning a pointer to it.
1575 // If AddChar != 0, the specified character is placed between the two original
1576 // strings (unless the first string is NULL or empty). The original input
1577 // string *First is de-allocated and replaced by the new merged string.
1578 // This is similar to StrCat, but safer and more flexible because
1579 // MergeStrings allocates memory that's the correct size for the
1580 // new merged string, so it can take a NULL *First and it cleans
1581 // up the old memory. It should *NOT* be used with a constant
1582 // *First, though....
1583 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1584 UINTN Length1
= 0, Length2
= 0;
1588 Length1
= StrLen(*First
);
1590 Length2
= StrLen(Second
);
1591 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1592 if (NewString
!= NULL
) {
1593 if ((*First
!= NULL
) && (StrLen(*First
) == 0)) {
1597 NewString
[0] = L
'\0';
1598 if (*First
!= NULL
) {
1599 StrCat(NewString
, *First
);
1601 NewString
[Length1
] = AddChar
;
1602 NewString
[Length1
+ 1] = '\0';
1604 } // if (*First != NULL)
1606 StrCat(NewString
, Second
);
1610 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1612 } // static CHAR16* MergeStrings()
1614 // Takes an input pathname (*Path) and returns the part of the filename from
1615 // the final dot onwards, converted to lowercase. If the filename includes
1616 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1617 // The calling function is responsible for freeing the memory associated with
1618 // the return value.
1619 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1621 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1624 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1627 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1628 if (Path
[i
] == L
'.')
1630 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1636 MergeStrings(&Extension
, &Path
[i
], 0);
1641 } // CHAR16 *FindExtension
1643 // Takes an input pathname (*Path) and locates the final directory component
1644 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1645 // function returns the string 'foo'.
1646 // Assumes the pathname is separated with backslashes.
1647 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1648 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1649 CHAR16
*Found
= NULL
;
1654 PathLength
= StrLen(Path
);
1655 // Find start & end of target element
1656 for (i
= 0; i
< PathLength
; i
++) {
1657 if (Path
[i
] == '\\') {
1658 StartOfElement
= EndOfElement
;
1662 // Extract the target element
1663 if (EndOfElement
> 0) {
1664 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1668 if (EndOfElement
>= StartOfElement
) {
1669 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1670 Found
= StrDuplicate(&Path
[StartOfElement
]);
1672 Found
[CopyLength
] = 0;
1673 } // if (EndOfElement >= StartOfElement)
1674 } // if (EndOfElement > 0)
1676 } // CHAR16 *FindLastDirName
1678 // Returns the directory portion of a pathname. For instance,
1679 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1680 // string 'EFI\foo'. The calling function is responsible for
1681 // freeing the returned string's memory.
1682 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1683 UINTN i
, LastBackslash
= 0;
1684 CHAR16
*PathOnly
= NULL
;
1686 if (FullPath
!= NULL
) {
1687 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1688 if (FullPath
[i
] == '\\')
1691 PathOnly
= StrDuplicate(FullPath
);
1692 if (PathOnly
!= NULL
)
1693 PathOnly
[LastBackslash
] = 0;
1700 * Routine Description:
1706 * String - Null-terminated string to search.
1707 * StrCharSet - Null-terminated string to search for.
1710 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1712 CHAR16
* MyStrStr (CHAR16
*String
, CHAR16
*StrCharSet
)
1717 if ((String
== NULL
) || (StrCharSet
== NULL
))
1723 while ((*String
!= L
'\0') && (*StrCharSet
!= L
'\0')) {
1724 if (*String
++ != *StrCharSet
) {
1731 if (*StrCharSet
== L
'\0') {
1736 } // CHAR16 *MyStrStr()
1738 // Restrict TheString to at most Limit characters.
1739 // Does this in two ways:
1740 // - Locates stretches of two or more spaces and compresses
1741 // them down to one space.
1742 // - Truncates TheString
1743 // Returns TRUE if changes were made, FALSE otherwise
1744 BOOLEAN
LimitStringLength(CHAR16
*TheString
, UINTN Limit
) {
1745 CHAR16
*SubString
, *TempString
;
1747 BOOLEAN HasChanged
= FALSE
;
1749 // SubString will be NULL or point WITHIN TheString
1750 SubString
= MyStrStr(TheString
, L
" ");
1751 while (SubString
!= NULL
) {
1753 while (SubString
[i
] == L
' ')
1755 if (i
>= StrLen(SubString
)) {
1756 SubString
[0] = '\0';
1759 TempString
= StrDuplicate(&SubString
[i
]);
1760 if (TempString
!= NULL
) {
1761 StrCpy(&SubString
[1], TempString
);
1762 MyFreePool(TempString
);
1765 // memory allocation problem; abort to avoid potentially infinite loop!
1769 SubString
= MyStrStr(TheString
, L
" ");
1772 // If the string is still too long, truncate it....
1773 if (StrLen(TheString
) > Limit
) {
1774 TheString
[Limit
] = '\0';
1779 } // BOOLEAN LimitStringLength()
1781 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1782 // DeviceVolume, and returns that and the filename (*loader).
1783 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1784 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1786 BOOLEAN Found
= FALSE
;
1788 MyFreePool(*loader
);
1789 MyFreePool(*DeviceVolume
);
1790 *DeviceVolume
= NULL
;
1791 DeviceString
= DevicePathToStr(loadpath
);
1792 *loader
= SplitDeviceString(DeviceString
);
1794 while ((i
< VolumesCount
) && (!Found
)) {
1795 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1796 Temp
= SplitDeviceString(VolumeDeviceString
);
1797 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1799 *DeviceVolume
= Volumes
[i
];
1802 MyFreePool(VolumeDeviceString
);
1806 MyFreePool(DeviceString
);
1807 } // VOID FindVolumeAndFilename()
1809 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1810 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1811 // the filename component in the original *Path variable and the split-off
1812 // volume component in the *VolName variable.
1813 // Returns TRUE if both components are found, FALSE otherwise.
1814 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1815 UINTN i
= 0, Length
;
1821 if (*VolName
!= NULL
) {
1822 MyFreePool(*VolName
);
1826 Length
= StrLen(*Path
);
1827 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1832 Filename
= StrDuplicate((*Path
) + i
+ 1);
1840 } // BOOLEAN SplitVolumeAndFilename()
1842 // Returns all the digits in the input string, including intervening
1843 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1844 // this function returns "3.3.4-7". If InString contains no digits,
1845 // the return value is NULL.
1846 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1847 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1848 CHAR16
*Found
= NULL
;
1850 if (InString
== NULL
)
1853 InLength
= StartOfElement
= StrLen(InString
);
1854 // Find start & end of target element
1855 for (i
= 0; i
< InLength
; i
++) {
1856 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1857 if (StartOfElement
> i
)
1859 if (EndOfElement
< i
)
1863 // Extract the target element
1864 if (EndOfElement
> 0) {
1865 if (EndOfElement
>= StartOfElement
) {
1866 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1867 Found
= StrDuplicate(&InString
[StartOfElement
]);
1869 Found
[CopyLength
] = 0;
1870 } // if (EndOfElement >= StartOfElement)
1871 } // if (EndOfElement > 0)
1873 } // CHAR16 *FindNumbers()
1875 // Find the #Index element (numbered from 0) in a comma-delimited string
1877 // Returns the found element, or NULL if Index is out of range or InString
1878 // is NULL. Note that the calling function is responsible for freeing the
1879 // memory associated with the returned string pointer.
1880 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1881 UINTN StartPos
= 0, CurPos
= 0;
1882 BOOLEAN Found
= FALSE
;
1883 CHAR16
*FoundString
= NULL
;
1885 if (InString
!= NULL
) {
1886 // After while() loop, StartPos marks start of item #Index
1887 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1888 if (InString
[CurPos
] == L
',') {
1890 StartPos
= CurPos
+ 1;
1894 // After while() loop, CurPos is one past the end of the element
1895 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1896 if (InString
[CurPos
] == L
',')
1902 FoundString
= StrDuplicate(&InString
[StartPos
]);
1903 if (FoundString
!= NULL
)
1904 FoundString
[CurPos
- StartPos
] = 0;
1906 return (FoundString
);
1907 } // CHAR16 *FindCommaDelimited()
1909 // Return the position of SmallString within BigString, or -1 if
1911 INTN
FindSubString(IN CHAR16
*SmallString
, IN CHAR16
*BigString
) {
1913 UINTN i
= 0, SmallSize
, BigSize
;
1914 BOOLEAN Found
= FALSE
;
1916 if ((SmallString
== NULL
) || (BigString
== NULL
))
1919 SmallSize
= StrLen(SmallString
);
1920 BigSize
= StrLen(BigString
);
1921 if ((SmallSize
> BigSize
) || (SmallSize
== 0) || (BigSize
== 0))
1924 while ((i
<= (BigSize
- SmallSize
) && !Found
)) {
1925 if (CompareMem(BigString
+ i
, SmallString
, SmallSize
) == 0) {
1932 } // INTN FindSubString()
1934 // Take an input path name, which may include a volume specification and/or
1935 // a path, and return separate volume, path, and file names. For instance,
1936 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1937 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1938 // the returned pointer is NULL. The calling function is responsible for
1939 // freeing the allocated memory.
1940 VOID
SplitPathName(CHAR16
*InPath
, CHAR16
**VolName
, CHAR16
**Path
, CHAR16
**Filename
) {
1941 CHAR16
*Temp
= NULL
;
1943 MyFreePool(*VolName
);
1945 MyFreePool(*Filename
);
1946 *VolName
= *Path
= *Filename
= NULL
;
1947 Temp
= StrDuplicate(InPath
);
1948 SplitVolumeAndFilename(&Temp
, VolName
); // VolName is NULL or has volume; Temp has rest of path
1949 CleanUpPathNameSlashes(Temp
);
1950 *Path
= FindPath(Temp
); // *Path has path (may be 0-length); Temp unchanged.
1951 *Filename
= StrDuplicate(Temp
+ StrLen(*Path
));
1952 CleanUpPathNameSlashes(*Filename
);
1953 if (StrLen(*Path
) == 0) {
1957 if (StrLen(*Filename
) == 0) {
1958 MyFreePool(*Filename
);
1962 } // VOID SplitPathName
1964 // Returns TRUE if SmallString is an element in the comma-delimited List,
1965 // FALSE otherwise. Performs comparison case-insensitively (except on
1966 // buggy EFIs with case-sensitive StriCmp() functions).
1967 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1969 BOOLEAN Found
= FALSE
;
1972 if (SmallString
&& List
) {
1973 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1974 if (StriCmp(OneElement
, SmallString
) == 0)
1981 // Returns TRUE if any element of List can be found as a substring of
1982 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1983 BOOLEAN
IsInSubstring(IN CHAR16
*BigString
, IN CHAR16
*List
) {
1984 UINTN i
= 0, ElementLength
;
1985 BOOLEAN Found
= FALSE
;
1988 if (BigString
&& List
) {
1989 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1990 ElementLength
= StrLen(OneElement
);
1991 if ((ElementLength
<= StrLen(BigString
)) && (StriSubCmp(OneElement
, BigString
)))
1996 } // BOOLEAN IsSubstringIn()
1998 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1999 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
2000 // Filename must *NOT* include a volume or path specification (that's part of
2001 // the Volume variable), but the List elements may. Performs comparison
2002 // case-insensitively (except on buggy EFIs with case-sensitive StriCmp()
2004 BOOLEAN
FilenameIn(REFIT_VOLUME
*Volume
, CHAR16
*Directory
, CHAR16
*Filename
, CHAR16
*List
) {
2006 BOOLEAN Found
= FALSE
;
2008 CHAR16
*TargetVolName
= NULL
, *TargetPath
= NULL
, *TargetFilename
= NULL
;
2010 if (Filename
&& List
) {
2011 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
2013 SplitPathName(OneElement
, &TargetVolName
, &TargetPath
, &TargetFilename
);
2014 VolumeNumberToName(Volume
, &TargetVolName
);
2015 if (((TargetVolName
!= NULL
) && ((Volume
== NULL
) || (StriCmp(TargetVolName
, Volume
->VolName
) != 0))) ||
2016 ((TargetPath
!= NULL
) && (StriCmp(TargetPath
, Directory
) != 0)) ||
2017 ((TargetFilename
!= NULL
) && (StriCmp(TargetFilename
, Filename
) != 0))) {
2020 MyFreePool(OneElement
);
2024 MyFreePool(TargetVolName
);
2025 MyFreePool(TargetPath
);
2026 MyFreePool(TargetFilename
);
2028 } // BOOLEAN FilenameIn()
2030 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
2031 // to this volume number, returns with *VolName changed to the volume name, as
2032 // stored in the Volume data structure.
2033 // Returns TRUE if this substitution was made, FALSE otherwise.
2034 BOOLEAN
VolumeNumberToName(REFIT_VOLUME
*Volume
, CHAR16
**VolName
) {
2035 BOOLEAN MadeSubstitution
= FALSE
;
2038 if ((VolName
== NULL
) || (*VolName
== NULL
))
2041 if ((StrLen(*VolName
) > 2) && (*VolName
[0] == L
'f') && (*VolName
[1] == L
's') && (*VolName
[2] >= L
'0') && (*VolName
[2] <= L
'9')) {
2042 VolNum
= Atoi(*VolName
+ 2);
2043 if (VolNum
== Volume
->VolNumber
) {
2044 MyFreePool(*VolName
);
2045 *VolName
= StrDuplicate(Volume
->VolName
);
2046 MadeSubstitution
= TRUE
;
2049 return MadeSubstitution
;
2050 } // BOOLEAN VolumeMatchesNumber()
2052 // Implement FreePool the way it should have been done to begin with, so that
2053 // it doesn't throw an ASSERT message if fed a NULL pointer....
2054 VOID
MyFreePool(IN VOID
*Pointer
) {
2055 if (Pointer
!= NULL
)
2059 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
2061 // Eject all removable media.
2062 // Returns TRUE if any media were ejected, FALSE otherwise.
2063 BOOLEAN
EjectMedia(VOID
) {
2065 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
2066 EFI_HANDLE
*Handles
, Handle
;
2067 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
2069 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
2070 if (EFI_ERROR(Status
) || HandleCount
== 0)
2071 return (FALSE
); // probably not an Apple system
2073 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
2074 Handle
= Handles
[HandleIndex
];
2075 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
2076 if (EFI_ERROR(Status
))
2078 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
2079 if (!EFI_ERROR(Status
))
2082 MyFreePool(Handles
);
2083 return (Ejected
> 0);
2084 } // VOID EjectMedia()
2086 // Converts consecutive characters in the input string into a
2087 // number, interpreting the string as a hexadecimal number, starting
2088 // at the specified position and continuing for the specified number
2089 // of characters or until the end of the string, whichever is first.
2090 // NumChars must be between 1 and 16. Ignores invalid characters.
2091 UINT64
StrToHex(CHAR16
*Input
, UINTN Pos
, UINTN NumChars
) {
2092 UINT64 retval
= 0x00;
2096 if ((Input
== NULL
) || (StrLen(Input
) < Pos
) || (NumChars
== 0) || (NumChars
> 16)) {
2100 while ((StrLen(Input
) >= Pos
) && (NumDone
< NumChars
)) {
2102 if ((a
>= '0') && (a
<= '9')) {
2104 retval
+= (a
- '0');
2107 if ((a
>= 'a') && (a
<= 'f')) {
2109 retval
+= (a
- 'a' + 0x0a);
2112 if ((a
>= 'A') && (a
<= 'F')) {
2114 retval
+= (a
- 'A' + 0x0a);
2122 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2123 // Note that the input string must have no extraneous spaces and must be
2124 // conventionally formatted as a 36-character GUID, complete with dashes in
2125 // appropriate places.
2126 BOOLEAN
IsGuid(CHAR16
*UnknownString
) {
2128 BOOLEAN retval
= TRUE
;
2131 if (UnknownString
== NULL
)
2134 Length
= StrLen(UnknownString
);
2138 for (i
= 0; i
< Length
; i
++) {
2139 a
= UnknownString
[i
];
2140 if ((i
== 8) || (i
== 13) || (i
== 18) || (i
== 23)) {
2143 } else if (((a
< 'a') || (a
> 'f')) && ((a
< 'A') || (a
> 'F')) && ((a
< '0') && (a
> '9'))) {
2148 } // BOOLEAN IsGuid()
2150 // Return the GUID as a string, suitable for display to the user. Note that the calling
2151 // function is responsible for freeing the allocated memory.
2152 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
2155 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
2156 if (TheString
!= 0) {
2157 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2158 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
2159 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
2160 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
2161 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
2164 } // GuidAsString(EFI_GUID *GuidData)
2166 EFI_GUID
StringAsGuid(CHAR16
* InString
) {
2167 EFI_GUID Guid
= NULL_GUID_VALUE
;
2169 if (!IsGuid(InString
)) {
2173 Guid
.Data1
= (UINT32
) StrToHex(InString
, 0, 8);
2174 Guid
.Data2
= (UINT16
) StrToHex(InString
, 9, 4);
2175 Guid
.Data3
= (UINT16
) StrToHex(InString
, 14, 4);
2176 Guid
.Data4
[0] = (UINT8
) StrToHex(InString
, 19, 2);
2177 Guid
.Data4
[1] = (UINT8
) StrToHex(InString
, 21, 2);
2178 Guid
.Data4
[2] = (UINT8
) StrToHex(InString
, 23, 2);
2179 Guid
.Data4
[3] = (UINT8
) StrToHex(InString
, 26, 2);
2180 Guid
.Data4
[4] = (UINT8
) StrToHex(InString
, 28, 2);
2181 Guid
.Data4
[5] = (UINT8
) StrToHex(InString
, 30, 2);
2182 Guid
.Data4
[6] = (UINT8
) StrToHex(InString
, 32, 2);
2183 Guid
.Data4
[7] = (UINT8
) StrToHex(InString
, 34, 2);
2186 } // EFI_GUID StringAsGuid()
2188 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2189 BOOLEAN
GuidsAreEqual(EFI_GUID
*Guid1
, EFI_GUID
*Guid2
) {
2190 return (CompareMem(Guid1
, Guid2
, 16) == 0);
2191 } // BOOLEAN CompareGuids()