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), or (at your option) any later version.
44 * This program is free software: you can redistribute it and/or modify
45 * it under the terms of the GNU General Public License as published by
46 * the Free Software Foundation, either version 3 of the License, or
47 * (at your option) any later version.
49 * This program is distributed in the hope that it will be useful,
50 * but WITHOUT ANY WARRANTY; without even the implied warranty of
51 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52 * GNU General Public License for more details.
54 * You should have received a copy of the GNU General Public License
55 * along with this program. If not, see <http://www.gnu.org/licenses/>.
62 #include "../include/refit_call_wrapper.h"
63 #include "../include/RemovableMedia.h"
67 #ifdef __MAKEWITH_GNUEFI
68 #define EfiReallocatePool ReallocatePool
70 #define LibLocateHandle gBS->LocateHandleBuffer
71 #define DevicePathProtocol gEfiDevicePathProtocolGuid
72 #define BlockIoProtocol gEfiBlockIoProtocolGuid
73 #define LibFileSystemInfo EfiLibFileSystemInfo
74 #define LibOpenRoot EfiLibOpenRoot
75 EFI_DEVICE_PATH EndDevicePath
[] = {
76 {END_DEVICE_PATH_TYPE
, END_ENTIRE_DEVICE_PATH_SUBTYPE
, {END_DEVICE_PATH_LENGTH
, 0}}
80 // "Magic" signatures for various filesystems
81 #define FAT_MAGIC 0xAA55
82 #define EXT2_SUPER_MAGIC 0xEF53
83 #define HFSPLUS_MAGIC1 0x2B48
84 #define HFSPLUS_MAGIC2 0x5848
85 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
86 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
87 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
88 #define BTRFS_SIGNATURE "_BHRfS_M"
89 #define XFS_SIGNATURE "XFSB"
90 #define NTFS_SIGNATURE "NTFS "
94 EFI_HANDLE SelfImageHandle
;
95 EFI_LOADED_IMAGE
*SelfLoadedImage
;
96 EFI_FILE
*SelfRootDir
;
100 REFIT_VOLUME
*SelfVolume
= NULL
;
101 REFIT_VOLUME
**Volumes
= NULL
;
102 UINTN VolumesCount
= 0;
103 extern GPT_DATA
*gPartitions
;
105 // Maximum size for disk sectors
106 #define SECTOR_SIZE 4096
108 // Number of bytes to read from a partition to determine its filesystem type
109 // and identify its boot loader, and hence probable BIOS-mode OS installation
110 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
113 // Pathname manipulations
116 // Converts forward slashes to backslashes, removes duplicate slashes, and
117 // removes slashes from both the start and end of the pathname.
118 // Necessary because some (buggy?) EFI implementations produce "\/" strings
119 // in pathnames, because some user inputs can produce duplicate directory
120 // separators, and because we want consistent start and end slashes for
121 // directory comparisons. A special case: If the PathName refers to root,
122 // return "/", since some firmware implementations flake out if this
124 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
126 UINTN i
, Length
, FinalChar
= 0;
127 BOOLEAN LastWasSlash
= FALSE
;
129 Length
= StrLen(PathName
);
130 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (Length
+ 2));
131 if (NewName
!= NULL
) {
132 for (i
= 0; i
< Length
; i
++) {
133 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
134 if ((!LastWasSlash
) && (FinalChar
!= 0))
135 NewName
[FinalChar
++] = L
'\\';
138 NewName
[FinalChar
++] = PathName
[i
];
139 LastWasSlash
= FALSE
;
142 NewName
[FinalChar
] = 0;
143 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
144 NewName
[--FinalChar
] = 0;
145 if (FinalChar
== 0) {
149 // Copy the transformed name back....
150 StrCpy(PathName
, NewName
);
152 } // if allocation OK
153 } // CleanUpPathNameSlashes()
155 // Splits an EFI device path into device and filename components. For instance, if InString is
156 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
157 // this function will truncate that input to
158 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
159 // and return bzImage-3.5.1.efi as its return value.
160 // It does this by searching for the last ")" character in InString, copying everything
161 // after that string (after some cleanup) as the return value, and truncating the original
163 // If InString contains no ")" character, this function leaves the original input string
164 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
165 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
167 CHAR16
*FileName
= NULL
;
168 BOOLEAN Found
= FALSE
;
170 if (InString
!= NULL
) {
171 i
= StrLen(InString
) - 1;
172 while ((i
>= 0) && (!Found
)) {
173 if (InString
[i
] == L
')') {
175 FileName
= StrDuplicate(&InString
[i
+ 1]);
176 CleanUpPathNameSlashes(FileName
);
177 InString
[i
+ 1] = '\0';
181 if (FileName
== NULL
)
182 FileName
= StrDuplicate(InString
);
185 } // static CHAR16* SplitDeviceString()
188 // Library initialization and de-initialization
191 static EFI_STATUS
FinishInitRefitLib(VOID
)
195 if (SelfRootDir
== NULL
) {
196 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
197 if (SelfRootDir
== NULL
) {
198 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
199 return EFI_LOAD_ERROR
;
203 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
204 if (CheckFatalError(Status
, L
"while opening our installation directory"))
205 return EFI_LOAD_ERROR
;
210 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
213 CHAR16
*DevicePathAsString
, *Temp
;
215 SelfImageHandle
= ImageHandle
;
216 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
217 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
218 return EFI_LOAD_ERROR
;
220 // find the current directory
221 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
222 GlobalConfig
.SelfDevicePath
= FileDevicePath(SelfLoadedImage
->DeviceHandle
, DevicePathAsString
);
223 CleanUpPathNameSlashes(DevicePathAsString
);
224 MyFreePool(SelfDirPath
);
225 Temp
= FindPath(DevicePathAsString
);
226 SelfDirPath
= SplitDeviceString(Temp
);
227 MyFreePool(DevicePathAsString
);
230 return FinishInitRefitLib();
233 static VOID
UninitVolumes(VOID
)
235 REFIT_VOLUME
*Volume
;
238 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
239 Volume
= Volumes
[VolumeIndex
];
241 if (Volume
->RootDir
!= NULL
) {
242 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
243 Volume
->RootDir
= NULL
;
246 Volume
->DeviceHandle
= NULL
;
247 Volume
->BlockIO
= NULL
;
248 Volume
->WholeDiskBlockIO
= NULL
;
250 } /* VOID UninitVolumes() */
252 VOID
ReinitVolumes(VOID
)
255 REFIT_VOLUME
*Volume
;
257 EFI_DEVICE_PATH
*RemainingDevicePath
;
258 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
260 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
261 Volume
= Volumes
[VolumeIndex
];
263 if (Volume
->DevicePath
!= NULL
) {
264 // get the handle for that path
265 RemainingDevicePath
= Volume
->DevicePath
;
266 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
268 if (!EFI_ERROR(Status
)) {
269 Volume
->DeviceHandle
= DeviceHandle
;
271 // get the root directory
272 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
275 CheckError(Status
, L
"from LocateDevicePath");
278 if (Volume
->WholeDiskDevicePath
!= NULL
) {
279 // get the handle for that path
280 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
281 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
283 if (!EFI_ERROR(Status
)) {
284 // get the BlockIO protocol
285 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
286 (VOID
**) &Volume
->WholeDiskBlockIO
);
287 if (EFI_ERROR(Status
)) {
288 Volume
->WholeDiskBlockIO
= NULL
;
289 CheckError(Status
, L
"from HandleProtocol");
292 CheckError(Status
, L
"from LocateDevicePath");
295 } /* VOID ReinitVolumes(VOID) */
297 // called before running external programs to close open file handles
298 VOID
UninitRefitLib(VOID
)
300 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
301 // See the comment on it there.
302 if(SelfRootDir
== SelfVolume
->RootDir
)
307 if (SelfDir
!= NULL
) {
308 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
312 if (SelfRootDir
!= NULL
) {
313 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
316 } /* VOID UninitRefitLib() */
318 // called after running external programs to re-open file handles
319 EFI_STATUS
ReinitRefitLib(VOID
)
323 if ((ST
->Hdr
.Revision
>> 16) == 1) {
324 // Below two lines were in rEFIt, but seem to cause system crashes or
325 // reboots when launching OSes after returning from programs on most
326 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
327 // installation volume" (see the next function) when returning from
328 // programs when these two lines are removed, and it often crashes
329 // when returning from a program or when launching a second program
330 // with these lines removed. Therefore, the preceding if() statement
331 // executes these lines only on EFIs with a major version number of 1
332 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
333 // of hardware on which to test is limited, though, so this may be the
334 // wrong test, or there may be a better way to fix this problem.
335 // TODO: Figure out cause of above weirdness and fix it more
337 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
338 SelfRootDir
= SelfVolume
->RootDir
;
341 return FinishInitRefitLib();
345 // EFI variable read and write functions
348 // From gummiboot: Retrieve a raw EFI variable.
349 // Returns EFI status
350 EFI_STATUS
EfivarGetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
**buffer
, UINTN
*size
) {
355 l
= sizeof(CHAR16
*) * EFI_MAXIMUM_VARIABLE_SIZE
;
356 buf
= AllocatePool(l
);
358 return EFI_OUT_OF_RESOURCES
;
360 err
= refit_call5_wrapper(RT
->GetVariable
, name
, vendor
, NULL
, &l
, buf
);
361 if (EFI_ERROR(err
) == EFI_SUCCESS
) {
368 } // EFI_STATUS EfivarGetRaw()
370 // From gummiboot: Set an EFI variable
371 EFI_STATUS
EfivarSetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
*buf
, UINTN size
, BOOLEAN persistent
) {
374 flags
= EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
376 flags
|= EFI_VARIABLE_NON_VOLATILE
;
378 return refit_call5_wrapper(RT
->SetVariable
, name
, vendor
, flags
, size
, buf
);
379 } // EFI_STATUS EfivarSetRaw()
385 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
389 if ((*ElementCount
& 15) == 0) {
390 AllocateCount
= *ElementCount
+ 16;
391 if (*ElementCount
== 0)
392 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
394 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
396 (*ListPtr
)[*ElementCount
] = NewElement
;
398 } /* VOID AddListElement() */
400 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
404 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
405 for (i
= 0; i
< *ElementCount
; i
++) {
406 // TODO: call a user-provided routine for each element here
407 MyFreePool((*ListPtr
)[i
]);
409 MyFreePool(*ListPtr
);
417 // Return a pointer to a string containing a filesystem type name. If the
418 // filesystem type is unknown, a blank (but non-null) string is returned.
419 // The returned variable is a constant that should NOT be freed.
420 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
421 CHAR16
*retval
= NULL
;
424 case FS_TYPE_WHOLEDISK
:
425 retval
= L
" whole disk";
430 case FS_TYPE_HFSPLUS
:
442 case FS_TYPE_REISERFS
:
443 retval
= L
" ReiserFS";
451 case FS_TYPE_ISO9660
:
452 retval
= L
" ISO-9660";
462 } // CHAR16 *FSTypeName()
464 // Identify the filesystem type and record the filesystem's UUID/serial number,
465 // if possible. Expects a Buffer containing the first few (normally at least
466 // 4096) bytes of the filesystem. Sets the filesystem type code in Volume->FSType
467 // and the UUID/serial number in Volume->VolUuid. Note that the UUID value is
468 // recognized differently for each filesystem, and is currently supported only
469 // for NTFS, ext2/3/4fs, and ReiserFS (and for NTFS it's really a 64-bit serial
470 // number not a UUID or GUID). If the UUID can't be determined, it's set to 0.
471 // Also, the UUID is just read directly into memory; it is *NOT* valid when
472 // displayed by GuidAsString() or used in other GUID/UUID-manipulating
473 // functions. (As I write, it's being used merely to detect partitions that are
474 // part of a RAID 1 array.)
475 static VOID
SetFilesystemData(IN UINT8
*Buffer
, IN UINTN BufferSize
, IN OUT REFIT_VOLUME
*Volume
) {
476 UINT32
*Ext2Incompat
, *Ext2Compat
;
481 if ((Buffer
!= NULL
) && (Volume
!= NULL
)) {
482 SetMem(&(Volume
->VolUuid
), sizeof(EFI_GUID
), 0);
483 Volume
->FSType
= FS_TYPE_UNKNOWN
;
485 if (BufferSize
>= (1024 + 100)) {
486 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
487 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
488 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
489 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
490 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
491 Volume
->FSType
= FS_TYPE_EXT4
;
492 } else if (*Ext2Compat
& 0x0004) { // check for journal
493 Volume
->FSType
= FS_TYPE_EXT3
;
494 } else { // none of these features; presume it's ext2...
495 Volume
->FSType
= FS_TYPE_EXT2
;
497 CopyMem(&(Volume
->VolUuid
), Buffer
+ 1024 + 104, sizeof(EFI_GUID
));
500 } // search for ext2/3/4 magic
502 if (BufferSize
>= (65536 + 100)) {
503 MagicString
= (char*) (Buffer
+ 65536 + 52);
504 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
505 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
506 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
507 Volume
->FSType
= FS_TYPE_REISERFS
;
508 CopyMem(&(Volume
->VolUuid
), Buffer
+ 65536 + 84, sizeof(EFI_GUID
));
511 } // search for ReiserFS magic
513 if (BufferSize
>= (65536 + 64 + 8)) {
514 MagicString
= (char*) (Buffer
+ 65536 + 64);
515 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0) {
516 Volume
->FSType
= FS_TYPE_BTRFS
;
519 } // search for Btrfs magic
521 if (BufferSize
>= 512) {
522 MagicString
= (char*) Buffer
;
523 if (CompareMem(MagicString
, XFS_SIGNATURE
, 4) == 0) {
524 Volume
->FSType
= FS_TYPE_XFS
;
527 } // search for XFS magic
529 if (BufferSize
>= (1024 + 2)) {
530 Magic16
= (UINT16
*) (Buffer
+ 1024);
531 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
532 Volume
->FSType
= FS_TYPE_HFSPLUS
;
535 } // search for HFS+ magic
537 if (BufferSize
>= 512) {
538 // Search for NTFS, FAT, and MBR/EBR.
539 // These all have 0xAA55 at the end of the first sector, but FAT and
540 // MBR/EBR are not easily distinguished. Thus, we first look for NTFS
541 // "magic"; then check to see if the volume can be mounted, thus
542 // relying on the EFI's built-in FAT driver to identify FAT; and then
543 // check to see if the "volume" is in fact a whole-disk device.
544 Magic16
= (UINT16
*) (Buffer
+ 510);
545 if (*Magic16
== FAT_MAGIC
) {
546 MagicString
= (char*) (Buffer
+ 3);
547 if (CompareMem(MagicString
, NTFS_SIGNATURE
, 8) == 0) {
548 Volume
->FSType
= FS_TYPE_NTFS
;
549 CopyMem(&(Volume
->VolUuid
), Buffer
+ 0x48, sizeof(UINT64
));
551 RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
552 if (RootDir
!= NULL
) {
553 Volume
->FSType
= FS_TYPE_FAT
;
554 } else if (!Volume
->BlockIO
->Media
->LogicalPartition
) {
555 Volume
->FSType
= FS_TYPE_WHOLEDISK
;
560 } // search for FAT and NTFS magic
562 // If no other filesystem is identified and block size is right, assume
564 if (Volume
->BlockIO
->Media
->BlockSize
== 2048) {
565 Volume
->FSType
= FS_TYPE_ISO9660
;
568 } // if ((Buffer != NULL) && (Volume != NULL))
569 } // UINT32 SetFilesystemData()
571 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
574 UINT8 Buffer
[SAMPLE_SIZE
];
576 MBR_PARTITION_INFO
*MbrTable
;
577 BOOLEAN MbrTableFound
= FALSE
;
579 Volume
->HasBootCode
= FALSE
;
580 Volume
->OSIconName
= NULL
;
581 Volume
->OSName
= NULL
;
584 if (Volume
->BlockIO
== NULL
)
586 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
587 return; // our buffer is too small...
589 // look at the boot sector (this is used for both hard disks and El Torito images!)
590 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
591 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
592 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
593 if (!EFI_ERROR(Status
)) {
594 SetFilesystemData(Buffer
, SAMPLE_SIZE
, Volume
);
596 if ((Status
== EFI_SUCCESS
) && (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)) {
597 if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) && (FindMem(Buffer
, 512, "EXFAT", 5) == -1)) {
599 Volume
->HasBootCode
= TRUE
;
602 // detect specific boot codes
603 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
604 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
605 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
606 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
607 Volume
->HasBootCode
= TRUE
;
608 Volume
->OSIconName
= L
"linux";
609 Volume
->OSName
= L
"Linux";
611 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
612 Volume
->HasBootCode
= TRUE
;
613 Volume
->OSIconName
= L
"grub,linux";
614 Volume
->OSName
= L
"Linux";
616 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
617 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
618 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
619 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
620 Volume
->HasBootCode
= TRUE
;
621 Volume
->OSIconName
= L
"freebsd";
622 Volume
->OSName
= L
"FreeBSD";
624 // If more differentiation needed, also search for
625 // "Invalid partition table" &/or "Missing boot loader".
626 } else if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55) &&
627 (FindMem(Buffer
, SECTOR_SIZE
, "Boot loader too large", 21) >= 0) &&
628 (FindMem(Buffer
, SECTOR_SIZE
, "I/O error loading boot loader", 29) >= 0)) {
629 Volume
->HasBootCode
= TRUE
;
630 Volume
->OSIconName
= L
"freebsd";
631 Volume
->OSName
= L
"FreeBSD";
633 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
634 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
635 Volume
->HasBootCode
= TRUE
;
636 Volume
->OSIconName
= L
"openbsd";
637 Volume
->OSName
= L
"OpenBSD";
639 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
640 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
641 Volume
->HasBootCode
= TRUE
;
642 Volume
->OSIconName
= L
"netbsd";
643 Volume
->OSName
= L
"NetBSD";
645 // Windows NT/200x/XP
646 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
647 Volume
->HasBootCode
= TRUE
;
648 Volume
->OSIconName
= L
"win";
649 Volume
->OSName
= L
"Windows";
652 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
653 Volume
->HasBootCode
= TRUE
;
654 Volume
->OSIconName
= L
"win8,win";
655 Volume
->OSName
= L
"Windows";
657 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
658 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
659 Volume
->HasBootCode
= TRUE
;
660 Volume
->OSIconName
= L
"freedos";
661 Volume
->OSName
= L
"FreeDOS";
663 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
664 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
665 Volume
->HasBootCode
= TRUE
;
666 Volume
->OSIconName
= L
"ecomstation";
667 Volume
->OSName
= L
"eComStation";
669 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
670 Volume
->HasBootCode
= TRUE
;
671 Volume
->OSIconName
= L
"beos";
672 Volume
->OSName
= L
"BeOS";
674 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
675 Volume
->HasBootCode
= TRUE
;
676 Volume
->OSIconName
= L
"zeta,beos";
677 Volume
->OSName
= L
"ZETA";
679 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
680 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
681 Volume
->HasBootCode
= TRUE
;
682 Volume
->OSIconName
= L
"haiku,beos";
683 Volume
->OSName
= L
"Haiku";
687 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
688 // need to fix AddLegacyEntry in refind/legacy.c.
691 Print(L
" Result of bootcode detection: %s %s (%s)\n",
692 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
693 Volume
->OSName
, Volume
->OSIconName
);
696 // dummy FAT boot sector (created by OS X's newfs_msdos)
697 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
698 Volume
->HasBootCode
= FALSE
;
700 // dummy FAT boot sector (created by Linux's mkdosfs)
701 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
702 Volume
->HasBootCode
= FALSE
;
704 // dummy FAT boot sector (created by Windows)
705 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
706 Volume
->HasBootCode
= FALSE
;
708 // check for MBR partition table
709 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
710 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
711 for (i
= 0; i
< 4; i
++)
712 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
713 MbrTableFound
= TRUE
;
714 for (i
= 0; i
< 4; i
++)
715 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
716 MbrTableFound
= FALSE
;
718 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
719 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
725 CheckError(Status
, L
"while reading boot sector");
728 } /* VOID ScanVolumeBootcode() */
730 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
731 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
733 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_BADGES
)
736 if (Volume
->VolBadgeImage
== NULL
) {
737 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", GlobalConfig
.IconSizes
[ICON_SIZE_BADGE
]);
740 if (Volume
->VolBadgeImage
== NULL
) {
741 switch (Volume
->DiskKind
) {
742 case DISK_KIND_INTERNAL
:
743 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
745 case DISK_KIND_EXTERNAL
:
746 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
748 case DISK_KIND_OPTICAL
:
749 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
752 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
756 } // VOID SetVolumeBadgeIcon()
758 // Return a string representing the input size in IEEE-1541 units.
759 // The calling function is responsible for freeing the allocated memory.
760 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
762 UINTN Index
= 0, NumPrefixes
;
763 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
766 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
767 if (TheValue
!= NULL
) {
768 NumPrefixes
= StrLen(Prefixes
);
769 SizeInIeee
= SizeInBytes
;
770 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
774 if (Prefixes
[Index
] == ' ') {
775 Units
= StrDuplicate(L
"-byte");
777 Units
= StrDuplicate(L
" iB");
778 Units
[1] = Prefixes
[Index
];
780 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
783 } // CHAR16 *SizeInIEEEUnits()
785 // Return a name for the volume. Ideally this should be the label for the
786 // filesystem or volume, but this function falls back to describing the
787 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
788 // this information can be extracted.
789 // The calling function is responsible for freeing the memory allocated
790 // for the name string.
791 static CHAR16
*GetVolumeName(REFIT_VOLUME
*Volume
) {
792 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
= NULL
;
793 CHAR16
*FoundName
= NULL
;
794 CHAR16
*SISize
, *TypeName
;
796 if (Volume
->RootDir
!= NULL
) {
797 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
800 if ((FileSystemInfoPtr
!= NULL
) && (FileSystemInfoPtr
->VolumeLabel
!= NULL
) &&
801 (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
802 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
805 // If no filesystem name, try to use the partition name....
806 if ((FoundName
== NULL
) && (Volume
->PartName
!= NULL
) && (StrLen(Volume
->PartName
) > 0) &&
807 !IsIn(Volume
->PartName
, IGNORE_PARTITION_NAMES
)) {
808 FoundName
= StrDuplicate(Volume
->PartName
);
809 } // if use partition name
811 // No filesystem or acceptable partition name, so use fs type and size
812 if ((FoundName
== NULL
) && (FileSystemInfoPtr
!= NULL
)) {
813 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
814 if (FoundName
!= NULL
) {
815 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
816 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
818 } // if allocated memory OK
819 } // if (FoundName == NULL)
821 MyFreePool(FileSystemInfoPtr
);
823 if (FoundName
== NULL
) {
824 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
825 if (FoundName
!= NULL
) {
826 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
827 if (StrLen(TypeName
) > 0)
828 SPrint(FoundName
, 255, L
"%s volume", TypeName
);
830 SPrint(FoundName
, 255, L
"unknown volume");
831 } // if allocated memory OK
834 // TODO: Above could be improved/extended, in case filesystem name is not found,
836 // - use or add disk/partition number (e.g., "(hd0,2)")
838 // Desperate fallback name....
839 if (FoundName
== NULL
) {
840 FoundName
= StrDuplicate(L
"unknown volume");
843 } // static CHAR16 *GetVolumeName()
845 // Determine the unique GUID, type code GUID, and name of the volume and store them.
846 static VOID
SetPartGuidAndName(REFIT_VOLUME
*Volume
, EFI_DEVICE_PATH_PROTOCOL
*DevicePath
) {
847 HARDDRIVE_DEVICE_PATH
*HdDevicePath
;
850 if ((Volume
== NULL
) || (DevicePath
== NULL
))
853 if ((DevicePath
->Type
== MEDIA_DEVICE_PATH
) && (DevicePath
->SubType
== MEDIA_HARDDRIVE_DP
)) {
854 HdDevicePath
= (HARDDRIVE_DEVICE_PATH
*) DevicePath
;
855 if (HdDevicePath
->SignatureType
== SIGNATURE_TYPE_GUID
) {
856 Volume
->PartGuid
= *((EFI_GUID
*) HdDevicePath
->Signature
);
857 PartInfo
= FindPartWithGuid(&(Volume
->PartGuid
));
859 Volume
->PartName
= StrDuplicate(PartInfo
->name
);
860 CopyMem(&(Volume
->PartTypeGuid
), PartInfo
->type_guid
, sizeof(EFI_GUID
));
861 if (GuidsAreEqual(&(Volume
->PartTypeGuid
), &gFreedesktopRootGuid
) &&
862 ((PartInfo
->attributes
& GPT_NO_AUTOMOUNT
) == 0)) {
863 GlobalConfig
.DiscoveredRoot
= Volume
;
864 } // if (GUIDs match && automounting OK)
865 Volume
->IsMarkedReadOnly
= ((PartInfo
->attributes
& GPT_READ_ONLY
) > 0);
866 } // if (PartInfo exists)
868 } // if (disk device)
869 } // VOID SetPartGuid()
871 // Return TRUE if NTFS boot files are found or if Volume is unreadable,
872 // FALSE otherwise. The idea is to weed out non-boot NTFS volumes from
873 // BIOS/legacy boot list on Macs. We can't assume NTFS will be readable,
874 // so return TRUE if it's unreadable; but if it IS readable, return
875 // TRUE only if Windows boot files are found.
876 static BOOLEAN
HasWindowsBiosBootFiles(REFIT_VOLUME
*Volume
) {
877 BOOLEAN FilesFound
= TRUE
;
879 if (Volume
->RootDir
!= NULL
) {
880 FilesFound
= FileExists(Volume
->RootDir
, L
"NTLDR") || // Windows NT/200x/XP boot file
881 FileExists(Volume
->RootDir
, L
"bootmgr"); // Windows Vista/7/8 boot file
884 } // static VOID HasWindowsBiosBootFiles()
886 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
889 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
890 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
891 EFI_HANDLE WholeDiskHandle
;
896 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
898 if (Volume
->DevicePath
!= NULL
) {
899 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
901 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
906 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
909 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
910 if (EFI_ERROR(Status
)) {
911 Volume
->BlockIO
= NULL
;
912 Print(L
"Warning: Can't get BlockIO protocol.\n");
914 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
915 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
918 // scan for bootcode and MBR table
920 ScanVolumeBootcode(Volume
, &Bootable
);
922 // detect device type
923 DevicePath
= Volume
->DevicePath
;
924 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
925 NextDevicePath
= NextDevicePathNode(DevicePath
);
927 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
) {
928 SetPartGuidAndName(Volume
, DevicePath
);
930 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
931 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
932 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
933 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
934 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
935 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
936 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
937 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
938 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
942 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
943 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
944 // TODO: also check for Boot Camp GUID
945 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
948 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
949 // make a device path for the whole device
950 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
951 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
952 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
953 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
955 // get the handle for that path
956 RemainingDevicePath
= DiskDevicePath
;
957 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
958 FreePool(DiskDevicePath
);
960 if (!EFI_ERROR(Status
)) {
961 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
963 // get the device path for later
964 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
965 if (!EFI_ERROR(Status
)) {
966 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
969 // look at the BlockIO protocol
970 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
971 (VOID
**) &Volume
->WholeDiskBlockIO
);
972 if (!EFI_ERROR(Status
)) {
974 // check the media block size
975 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
976 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
979 Volume
->WholeDiskBlockIO
= NULL
;
980 //CheckError(Status, L"from HandleProtocol");
983 // CheckError(Status, L"from LocateDevicePath");
986 DevicePath
= NextDevicePath
;
991 if (Volume
->HasBootCode
)
992 Print(L
" Volume considered non-bootable, but boot code is present\n");
994 Volume
->HasBootCode
= FALSE
;
997 // open the root directory of the volume
998 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1000 // Set volume icon based on .VolumeBadge icon or disk kind
1001 SetVolumeBadgeIcon(Volume
);
1003 Volume
->VolName
= GetVolumeName(Volume
);
1005 if (Volume
->RootDir
== NULL
) {
1006 Volume
->IsReadable
= FALSE
;
1009 Volume
->IsReadable
= TRUE
;
1010 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
) && (Volume
->FSType
== FS_TYPE_NTFS
) && Volume
->HasBootCode
) {
1011 // VBR boot code found on NTFS, but volume is not actually bootable
1012 // unless there are actual boot file, so check for them....
1013 Volume
->HasBootCode
= HasWindowsBiosBootFiles(Volume
);
1017 // get custom volume icons if present
1018 if (!Volume
->VolIconImage
) {
1019 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
1023 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
1026 REFIT_VOLUME
*Volume
;
1027 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
1029 UINTN LogicalPartitionIndex
= 4;
1030 UINT8 SectorBuffer
[512];
1032 MBR_PARTITION_INFO
*EMbrTable
;
1034 ExtBase
= MbrEntry
->StartLBA
;
1036 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
1037 // read current EMBR
1038 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
1039 WholeDiskVolume
->BlockIO
,
1040 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
1041 ExtCurrent
, 512, SectorBuffer
);
1042 if (EFI_ERROR(Status
))
1044 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
1046 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
1048 // scan logical partitions in this EMBR
1050 for (i
= 0; i
< 4; i
++) {
1051 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
1052 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
1054 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
1055 // set next ExtCurrent
1056 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
1059 // found a logical partition
1060 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1061 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
1062 Volume
->IsMbrPartition
= TRUE
;
1063 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
1064 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
1065 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
1066 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
1067 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
1068 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
1071 ScanVolumeBootcode(Volume
, &Bootable
);
1073 Volume
->HasBootCode
= FALSE
;
1074 SetVolumeBadgeIcon(Volume
);
1075 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1079 } /* VOID ScanExtendedPartition() */
1081 VOID
ScanVolumes(VOID
)
1084 EFI_HANDLE
*Handles
;
1085 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
1086 MBR_PARTITION_INFO
*MbrTable
;
1087 UINTN HandleCount
= 0;
1089 UINTN VolumeIndex
, VolumeIndex2
;
1090 UINTN PartitionIndex
;
1091 UINTN SectorSum
, i
, VolNumber
= 0;
1092 UINT8
*SectorBuffer1
, *SectorBuffer2
;
1094 EFI_GUID NullUuid
= NULL_GUID_VALUE
;
1096 MyFreePool(Volumes
);
1099 ForgetPartitionTables();
1101 // get all filesystem handles
1102 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
1103 UuidList
= AllocateZeroPool(sizeof(EFI_GUID
) * HandleCount
);
1104 if (Status
== EFI_NOT_FOUND
) {
1105 return; // no filesystems. strange, but true...
1107 if (CheckError(Status
, L
"while listing all file systems"))
1110 // first pass: collect information about all handles
1111 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1112 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1113 Volume
->DeviceHandle
= Handles
[HandleIndex
];
1114 AddPartitionTable(Volume
);
1117 UuidList
[HandleIndex
] = Volume
->VolUuid
;
1118 for (i
= 0; i
< HandleIndex
; i
++) {
1119 if ((CompareMem(&(Volume
->VolUuid
), &(UuidList
[i
]), sizeof(EFI_GUID
)) == 0) &&
1120 (CompareMem(&(Volume
->VolUuid
), &NullUuid
, sizeof(EFI_GUID
)) != 0)) { // Duplicate filesystem UUID
1121 Volume
->IsReadable
= FALSE
;
1125 if (Volume
->IsReadable
)
1126 Volume
->VolNumber
= VolNumber
++;
1128 Volume
->VolNumber
= VOL_UNREADABLE
;
1130 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1132 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
1133 SelfVolume
= Volume
;
1135 MyFreePool(Handles
);
1137 if (SelfVolume
== NULL
)
1138 Print(L
"WARNING: SelfVolume not found");
1140 // second pass: relate partitions and whole disk devices
1141 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1142 Volume
= Volumes
[VolumeIndex
];
1143 // check MBR partition table for extended partitions
1144 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1145 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
1146 Volume
->MbrPartitionTable
!= NULL
) {
1147 MbrTable
= Volume
->MbrPartitionTable
;
1148 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1149 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
1150 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
1155 // search for corresponding whole disk volume entry
1156 WholeDiskVolume
= NULL
;
1157 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1158 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1159 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1160 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1161 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0) {
1162 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1167 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1168 // check if this volume is one of the partitions in the table
1169 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1170 SectorBuffer1
= AllocatePool(512);
1171 SectorBuffer2
= AllocatePool(512);
1172 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1174 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1177 // compare boot sector read through offset vs. directly
1178 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1179 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1180 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1181 if (EFI_ERROR(Status
))
1183 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1184 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1185 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1186 if (EFI_ERROR(Status
))
1188 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1191 for (i
= 0; i
< 512; i
++)
1192 SectorSum
+= SectorBuffer1
[i
];
1193 if (SectorSum
< 1000)
1196 // TODO: mark entry as non-bootable if it is an extended partition
1198 // now we're reasonably sure the association is correct...
1199 Volume
->IsMbrPartition
= TRUE
;
1200 Volume
->MbrPartitionIndex
= PartitionIndex
;
1201 if (Volume
->VolName
== NULL
) {
1202 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1203 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1208 MyFreePool(SectorBuffer1
);
1209 MyFreePool(SectorBuffer2
);
1212 } /* VOID ScanVolumes() */
1215 // file and dir functions
1218 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1221 EFI_FILE_HANDLE TestFile
;
1223 if (BaseDir
!= NULL
) {
1224 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1225 if (Status
== EFI_SUCCESS
) {
1226 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1233 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1237 UINTN LastBufferSize
, BufferSize
;
1242 // free pointer from last call
1243 if (*DirEntry
!= NULL
) {
1244 FreePool(*DirEntry
);
1248 // read next directory entry
1249 LastBufferSize
= BufferSize
= 256;
1250 Buffer
= AllocatePool(BufferSize
);
1251 for (IterCount
= 0; ; IterCount
++) {
1252 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1253 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1255 if (BufferSize
<= LastBufferSize
) {
1256 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1257 BufferSize
= LastBufferSize
* 2;
1260 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1263 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1264 LastBufferSize
= BufferSize
;
1266 if (EFI_ERROR(Status
)) {
1272 // check for end of listing
1273 if (BufferSize
== 0) { // end of directory listing
1279 // entry is ready to be returned
1280 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1283 if (FilterMode
== 1) { // only return directories
1284 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1286 } else if (FilterMode
== 2) { // only return files
1287 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1289 } else // no filter or unknown filter -> return everything
1296 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1298 if (RelativePath
== NULL
) {
1299 DirIter
->LastStatus
= EFI_SUCCESS
;
1300 DirIter
->DirHandle
= BaseDir
;
1301 DirIter
->CloseDirHandle
= FALSE
;
1303 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1304 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1306 DirIter
->LastFileInfo
= NULL
;
1309 #ifndef __MAKEWITH_GNUEFI
1310 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1313 InitializeUnicodeCollationProtocol (VOID
)
1317 if (mUnicodeCollation
!= NULL
) {
1322 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1323 // instances first and then select one which support English language.
1324 // Current implementation just pick the first instance.
1326 Status
= gBS
->LocateProtocol (
1327 &gEfiUnicodeCollation2ProtocolGuid
,
1329 (VOID
**) &mUnicodeCollation
1331 if (EFI_ERROR(Status
)) {
1332 Status
= gBS
->LocateProtocol (
1333 &gEfiUnicodeCollationProtocolGuid
,
1335 (VOID
**) &mUnicodeCollation
1343 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1345 if (!mUnicodeCollation
) {
1346 InitializeUnicodeCollationProtocol();
1348 if (mUnicodeCollation
)
1349 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1350 return FALSE
; // Shouldn't happen
1355 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1356 OUT EFI_FILE_INFO
**DirEntry
)
1358 BOOLEAN KeepGoing
= TRUE
;
1362 if (DirIter
->LastFileInfo
!= NULL
) {
1363 FreePool(DirIter
->LastFileInfo
);
1364 DirIter
->LastFileInfo
= NULL
;
1367 if (EFI_ERROR(DirIter
->LastStatus
))
1368 return FALSE
; // stop iteration
1371 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1372 if (EFI_ERROR(DirIter
->LastStatus
))
1374 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1376 if (FilePattern
!= NULL
) {
1377 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1380 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1381 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1384 // else continue loop
1387 } while (KeepGoing
&& FilePattern
);
1389 *DirEntry
= DirIter
->LastFileInfo
;
1393 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1395 if (DirIter
->LastFileInfo
!= NULL
) {
1396 FreePool(DirIter
->LastFileInfo
);
1397 DirIter
->LastFileInfo
= NULL
;
1399 if (DirIter
->CloseDirHandle
)
1400 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1401 return DirIter
->LastStatus
;
1405 // file name manipulation
1408 // Returns the filename portion (minus path name) of the
1410 CHAR16
* Basename(IN CHAR16
*Path
)
1418 for (i
= StrLen(Path
); i
> 0; i
--) {
1419 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1420 FileName
= Path
+ i
;
1429 // Remove the .efi extension from FileName -- for instance, if FileName is
1430 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1431 // returns a copy of the original input.
1432 CHAR16
* StripEfiExtension(IN CHAR16
*FileName
) {
1434 CHAR16
*Copy
= NULL
;
1436 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1437 Length
= StrLen(Copy
);
1438 if ((Length
>= 4) && MyStriCmp(&Copy
[Length
- 4], L
".efi")) {
1439 Copy
[Length
- 4] = 0;
1443 } // CHAR16 * StripExtension()
1446 // memory string search
1449 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1455 BufferLength
-= SearchStringLength
;
1456 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1457 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1458 return (INTN
)Offset
;
1464 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1465 BOOLEAN Found
= 0, Terminate
= 0;
1466 UINTN BigIndex
= 0, SmallIndex
= 0, BigStart
= 0;
1468 if (SmallStr
&& BigStr
) {
1469 while (!Terminate
) {
1470 if (BigStr
[BigIndex
] == '\0') {
1473 if (SmallStr
[SmallIndex
] == '\0') {
1477 if ((SmallStr
[SmallIndex
] & ~0x20) == (BigStr
[BigIndex
] & ~0x20)) {
1483 BigIndex
= BigStart
;
1488 } // BOOLEAN StriSubCmp()
1490 // Performs a case-insensitive string comparison. This function is necesary
1491 // because some EFIs have buggy StriCmp() functions that actually perform
1492 // case-sensitive comparisons.
1493 // Returns TRUE if strings are identical, FALSE otherwise.
1494 BOOLEAN
MyStriCmp(IN CONST CHAR16
*FirstString
, IN CONST CHAR16
*SecondString
) {
1495 if (FirstString
&& SecondString
) {
1496 while ((*FirstString
!= L
'\0') && ((*FirstString
& ~0x20) == (*SecondString
& ~0x20))) {
1500 return (*FirstString
== *SecondString
);
1504 } // BOOLEAN MyStriCmp()
1506 // Convert input string to all-lowercase.
1507 // DO NOT USE the standard StrLwr() function, since it's broken on some EFIs!
1508 VOID
ToLower(CHAR16
* MyString
) {
1512 while (MyString
[i
] != L
'\0') {
1513 if ((MyString
[i
] >= L
'A') && (MyString
[i
] <= L
'Z'))
1514 MyString
[i
] = MyString
[i
] - L
'A' + L
'a';
1520 // Merges two strings, creating a new one and returning a pointer to it.
1521 // If AddChar != 0, the specified character is placed between the two original
1522 // strings (unless the first string is NULL or empty). The original input
1523 // string *First is de-allocated and replaced by the new merged string.
1524 // This is similar to StrCat, but safer and more flexible because
1525 // MergeStrings allocates memory that's the correct size for the
1526 // new merged string, so it can take a NULL *First and it cleans
1527 // up the old memory. It should *NOT* be used with a constant
1528 // *First, though....
1529 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1530 UINTN Length1
= 0, Length2
= 0;
1534 Length1
= StrLen(*First
);
1536 Length2
= StrLen(Second
);
1537 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1538 if (NewString
!= NULL
) {
1539 if ((*First
!= NULL
) && (Length1
== 0)) {
1543 NewString
[0] = L
'\0';
1544 if (*First
!= NULL
) {
1545 StrCat(NewString
, *First
);
1547 NewString
[Length1
] = AddChar
;
1548 NewString
[Length1
+ 1] = '\0';
1550 } // if (*First != NULL)
1552 StrCat(NewString
, Second
);
1556 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1558 } // VOID MergeStrings()
1560 // Similar to MergeStrings, but breaks the input string into word chunks and
1561 // merges each word separately. Words are defined as string fragments separated
1562 // by ' ', '_', or '-'.
1563 VOID
MergeWords(CHAR16
**MergeTo
, CHAR16
*SourceString
, CHAR16 AddChar
) {
1564 CHAR16
*Temp
, *Word
, *p
;
1565 BOOLEAN LineFinished
= FALSE
;
1568 Temp
= Word
= p
= StrDuplicate(SourceString
);
1570 while (!LineFinished
) {
1571 if ((*p
== L
' ') || (*p
== L
'_') || (*p
== L
'-') || (*p
== L
'\0')) {
1573 LineFinished
= TRUE
;
1576 MergeStrings(MergeTo
, Word
, AddChar
);
1583 Print(L
"Error! Unable to allocate memory in MergeWords()!\n");
1586 } // VOID MergeWords()
1588 // Takes an input pathname (*Path) and returns the part of the filename from
1589 // the final dot onwards, converted to lowercase. If the filename includes
1590 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1591 // The calling function is responsible for freeing the memory associated with
1592 // the return value.
1593 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1595 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1598 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1601 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1602 if (Path
[i
] == L
'.')
1604 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1610 MergeStrings(&Extension
, &Path
[i
], 0);
1615 } // CHAR16 *FindExtension()
1617 // Takes an input pathname (*Path) and locates the final directory component
1618 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1619 // function returns the string 'foo'.
1620 // Assumes the pathname is separated with backslashes.
1621 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1622 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1623 CHAR16
*Found
= NULL
;
1628 PathLength
= StrLen(Path
);
1629 // Find start & end of target element
1630 for (i
= 0; i
< PathLength
; i
++) {
1631 if (Path
[i
] == '\\') {
1632 StartOfElement
= EndOfElement
;
1636 // Extract the target element
1637 if (EndOfElement
> 0) {
1638 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1642 if (EndOfElement
>= StartOfElement
) {
1643 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1644 Found
= StrDuplicate(&Path
[StartOfElement
]);
1646 Found
[CopyLength
] = 0;
1647 } // if (EndOfElement >= StartOfElement)
1648 } // if (EndOfElement > 0)
1650 } // CHAR16 *FindLastDirName()
1652 // Returns the directory portion of a pathname. For instance,
1653 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1654 // string 'EFI\foo'. The calling function is responsible for
1655 // freeing the returned string's memory.
1656 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1657 UINTN i
, LastBackslash
= 0;
1658 CHAR16
*PathOnly
= NULL
;
1660 if (FullPath
!= NULL
) {
1661 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1662 if (FullPath
[i
] == '\\')
1665 PathOnly
= StrDuplicate(FullPath
);
1666 if (PathOnly
!= NULL
)
1667 PathOnly
[LastBackslash
] = 0;
1674 * Routine Description:
1680 * String - Null-terminated string to search.
1681 * StrCharSet - Null-terminated string to search for.
1684 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1686 CHAR16
* MyStrStr (IN CHAR16
*String
, IN CHAR16
*StrCharSet
)
1691 if ((String
== NULL
) || (StrCharSet
== NULL
))
1697 while ((*String
!= L
'\0') && (*StrCharSet
!= L
'\0')) {
1698 if (*String
++ != *StrCharSet
) {
1705 if (*StrCharSet
== L
'\0') {
1710 } // CHAR16 *MyStrStr()
1712 // Restrict TheString to at most Limit characters.
1713 // Does this in two ways:
1714 // - Locates stretches of two or more spaces and compresses
1715 // them down to one space.
1716 // - Truncates TheString
1717 // Returns TRUE if changes were made, FALSE otherwise
1718 BOOLEAN
LimitStringLength(CHAR16
*TheString
, UINTN Limit
) {
1719 CHAR16
*SubString
, *TempString
;
1721 BOOLEAN HasChanged
= FALSE
;
1723 // SubString will be NULL or point WITHIN TheString
1724 SubString
= MyStrStr(TheString
, L
" ");
1725 while (SubString
!= NULL
) {
1727 while (SubString
[i
] == L
' ')
1729 if (i
>= StrLen(SubString
)) {
1730 SubString
[0] = '\0';
1733 TempString
= StrDuplicate(&SubString
[i
]);
1734 if (TempString
!= NULL
) {
1735 StrCpy(&SubString
[1], TempString
);
1736 MyFreePool(TempString
);
1739 // memory allocation problem; abort to avoid potentially infinite loop!
1743 SubString
= MyStrStr(TheString
, L
" ");
1746 // If the string is still too long, truncate it....
1747 if (StrLen(TheString
) > Limit
) {
1748 TheString
[Limit
] = '\0';
1753 } // BOOLEAN LimitStringLength()
1755 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1756 // DeviceVolume, and returns that and the filename (*loader).
1757 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1758 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1760 BOOLEAN Found
= FALSE
;
1762 MyFreePool(*loader
);
1763 MyFreePool(*DeviceVolume
);
1764 *DeviceVolume
= NULL
;
1765 DeviceString
= DevicePathToStr(loadpath
);
1766 *loader
= SplitDeviceString(DeviceString
);
1768 while ((i
< VolumesCount
) && (!Found
)) {
1769 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1770 Temp
= SplitDeviceString(VolumeDeviceString
);
1771 if (MyStriCmp(DeviceString
, VolumeDeviceString
)) {
1773 *DeviceVolume
= Volumes
[i
];
1776 MyFreePool(VolumeDeviceString
);
1780 MyFreePool(DeviceString
);
1781 } // VOID FindVolumeAndFilename()
1783 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1784 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1785 // the filename component in the original *Path variable and the split-off
1786 // volume component in the *VolName variable.
1787 // Returns TRUE if both components are found, FALSE otherwise.
1788 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1789 UINTN i
= 0, Length
;
1795 if (*VolName
!= NULL
) {
1796 MyFreePool(*VolName
);
1800 Length
= StrLen(*Path
);
1801 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1806 Filename
= StrDuplicate((*Path
) + i
+ 1);
1814 } // BOOLEAN SplitVolumeAndFilename()
1816 // Returns all the digits in the input string, including intervening
1817 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1818 // this function returns "3.3.4-7". If InString contains no digits,
1819 // the return value is NULL.
1820 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1821 UINTN i
, StartOfElement
, EndOfElement
= 0, CopyLength
;
1822 CHAR16
*Found
= NULL
;
1824 if (InString
== NULL
)
1827 StartOfElement
= StrLen(InString
);
1828 // Find start & end of target element
1829 for (i
= 0; InString
[i
] != L
'\0'; i
++) {
1830 if ((InString
[i
] >= L
'0') && (InString
[i
] <= L
'9')) {
1831 if (StartOfElement
> i
)
1833 if (EndOfElement
< i
)
1837 // Extract the target element
1838 if (EndOfElement
> 0) {
1839 if (EndOfElement
>= StartOfElement
) {
1840 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1841 Found
= StrDuplicate(&InString
[StartOfElement
]);
1843 Found
[CopyLength
] = 0;
1844 } // if (EndOfElement >= StartOfElement)
1845 } // if (EndOfElement > 0)
1847 } // CHAR16 *FindNumbers()
1849 // Find the #Index element (numbered from 0) in a comma-delimited string
1851 // Returns the found element, or NULL if Index is out of range or InString
1852 // is NULL. Note that the calling function is responsible for freeing the
1853 // memory associated with the returned string pointer.
1854 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1855 UINTN StartPos
= 0, CurPos
= 0, InLength
;
1856 BOOLEAN Found
= FALSE
;
1857 CHAR16
*FoundString
= NULL
;
1859 if (InString
!= NULL
) {
1860 InLength
= StrLen(InString
);
1861 // After while() loop, StartPos marks start of item #Index
1862 while ((Index
> 0) && (CurPos
< InLength
)) {
1863 if (InString
[CurPos
] == L
',') {
1865 StartPos
= CurPos
+ 1;
1869 // After while() loop, CurPos is one past the end of the element
1870 while ((CurPos
< InLength
) && (!Found
)) {
1871 if (InString
[CurPos
] == L
',')
1877 FoundString
= StrDuplicate(&InString
[StartPos
]);
1878 if (FoundString
!= NULL
)
1879 FoundString
[CurPos
- StartPos
] = 0;
1881 return (FoundString
);
1882 } // CHAR16 *FindCommaDelimited()
1884 // Take an input path name, which may include a volume specification and/or
1885 // a path, and return separate volume, path, and file names. For instance,
1886 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1887 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1888 // the returned pointer is NULL. The calling function is responsible for
1889 // freeing the allocated memory.
1890 VOID
SplitPathName(CHAR16
*InPath
, CHAR16
**VolName
, CHAR16
**Path
, CHAR16
**Filename
) {
1891 CHAR16
*Temp
= NULL
;
1893 MyFreePool(*VolName
);
1895 MyFreePool(*Filename
);
1896 *VolName
= *Path
= *Filename
= NULL
;
1897 Temp
= StrDuplicate(InPath
);
1898 SplitVolumeAndFilename(&Temp
, VolName
); // VolName is NULL or has volume; Temp has rest of path
1899 CleanUpPathNameSlashes(Temp
);
1900 *Path
= FindPath(Temp
); // *Path has path (may be 0-length); Temp unchanged.
1901 *Filename
= StrDuplicate(Temp
+ StrLen(*Path
));
1902 CleanUpPathNameSlashes(*Filename
);
1903 if (StrLen(*Path
) == 0) {
1907 if (StrLen(*Filename
) == 0) {
1908 MyFreePool(*Filename
);
1912 } // VOID SplitPathName
1914 // Returns TRUE if SmallString is an element in the comma-delimited List,
1915 // FALSE otherwise. Performs comparison case-insensitively.
1916 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1918 BOOLEAN Found
= FALSE
;
1921 if (SmallString
&& List
) {
1922 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1923 if (MyStriCmp(OneElement
, SmallString
))
1930 // Returns TRUE if any element of List can be found as a substring of
1931 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1932 BOOLEAN
IsInSubstring(IN CHAR16
*BigString
, IN CHAR16
*List
) {
1933 UINTN i
= 0, ElementLength
;
1934 BOOLEAN Found
= FALSE
;
1937 if (BigString
&& List
) {
1938 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1939 ElementLength
= StrLen(OneElement
);
1940 if ((ElementLength
<= StrLen(BigString
)) && (StriSubCmp(OneElement
, BigString
)))
1945 } // BOOLEAN IsSubstringIn()
1947 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1948 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1949 // Filename must *NOT* include a volume or path specification (that's part of
1950 // the Volume variable), but the List elements may. Performs comparison
1951 // case-insensitively.
1952 BOOLEAN
FilenameIn(REFIT_VOLUME
*Volume
, CHAR16
*Directory
, CHAR16
*Filename
, CHAR16
*List
) {
1954 BOOLEAN Found
= FALSE
;
1956 CHAR16
*TargetVolName
= NULL
, *TargetPath
= NULL
, *TargetFilename
= NULL
;
1958 if (Filename
&& List
) {
1959 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1961 SplitPathName(OneElement
, &TargetVolName
, &TargetPath
, &TargetFilename
);
1962 VolumeNumberToName(Volume
, &TargetVolName
);
1963 if (((TargetVolName
!= NULL
) && ((Volume
== NULL
) || (!MyStriCmp(TargetVolName
, Volume
->VolName
)))) ||
1964 ((TargetPath
!= NULL
) && (!MyStriCmp(TargetPath
, Directory
))) ||
1965 ((TargetFilename
!= NULL
) && (!MyStriCmp(TargetFilename
, Filename
)))) {
1968 MyFreePool(OneElement
);
1972 MyFreePool(TargetVolName
);
1973 MyFreePool(TargetPath
);
1974 MyFreePool(TargetFilename
);
1976 } // BOOLEAN FilenameIn()
1978 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1979 // to this volume number, returns with *VolName changed to the volume name, as
1980 // stored in the Volume data structure.
1981 // Returns TRUE if this substitution was made, FALSE otherwise.
1982 BOOLEAN
VolumeNumberToName(REFIT_VOLUME
*Volume
, CHAR16
**VolName
) {
1983 BOOLEAN MadeSubstitution
= FALSE
;
1986 if ((VolName
== NULL
) || (*VolName
== NULL
))
1989 if ((StrLen(*VolName
) > 2) && (*VolName
[0] == L
'f') && (*VolName
[1] == L
's') && (*VolName
[2] >= L
'0') && (*VolName
[2] <= L
'9')) {
1990 VolNum
= Atoi(*VolName
+ 2);
1991 if (VolNum
== Volume
->VolNumber
) {
1992 MyFreePool(*VolName
);
1993 *VolName
= StrDuplicate(Volume
->VolName
);
1994 MadeSubstitution
= TRUE
;
1997 return MadeSubstitution
;
1998 } // BOOLEAN VolumeMatchesNumber()
2000 // Implement FreePool the way it should have been done to begin with, so that
2001 // it doesn't throw an ASSERT message if fed a NULL pointer....
2002 VOID
MyFreePool(IN VOID
*Pointer
) {
2003 if (Pointer
!= NULL
)
2007 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
2009 // Eject all removable media.
2010 // Returns TRUE if any media were ejected, FALSE otherwise.
2011 BOOLEAN
EjectMedia(VOID
) {
2013 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
2014 EFI_HANDLE
*Handles
, Handle
;
2015 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
2017 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
2018 if (EFI_ERROR(Status
) || HandleCount
== 0)
2019 return (FALSE
); // probably not an Apple system
2021 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
2022 Handle
= Handles
[HandleIndex
];
2023 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
2024 if (EFI_ERROR(Status
))
2026 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
2027 if (!EFI_ERROR(Status
))
2030 MyFreePool(Handles
);
2031 return (Ejected
> 0);
2032 } // VOID EjectMedia()
2034 // Converts consecutive characters in the input string into a
2035 // number, interpreting the string as a hexadecimal number, starting
2036 // at the specified position and continuing for the specified number
2037 // of characters or until the end of the string, whichever is first.
2038 // NumChars must be between 1 and 16. Ignores invalid characters.
2039 UINT64
StrToHex(CHAR16
*Input
, UINTN Pos
, UINTN NumChars
) {
2040 UINT64 retval
= 0x00;
2041 UINTN NumDone
= 0, InputLength
;
2044 if ((Input
== NULL
) || (NumChars
== 0) || (NumChars
> 16)) {
2048 InputLength
= StrLen(Input
);
2049 while ((Pos
<= InputLength
) && (NumDone
< NumChars
)) {
2051 if ((a
>= '0') && (a
<= '9')) {
2053 retval
+= (a
- '0');
2056 if ((a
>= 'a') && (a
<= 'f')) {
2058 retval
+= (a
- 'a' + 0x0a);
2061 if ((a
>= 'A') && (a
<= 'F')) {
2063 retval
+= (a
- 'A' + 0x0a);
2071 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2072 // Note that the input string must have no extraneous spaces and must be
2073 // conventionally formatted as a 36-character GUID, complete with dashes in
2074 // appropriate places.
2075 BOOLEAN
IsGuid(CHAR16
*UnknownString
) {
2077 BOOLEAN retval
= TRUE
;
2080 if (UnknownString
== NULL
)
2083 Length
= StrLen(UnknownString
);
2087 for (i
= 0; i
< Length
; i
++) {
2088 a
= UnknownString
[i
];
2089 if ((i
== 8) || (i
== 13) || (i
== 18) || (i
== 23)) {
2092 } else if (((a
< L
'a') || (a
> L
'f')) &&
2093 ((a
< L
'A') || (a
> L
'F')) &&
2094 ((a
< L
'0') && (a
> L
'9'))) {
2099 } // BOOLEAN IsGuid()
2101 // Return the GUID as a string, suitable for display to the user. Note that the calling
2102 // function is responsible for freeing the allocated memory.
2103 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
2106 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
2107 if (TheString
!= 0) {
2108 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2109 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
2110 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
2111 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
2112 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
2115 } // GuidAsString(EFI_GUID *GuidData)
2117 EFI_GUID
StringAsGuid(CHAR16
* InString
) {
2118 EFI_GUID Guid
= NULL_GUID_VALUE
;
2120 if (!IsGuid(InString
)) {
2124 Guid
.Data1
= (UINT32
) StrToHex(InString
, 0, 8);
2125 Guid
.Data2
= (UINT16
) StrToHex(InString
, 9, 4);
2126 Guid
.Data3
= (UINT16
) StrToHex(InString
, 14, 4);
2127 Guid
.Data4
[0] = (UINT8
) StrToHex(InString
, 19, 2);
2128 Guid
.Data4
[1] = (UINT8
) StrToHex(InString
, 21, 2);
2129 Guid
.Data4
[2] = (UINT8
) StrToHex(InString
, 23, 2);
2130 Guid
.Data4
[3] = (UINT8
) StrToHex(InString
, 26, 2);
2131 Guid
.Data4
[4] = (UINT8
) StrToHex(InString
, 28, 2);
2132 Guid
.Data4
[5] = (UINT8
) StrToHex(InString
, 30, 2);
2133 Guid
.Data4
[6] = (UINT8
) StrToHex(InString
, 32, 2);
2134 Guid
.Data4
[7] = (UINT8
) StrToHex(InString
, 34, 2);
2137 } // EFI_GUID StringAsGuid()
2139 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2140 BOOLEAN
GuidsAreEqual(EFI_GUID
*Guid1
, EFI_GUID
*Guid2
) {
2141 return (CompareMem(Guid1
, Guid2
, 16) == 0);
2142 } // BOOLEAN GuidsAreEqual()