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"
54 #ifdef __MAKEWITH_GNUEFI
55 #define EfiReallocatePool ReallocatePool
57 #define LibLocateHandle gBS->LocateHandleBuffer
58 #define DevicePathProtocol gEfiDevicePathProtocolGuid
59 #define BlockIoProtocol gEfiBlockIoProtocolGuid
60 #define LibFileSystemInfo EfiLibFileSystemInfo
61 #define LibOpenRoot EfiLibOpenRoot
62 EFI_DEVICE_PATH EndDevicePath
[] = {
63 {END_DEVICE_PATH_TYPE
, END_ENTIRE_DEVICE_PATH_SUBTYPE
, {END_DEVICE_PATH_LENGTH
, 0}}
67 // "Magic" signatures for various filesystems
68 #define FAT_MAGIC 0xAA55
69 #define EXT2_SUPER_MAGIC 0xEF53
70 #define HFSPLUS_MAGIC1 0x2B48
71 #define HFSPLUS_MAGIC2 0x5848
72 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
73 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
74 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
75 #define BTRFS_SIGNATURE "_BHRfS_M"
76 #define XFS_SIGNATURE "XFSB"
77 #define NTFS_SIGNATURE "NTFS "
81 EFI_HANDLE SelfImageHandle
;
82 EFI_LOADED_IMAGE
*SelfLoadedImage
;
83 EFI_FILE
*SelfRootDir
;
87 REFIT_VOLUME
*SelfVolume
= NULL
;
88 REFIT_VOLUME
**Volumes
= NULL
;
89 UINTN VolumesCount
= 0;
90 extern GPT_DATA
*gPartitions
;
92 // Maximum size for disk sectors
93 #define SECTOR_SIZE 4096
95 // Number of bytes to read from a partition to determine its filesystem type
96 // and identify its boot loader, and hence probable BIOS-mode OS installation
97 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
100 // Pathname manipulations
103 // Converts forward slashes to backslashes, removes duplicate slashes, and
104 // removes slashes from both the start and end of the pathname.
105 // Necessary because some (buggy?) EFI implementations produce "\/" strings
106 // in pathnames, because some user inputs can produce duplicate directory
107 // separators, and because we want consistent start and end slashes for
108 // directory comparisons. A special case: If the PathName refers to root,
109 // return "/", since some firmware implementations flake out if this
111 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
113 UINTN i
, Length
, FinalChar
= 0;
114 BOOLEAN LastWasSlash
= FALSE
;
116 Length
= StrLen(PathName
);
117 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (Length
+ 2));
118 if (NewName
!= NULL
) {
119 for (i
= 0; i
< Length
; i
++) {
120 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
121 if ((!LastWasSlash
) && (FinalChar
!= 0))
122 NewName
[FinalChar
++] = L
'\\';
125 NewName
[FinalChar
++] = PathName
[i
];
126 LastWasSlash
= FALSE
;
129 NewName
[FinalChar
] = 0;
130 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
131 NewName
[--FinalChar
] = 0;
132 if (FinalChar
== 0) {
136 // Copy the transformed name back....
137 StrCpy(PathName
, NewName
);
139 } // if allocation OK
140 } // CleanUpPathNameSlashes()
142 // Splits an EFI device path into device and filename components. For instance, if InString is
143 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
144 // this function will truncate that input to
145 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
146 // and return bzImage-3.5.1.efi as its return value.
147 // It does this by searching for the last ")" character in InString, copying everything
148 // after that string (after some cleanup) as the return value, and truncating the original
150 // If InString contains no ")" character, this function leaves the original input string
151 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
152 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
154 CHAR16
*FileName
= NULL
;
155 BOOLEAN Found
= FALSE
;
157 if (InString
!= NULL
) {
158 i
= StrLen(InString
) - 1;
159 while ((i
>= 0) && (!Found
)) {
160 if (InString
[i
] == L
')') {
162 FileName
= StrDuplicate(&InString
[i
+ 1]);
163 CleanUpPathNameSlashes(FileName
);
164 InString
[i
+ 1] = '\0';
168 if (FileName
== NULL
)
169 FileName
= StrDuplicate(InString
);
172 } // static CHAR16* SplitDeviceString()
175 // Library initialization and de-initialization
178 static EFI_STATUS
FinishInitRefitLib(VOID
)
182 if (SelfRootDir
== NULL
) {
183 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
184 if (SelfRootDir
== NULL
) {
185 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
186 return EFI_LOAD_ERROR
;
190 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
191 if (CheckFatalError(Status
, L
"while opening our installation directory"))
192 return EFI_LOAD_ERROR
;
197 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
200 CHAR16
*DevicePathAsString
, *Temp
;
202 SelfImageHandle
= ImageHandle
;
203 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
204 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
205 return EFI_LOAD_ERROR
;
207 // find the current directory
208 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
209 GlobalConfig
.SelfDevicePath
= FileDevicePath(SelfLoadedImage
->DeviceHandle
, DevicePathAsString
);
210 CleanUpPathNameSlashes(DevicePathAsString
);
211 MyFreePool(SelfDirPath
);
212 Temp
= FindPath(DevicePathAsString
);
213 SelfDirPath
= SplitDeviceString(Temp
);
214 MyFreePool(DevicePathAsString
);
217 return FinishInitRefitLib();
220 static VOID
UninitVolumes(VOID
)
222 REFIT_VOLUME
*Volume
;
225 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
226 Volume
= Volumes
[VolumeIndex
];
228 if (Volume
->RootDir
!= NULL
) {
229 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
230 Volume
->RootDir
= NULL
;
233 Volume
->DeviceHandle
= NULL
;
234 Volume
->BlockIO
= NULL
;
235 Volume
->WholeDiskBlockIO
= NULL
;
237 } /* VOID UninitVolumes() */
239 VOID
ReinitVolumes(VOID
)
242 REFIT_VOLUME
*Volume
;
244 EFI_DEVICE_PATH
*RemainingDevicePath
;
245 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
247 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
248 Volume
= Volumes
[VolumeIndex
];
250 if (Volume
->DevicePath
!= NULL
) {
251 // get the handle for that path
252 RemainingDevicePath
= Volume
->DevicePath
;
253 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
255 if (!EFI_ERROR(Status
)) {
256 Volume
->DeviceHandle
= DeviceHandle
;
258 // get the root directory
259 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
262 CheckError(Status
, L
"from LocateDevicePath");
265 if (Volume
->WholeDiskDevicePath
!= NULL
) {
266 // get the handle for that path
267 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
268 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
270 if (!EFI_ERROR(Status
)) {
271 // get the BlockIO protocol
272 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
273 (VOID
**) &Volume
->WholeDiskBlockIO
);
274 if (EFI_ERROR(Status
)) {
275 Volume
->WholeDiskBlockIO
= NULL
;
276 CheckError(Status
, L
"from HandleProtocol");
279 CheckError(Status
, L
"from LocateDevicePath");
282 } /* VOID ReinitVolumes(VOID) */
284 // called before running external programs to close open file handles
285 VOID
UninitRefitLib(VOID
)
287 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
288 // See the comment on it there.
289 if(SelfRootDir
== SelfVolume
->RootDir
)
294 if (SelfDir
!= NULL
) {
295 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
299 if (SelfRootDir
!= NULL
) {
300 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
303 } /* VOID UninitRefitLib() */
305 // called after running external programs to re-open file handles
306 EFI_STATUS
ReinitRefitLib(VOID
)
310 if ((ST
->Hdr
.Revision
>> 16) == 1) {
311 // Below two lines were in rEFIt, but seem to cause system crashes or
312 // reboots when launching OSes after returning from programs on most
313 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
314 // installation volume" (see the next function) when returning from
315 // programs when these two lines are removed, and it often crashes
316 // when returning from a program or when launching a second program
317 // with these lines removed. Therefore, the preceding if() statement
318 // executes these lines only on EFIs with a major version number of 1
319 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
320 // of hardware on which to test is limited, though, so this may be the
321 // wrong test, or there may be a better way to fix this problem.
322 // TODO: Figure out cause of above weirdness and fix it more
324 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
325 SelfRootDir
= SelfVolume
->RootDir
;
328 return FinishInitRefitLib();
332 // EFI variable read and write functions
335 // From gummiboot: Retrieve a raw EFI variable.
336 // Returns EFI status
337 EFI_STATUS
EfivarGetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
**buffer
, UINTN
*size
) {
342 l
= sizeof(CHAR16
*) * EFI_MAXIMUM_VARIABLE_SIZE
;
343 buf
= AllocatePool(l
);
345 return EFI_OUT_OF_RESOURCES
;
347 err
= refit_call5_wrapper(RT
->GetVariable
, name
, vendor
, NULL
, &l
, buf
);
348 if (EFI_ERROR(err
) == EFI_SUCCESS
) {
355 } // EFI_STATUS EfivarGetRaw()
357 // From gummiboot: Set an EFI variable
358 EFI_STATUS
EfivarSetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
*buf
, UINTN size
, BOOLEAN persistent
) {
361 flags
= EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
363 flags
|= EFI_VARIABLE_NON_VOLATILE
;
365 return refit_call5_wrapper(RT
->SetVariable
, name
, vendor
, flags
, size
, buf
);
366 } // EFI_STATUS EfivarSetRaw()
372 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
376 if ((*ElementCount
& 15) == 0) {
377 AllocateCount
= *ElementCount
+ 16;
378 if (*ElementCount
== 0)
379 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
381 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
383 (*ListPtr
)[*ElementCount
] = NewElement
;
385 } /* VOID AddListElement() */
387 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
391 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
392 for (i
= 0; i
< *ElementCount
; i
++) {
393 // TODO: call a user-provided routine for each element here
394 MyFreePool((*ListPtr
)[i
]);
396 MyFreePool(*ListPtr
);
404 // Return a pointer to a string containing a filesystem type name. If the
405 // filesystem type is unknown, a blank (but non-null) string is returned.
406 // The returned variable is a constant that should NOT be freed.
407 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
408 CHAR16
*retval
= NULL
;
411 case FS_TYPE_WHOLEDISK
:
412 retval
= L
" whole disk";
417 case FS_TYPE_HFSPLUS
:
429 case FS_TYPE_REISERFS
:
430 retval
= L
" ReiserFS";
438 case FS_TYPE_ISO9660
:
439 retval
= L
" ISO-9660";
449 } // CHAR16 *FSTypeName()
451 // Identify the filesystem type and record the filesystem's UUID/serial number,
452 // if possible. Expects a Buffer containing the first few (normally at least
453 // 4096) bytes of the filesystem. Sets the filesystem type code in Volume->FSType
454 // and the UUID/serial number in Volume->VolUuid. Note that the UUID value is
455 // recognized differently for each filesystem, and is currently supported only
456 // for NTFS, ext2/3/4fs, and ReiserFS (and for NTFS it's really a 64-bit serial
457 // number not a UUID or GUID). If the UUID can't be determined, it's set to 0.
458 // Also, the UUID is just read directly into memory; it is *NOT* valid when
459 // displayed by GuidAsString() or used in other GUID/UUID-manipulating
460 // functions. (As I write, it's being used merely to detect partitions that are
461 // part of a RAID 1 array.)
462 static VOID
SetFilesystemData(IN UINT8
*Buffer
, IN UINTN BufferSize
, IN OUT REFIT_VOLUME
*Volume
) {
463 UINT32
*Ext2Incompat
, *Ext2Compat
;
468 if ((Buffer
!= NULL
) && (Volume
!= NULL
)) {
469 SetMem(&(Volume
->VolUuid
), sizeof(EFI_GUID
), 0);
470 Volume
->FSType
= FS_TYPE_UNKNOWN
;
472 if (BufferSize
>= (1024 + 100)) {
473 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
474 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
475 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
476 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
477 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
478 Volume
->FSType
= FS_TYPE_EXT4
;
479 } else if (*Ext2Compat
& 0x0004) { // check for journal
480 Volume
->FSType
= FS_TYPE_EXT3
;
481 } else { // none of these features; presume it's ext2...
482 Volume
->FSType
= FS_TYPE_EXT2
;
484 CopyMem(&(Volume
->VolUuid
), Buffer
+ 1024 + 104, sizeof(EFI_GUID
));
487 } // search for ext2/3/4 magic
489 if (BufferSize
>= (65536 + 100)) {
490 MagicString
= (char*) (Buffer
+ 65536 + 52);
491 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
492 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
493 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
494 Volume
->FSType
= FS_TYPE_REISERFS
;
495 CopyMem(&(Volume
->VolUuid
), Buffer
+ 65536 + 84, sizeof(EFI_GUID
));
498 } // search for ReiserFS magic
500 if (BufferSize
>= (65536 + 64 + 8)) {
501 MagicString
= (char*) (Buffer
+ 65536 + 64);
502 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0) {
503 Volume
->FSType
= FS_TYPE_BTRFS
;
506 } // search for Btrfs magic
508 if (BufferSize
>= 512) {
509 MagicString
= (char*) Buffer
;
510 if (CompareMem(MagicString
, XFS_SIGNATURE
, 4) == 0) {
511 Volume
->FSType
= FS_TYPE_XFS
;
514 } // search for XFS magic
516 if (BufferSize
>= (1024 + 2)) {
517 Magic16
= (UINT16
*) (Buffer
+ 1024);
518 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
519 Volume
->FSType
= FS_TYPE_HFSPLUS
;
522 } // search for HFS+ magic
524 if (BufferSize
>= 512) {
525 // Search for NTFS, FAT, and MBR/EBR.
526 // These all have 0xAA55 at the end of the first sector, but FAT and
527 // MBR/EBR are not easily distinguished. Thus, we first look for NTFS
528 // "magic"; then check to see if the volume can be mounted, thus
529 // relying on the EFI's built-in FAT driver to identify FAT; and then
530 // check to see if the "volume" is in fact a whole-disk device.
531 Magic16
= (UINT16
*) (Buffer
+ 510);
532 if (*Magic16
== FAT_MAGIC
) {
533 MagicString
= (char*) (Buffer
+ 3);
534 if (CompareMem(MagicString
, NTFS_SIGNATURE
, 8) == 0) {
535 Volume
->FSType
= FS_TYPE_NTFS
;
536 CopyMem(&(Volume
->VolUuid
), Buffer
+ 0x48, sizeof(UINT64
));
538 RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
539 if (RootDir
!= NULL
) {
540 Volume
->FSType
= FS_TYPE_FAT
;
541 } else if (!Volume
->BlockIO
->Media
->LogicalPartition
) {
542 Volume
->FSType
= FS_TYPE_WHOLEDISK
;
547 } // search for FAT and NTFS magic
549 // If no other filesystem is identified and block size is right, assume
551 if (Volume
->BlockIO
->Media
->BlockSize
== 2048) {
552 Volume
->FSType
= FS_TYPE_ISO9660
;
555 } // if ((Buffer != NULL) && (Volume != NULL))
556 } // UINT32 SetFilesystemData()
558 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
561 UINT8 Buffer
[SAMPLE_SIZE
];
563 MBR_PARTITION_INFO
*MbrTable
;
564 BOOLEAN MbrTableFound
= FALSE
;
566 Volume
->HasBootCode
= FALSE
;
567 Volume
->OSIconName
= NULL
;
568 Volume
->OSName
= NULL
;
571 if (Volume
->BlockIO
== NULL
)
573 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
574 return; // our buffer is too small...
576 // look at the boot sector (this is used for both hard disks and El Torito images!)
577 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
578 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
579 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
580 if (!EFI_ERROR(Status
)) {
581 SetFilesystemData(Buffer
, SAMPLE_SIZE
, Volume
);
583 if ((Status
== EFI_SUCCESS
) && (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)) {
584 if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) && (FindMem(Buffer
, 512, "EXFAT", 5) == -1)) {
586 Volume
->HasBootCode
= TRUE
;
589 // detect specific boot codes
590 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
591 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
592 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
593 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
594 Volume
->HasBootCode
= TRUE
;
595 Volume
->OSIconName
= L
"linux";
596 Volume
->OSName
= L
"Linux";
598 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
599 Volume
->HasBootCode
= TRUE
;
600 Volume
->OSIconName
= L
"grub,linux";
601 Volume
->OSName
= L
"Linux";
603 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
604 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
605 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
606 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
607 Volume
->HasBootCode
= TRUE
;
608 Volume
->OSIconName
= L
"freebsd";
609 Volume
->OSName
= L
"FreeBSD";
611 // If more differentiation needed, also search for
612 // "Invalid partition table" &/or "Missing boot loader".
613 } else if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55) &&
614 (FindMem(Buffer
, SECTOR_SIZE
, "Boot loader too large", 21) >= 0) &&
615 (FindMem(Buffer
, SECTOR_SIZE
, "I/O error loading boot loader", 29) >= 0)) {
616 Volume
->HasBootCode
= TRUE
;
617 Volume
->OSIconName
= L
"freebsd";
618 Volume
->OSName
= L
"FreeBSD";
620 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
621 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
622 Volume
->HasBootCode
= TRUE
;
623 Volume
->OSIconName
= L
"openbsd";
624 Volume
->OSName
= L
"OpenBSD";
626 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
627 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
628 Volume
->HasBootCode
= TRUE
;
629 Volume
->OSIconName
= L
"netbsd";
630 Volume
->OSName
= L
"NetBSD";
632 // Windows NT/200x/XP
633 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
634 Volume
->HasBootCode
= TRUE
;
635 Volume
->OSIconName
= L
"win";
636 Volume
->OSName
= L
"Windows";
639 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
640 Volume
->HasBootCode
= TRUE
;
641 Volume
->OSIconName
= L
"win8,win";
642 Volume
->OSName
= L
"Windows";
644 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
645 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
646 Volume
->HasBootCode
= TRUE
;
647 Volume
->OSIconName
= L
"freedos";
648 Volume
->OSName
= L
"FreeDOS";
650 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
651 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
652 Volume
->HasBootCode
= TRUE
;
653 Volume
->OSIconName
= L
"ecomstation";
654 Volume
->OSName
= L
"eComStation";
656 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
657 Volume
->HasBootCode
= TRUE
;
658 Volume
->OSIconName
= L
"beos";
659 Volume
->OSName
= L
"BeOS";
661 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
662 Volume
->HasBootCode
= TRUE
;
663 Volume
->OSIconName
= L
"zeta,beos";
664 Volume
->OSName
= L
"ZETA";
666 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
667 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
668 Volume
->HasBootCode
= TRUE
;
669 Volume
->OSIconName
= L
"haiku,beos";
670 Volume
->OSName
= L
"Haiku";
674 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
675 // need to fix AddLegacyEntry in refind/legacy.c.
678 Print(L
" Result of bootcode detection: %s %s (%s)\n",
679 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
680 Volume
->OSName
, Volume
->OSIconName
);
683 // dummy FAT boot sector (created by OS X's newfs_msdos)
684 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
685 Volume
->HasBootCode
= FALSE
;
687 // dummy FAT boot sector (created by Linux's mkdosfs)
688 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
689 Volume
->HasBootCode
= FALSE
;
691 // dummy FAT boot sector (created by Windows)
692 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
693 Volume
->HasBootCode
= FALSE
;
695 // check for MBR partition table
696 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
697 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
698 for (i
= 0; i
< 4; i
++)
699 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
700 MbrTableFound
= TRUE
;
701 for (i
= 0; i
< 4; i
++)
702 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
703 MbrTableFound
= FALSE
;
705 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
706 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
712 CheckError(Status
, L
"while reading boot sector");
715 } /* VOID ScanVolumeBootcode() */
717 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
718 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
720 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_BADGES
)
723 if (Volume
->VolBadgeImage
== NULL
) {
724 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", GlobalConfig
.IconSizes
[ICON_SIZE_BADGE
]);
727 if (Volume
->VolBadgeImage
== NULL
) {
728 switch (Volume
->DiskKind
) {
729 case DISK_KIND_INTERNAL
:
730 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
732 case DISK_KIND_EXTERNAL
:
733 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
735 case DISK_KIND_OPTICAL
:
736 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
739 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
743 } // VOID SetVolumeBadgeIcon()
745 // Return a string representing the input size in IEEE-1541 units.
746 // The calling function is responsible for freeing the allocated memory.
747 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
749 UINTN Index
= 0, NumPrefixes
;
750 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
753 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
754 if (TheValue
!= NULL
) {
755 NumPrefixes
= StrLen(Prefixes
);
756 SizeInIeee
= SizeInBytes
;
757 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
761 if (Prefixes
[Index
] == ' ') {
762 Units
= StrDuplicate(L
"-byte");
764 Units
= StrDuplicate(L
" iB");
765 Units
[1] = Prefixes
[Index
];
767 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
770 } // CHAR16 *SizeInIEEEUnits()
772 // Return a name for the volume. Ideally this should be the label for the
773 // filesystem or volume, but this function falls back to describing the
774 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
775 // this information can be extracted.
776 // The calling function is responsible for freeing the memory allocated
777 // for the name string.
778 static CHAR16
*GetVolumeName(REFIT_VOLUME
*Volume
) {
779 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
= NULL
;
780 CHAR16
*FoundName
= NULL
;
781 CHAR16
*SISize
, *TypeName
;
783 if (Volume
->RootDir
!= NULL
) {
784 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
787 if ((FileSystemInfoPtr
!= NULL
) && (FileSystemInfoPtr
->VolumeLabel
!= NULL
) &&
788 (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
789 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
792 // If no filesystem name, try to use the partition name....
793 if ((FoundName
== NULL
) && (Volume
->PartName
!= NULL
) && (StrLen(Volume
->PartName
) > 0) &&
794 !IsIn(Volume
->PartName
, IGNORE_PARTITION_NAMES
)) {
795 FoundName
= StrDuplicate(Volume
->PartName
);
796 } // if use partition name
798 // No filesystem or acceptable partition name, so use fs type and size
799 if ((FoundName
== NULL
) && (FileSystemInfoPtr
!= NULL
)) {
800 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
801 if (FoundName
!= NULL
) {
802 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
803 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
805 } // if allocated memory OK
806 } // if (FoundName == NULL)
808 MyFreePool(FileSystemInfoPtr
);
810 if (FoundName
== NULL
) {
811 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
812 if (FoundName
!= NULL
) {
813 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
814 if (StrLen(TypeName
) > 0)
815 SPrint(FoundName
, 255, L
"%s volume", TypeName
);
817 SPrint(FoundName
, 255, L
"unknown volume");
818 } // if allocated memory OK
821 // TODO: Above could be improved/extended, in case filesystem name is not found,
823 // - use or add disk/partition number (e.g., "(hd0,2)")
825 // Desperate fallback name....
826 if (FoundName
== NULL
) {
827 FoundName
= StrDuplicate(L
"unknown volume");
830 } // static CHAR16 *GetVolumeName()
832 // Determine the unique GUID, type code GUID, and name of the volume and store them.
833 static VOID
SetPartGuidAndName(REFIT_VOLUME
*Volume
, EFI_DEVICE_PATH_PROTOCOL
*DevicePath
) {
834 HARDDRIVE_DEVICE_PATH
*HdDevicePath
;
837 if ((Volume
== NULL
) || (DevicePath
== NULL
))
840 if ((DevicePath
->Type
== MEDIA_DEVICE_PATH
) && (DevicePath
->SubType
== MEDIA_HARDDRIVE_DP
)) {
841 HdDevicePath
= (HARDDRIVE_DEVICE_PATH
*) DevicePath
;
842 if (HdDevicePath
->SignatureType
== SIGNATURE_TYPE_GUID
) {
843 Volume
->PartGuid
= *((EFI_GUID
*) HdDevicePath
->Signature
);
844 PartInfo
= FindPartWithGuid(&(Volume
->PartGuid
));
846 Volume
->PartName
= StrDuplicate(PartInfo
->name
);
847 CopyMem(&(Volume
->PartTypeGuid
), PartInfo
->type_guid
, sizeof(EFI_GUID
));
848 if (GuidsAreEqual(&(Volume
->PartTypeGuid
), &gFreedesktopRootGuid
) &&
849 ((PartInfo
->attributes
& GPT_NO_AUTOMOUNT
) == 0)) {
850 GlobalConfig
.DiscoveredRoot
= Volume
;
851 } // if (GUIDs match && automounting OK)
852 Volume
->IsMarkedReadOnly
= ((PartInfo
->attributes
& GPT_READ_ONLY
) > 0);
853 } // if (PartInfo exists)
855 } // if (disk device)
856 } // VOID SetPartGuid()
858 // Return TRUE if NTFS boot files are found or if Volume is unreadable,
859 // FALSE otherwise. The idea is to weed out non-boot NTFS volumes from
860 // BIOS/legacy boot list on Macs. We can't assume NTFS will be readable,
861 // so return TRUE if it's unreadable; but if it IS readable, return
862 // TRUE only if Windows boot files are found.
863 static BOOLEAN
HasWindowsBiosBootFiles(REFIT_VOLUME
*Volume
) {
864 BOOLEAN FilesFound
= TRUE
;
866 if (Volume
->RootDir
!= NULL
) {
867 FilesFound
= FileExists(Volume
->RootDir
, L
"NTLDR") || // Windows NT/200x/XP boot file
868 FileExists(Volume
->RootDir
, L
"bootmgr"); // Windows Vista/7/8 boot file
871 } // static VOID HasWindowsBiosBootFiles()
873 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
876 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
877 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
878 EFI_HANDLE WholeDiskHandle
;
883 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
885 if (Volume
->DevicePath
!= NULL
) {
886 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
888 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
893 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
896 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
897 if (EFI_ERROR(Status
)) {
898 Volume
->BlockIO
= NULL
;
899 Print(L
"Warning: Can't get BlockIO protocol.\n");
901 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
902 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
905 // scan for bootcode and MBR table
907 ScanVolumeBootcode(Volume
, &Bootable
);
909 // detect device type
910 DevicePath
= Volume
->DevicePath
;
911 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
912 NextDevicePath
= NextDevicePathNode(DevicePath
);
914 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
) {
915 SetPartGuidAndName(Volume
, DevicePath
);
917 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
918 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
919 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
920 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
921 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
922 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
923 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
924 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
925 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
929 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
930 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
931 // TODO: also check for Boot Camp GUID
932 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
935 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
936 // make a device path for the whole device
937 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
938 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
939 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
940 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
942 // get the handle for that path
943 RemainingDevicePath
= DiskDevicePath
;
944 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
945 FreePool(DiskDevicePath
);
947 if (!EFI_ERROR(Status
)) {
948 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
950 // get the device path for later
951 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
952 if (!EFI_ERROR(Status
)) {
953 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
956 // look at the BlockIO protocol
957 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
958 (VOID
**) &Volume
->WholeDiskBlockIO
);
959 if (!EFI_ERROR(Status
)) {
961 // check the media block size
962 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
963 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
966 Volume
->WholeDiskBlockIO
= NULL
;
967 //CheckError(Status, L"from HandleProtocol");
970 // CheckError(Status, L"from LocateDevicePath");
973 DevicePath
= NextDevicePath
;
978 if (Volume
->HasBootCode
)
979 Print(L
" Volume considered non-bootable, but boot code is present\n");
981 Volume
->HasBootCode
= FALSE
;
984 // open the root directory of the volume
985 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
987 // Set volume icon based on .VolumeBadge icon or disk kind
988 SetVolumeBadgeIcon(Volume
);
990 Volume
->VolName
= GetVolumeName(Volume
);
992 if (Volume
->RootDir
== NULL
) {
993 Volume
->IsReadable
= FALSE
;
996 Volume
->IsReadable
= TRUE
;
997 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
) && (Volume
->FSType
== FS_TYPE_NTFS
) && Volume
->HasBootCode
) {
998 // VBR boot code found on NTFS, but volume is not actually bootable
999 // unless there are actual boot file, so check for them....
1000 Volume
->HasBootCode
= HasWindowsBiosBootFiles(Volume
);
1004 // get custom volume icons if present
1005 if (!Volume
->VolIconImage
) {
1006 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
1010 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
1013 REFIT_VOLUME
*Volume
;
1014 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
1016 UINTN LogicalPartitionIndex
= 4;
1017 UINT8 SectorBuffer
[512];
1019 MBR_PARTITION_INFO
*EMbrTable
;
1021 ExtBase
= MbrEntry
->StartLBA
;
1023 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
1024 // read current EMBR
1025 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
1026 WholeDiskVolume
->BlockIO
,
1027 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
1028 ExtCurrent
, 512, SectorBuffer
);
1029 if (EFI_ERROR(Status
))
1031 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
1033 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
1035 // scan logical partitions in this EMBR
1037 for (i
= 0; i
< 4; i
++) {
1038 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
1039 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
1041 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
1042 // set next ExtCurrent
1043 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
1046 // found a logical partition
1047 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1048 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
1049 Volume
->IsMbrPartition
= TRUE
;
1050 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
1051 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
1052 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
1053 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
1054 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
1055 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
1058 ScanVolumeBootcode(Volume
, &Bootable
);
1060 Volume
->HasBootCode
= FALSE
;
1061 SetVolumeBadgeIcon(Volume
);
1062 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1066 } /* VOID ScanExtendedPartition() */
1068 VOID
ScanVolumes(VOID
)
1071 EFI_HANDLE
*Handles
;
1072 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
1073 MBR_PARTITION_INFO
*MbrTable
;
1074 UINTN HandleCount
= 0;
1076 UINTN VolumeIndex
, VolumeIndex2
;
1077 UINTN PartitionIndex
;
1078 UINTN SectorSum
, i
, VolNumber
= 0;
1079 UINT8
*SectorBuffer1
, *SectorBuffer2
;
1081 EFI_GUID NullUuid
= NULL_GUID_VALUE
;
1083 MyFreePool(Volumes
);
1086 ForgetPartitionTables();
1088 // get all filesystem handles
1089 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
1090 UuidList
= AllocateZeroPool(sizeof(EFI_GUID
) * HandleCount
);
1091 if (Status
== EFI_NOT_FOUND
) {
1092 return; // no filesystems. strange, but true...
1094 if (CheckError(Status
, L
"while listing all file systems"))
1097 // first pass: collect information about all handles
1098 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1099 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1100 Volume
->DeviceHandle
= Handles
[HandleIndex
];
1101 AddPartitionTable(Volume
);
1104 UuidList
[HandleIndex
] = Volume
->VolUuid
;
1105 for (i
= 0; i
< HandleIndex
; i
++) {
1106 if ((CompareMem(&(Volume
->VolUuid
), &(UuidList
[i
]), sizeof(EFI_GUID
)) == 0) &&
1107 (CompareMem(&(Volume
->VolUuid
), &NullUuid
, sizeof(EFI_GUID
)) != 0)) { // Duplicate filesystem UUID
1108 Volume
->IsReadable
= FALSE
;
1112 if (Volume
->IsReadable
)
1113 Volume
->VolNumber
= VolNumber
++;
1115 Volume
->VolNumber
= VOL_UNREADABLE
;
1117 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1119 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
1120 SelfVolume
= Volume
;
1122 MyFreePool(Handles
);
1124 if (SelfVolume
== NULL
)
1125 Print(L
"WARNING: SelfVolume not found");
1127 // second pass: relate partitions and whole disk devices
1128 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1129 Volume
= Volumes
[VolumeIndex
];
1130 // check MBR partition table for extended partitions
1131 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1132 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
1133 Volume
->MbrPartitionTable
!= NULL
) {
1134 MbrTable
= Volume
->MbrPartitionTable
;
1135 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1136 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
1137 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
1142 // search for corresponding whole disk volume entry
1143 WholeDiskVolume
= NULL
;
1144 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1145 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1146 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1147 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1148 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0) {
1149 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1154 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1155 // check if this volume is one of the partitions in the table
1156 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1157 SectorBuffer1
= AllocatePool(512);
1158 SectorBuffer2
= AllocatePool(512);
1159 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1161 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1164 // compare boot sector read through offset vs. directly
1165 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1166 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1167 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1168 if (EFI_ERROR(Status
))
1170 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1171 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1172 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1173 if (EFI_ERROR(Status
))
1175 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1178 for (i
= 0; i
< 512; i
++)
1179 SectorSum
+= SectorBuffer1
[i
];
1180 if (SectorSum
< 1000)
1183 // TODO: mark entry as non-bootable if it is an extended partition
1185 // now we're reasonably sure the association is correct...
1186 Volume
->IsMbrPartition
= TRUE
;
1187 Volume
->MbrPartitionIndex
= PartitionIndex
;
1188 if (Volume
->VolName
== NULL
) {
1189 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1190 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1195 MyFreePool(SectorBuffer1
);
1196 MyFreePool(SectorBuffer2
);
1199 } /* VOID ScanVolumes() */
1202 // file and dir functions
1205 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1208 EFI_FILE_HANDLE TestFile
;
1210 if (BaseDir
!= NULL
) {
1211 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1212 if (Status
== EFI_SUCCESS
) {
1213 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1220 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1224 UINTN LastBufferSize
, BufferSize
;
1229 // free pointer from last call
1230 if (*DirEntry
!= NULL
) {
1231 FreePool(*DirEntry
);
1235 // read next directory entry
1236 LastBufferSize
= BufferSize
= 256;
1237 Buffer
= AllocatePool(BufferSize
);
1238 for (IterCount
= 0; ; IterCount
++) {
1239 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1240 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1242 if (BufferSize
<= LastBufferSize
) {
1243 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1244 BufferSize
= LastBufferSize
* 2;
1247 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1250 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1251 LastBufferSize
= BufferSize
;
1253 if (EFI_ERROR(Status
)) {
1259 // check for end of listing
1260 if (BufferSize
== 0) { // end of directory listing
1266 // entry is ready to be returned
1267 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1270 if (FilterMode
== 1) { // only return directories
1271 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1273 } else if (FilterMode
== 2) { // only return files
1274 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1276 } else // no filter or unknown filter -> return everything
1283 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1285 if (RelativePath
== NULL
) {
1286 DirIter
->LastStatus
= EFI_SUCCESS
;
1287 DirIter
->DirHandle
= BaseDir
;
1288 DirIter
->CloseDirHandle
= FALSE
;
1290 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1291 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1293 DirIter
->LastFileInfo
= NULL
;
1296 #ifndef __MAKEWITH_GNUEFI
1297 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1300 InitializeUnicodeCollationProtocol (VOID
)
1304 if (mUnicodeCollation
!= NULL
) {
1309 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1310 // instances first and then select one which support English language.
1311 // Current implementation just pick the first instance.
1313 Status
= gBS
->LocateProtocol (
1314 &gEfiUnicodeCollation2ProtocolGuid
,
1316 (VOID
**) &mUnicodeCollation
1318 if (EFI_ERROR(Status
)) {
1319 Status
= gBS
->LocateProtocol (
1320 &gEfiUnicodeCollationProtocolGuid
,
1322 (VOID
**) &mUnicodeCollation
1330 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1332 if (!mUnicodeCollation
) {
1333 InitializeUnicodeCollationProtocol();
1335 if (mUnicodeCollation
)
1336 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1337 return FALSE
; // Shouldn't happen
1342 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1343 OUT EFI_FILE_INFO
**DirEntry
)
1345 BOOLEAN KeepGoing
= TRUE
;
1349 if (DirIter
->LastFileInfo
!= NULL
) {
1350 FreePool(DirIter
->LastFileInfo
);
1351 DirIter
->LastFileInfo
= NULL
;
1354 if (EFI_ERROR(DirIter
->LastStatus
))
1355 return FALSE
; // stop iteration
1358 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1359 if (EFI_ERROR(DirIter
->LastStatus
))
1361 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1363 if (FilePattern
!= NULL
) {
1364 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1367 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1368 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1371 // else continue loop
1374 } while (KeepGoing
&& FilePattern
);
1376 *DirEntry
= DirIter
->LastFileInfo
;
1380 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1382 if (DirIter
->LastFileInfo
!= NULL
) {
1383 FreePool(DirIter
->LastFileInfo
);
1384 DirIter
->LastFileInfo
= NULL
;
1386 if (DirIter
->CloseDirHandle
)
1387 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1388 return DirIter
->LastStatus
;
1392 // file name manipulation
1395 // Returns the filename portion (minus path name) of the
1397 CHAR16
* Basename(IN CHAR16
*Path
)
1405 for (i
= StrLen(Path
); i
> 0; i
--) {
1406 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1407 FileName
= Path
+ i
;
1416 // Remove the .efi extension from FileName -- for instance, if FileName is
1417 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1418 // returns a copy of the original input.
1419 CHAR16
* StripEfiExtension(IN CHAR16
*FileName
) {
1421 CHAR16
*Copy
= NULL
;
1423 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1424 Length
= StrLen(Copy
);
1425 if ((Length
>= 4) && MyStriCmp(&Copy
[Length
- 4], L
".efi")) {
1426 Copy
[Length
- 4] = 0;
1430 } // CHAR16 * StripExtension()
1433 // memory string search
1436 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1442 BufferLength
-= SearchStringLength
;
1443 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1444 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1445 return (INTN
)Offset
;
1451 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1452 BOOLEAN Found
= 0, Terminate
= 0;
1453 UINTN BigIndex
= 0, SmallIndex
= 0, BigStart
= 0;
1455 if (SmallStr
&& BigStr
) {
1456 while (!Terminate
) {
1457 if (BigStr
[BigIndex
] == '\0') {
1460 if (SmallStr
[SmallIndex
] == '\0') {
1464 if ((SmallStr
[SmallIndex
] & ~0x20) == (BigStr
[BigIndex
] & ~0x20)) {
1470 BigIndex
= BigStart
;
1475 } // BOOLEAN StriSubCmp()
1477 // Performs a case-insensitive string comparison. This function is necesary
1478 // because some EFIs have buggy StriCmp() functions that actually perform
1479 // case-sensitive comparisons.
1480 // Returns TRUE if strings are identical, FALSE otherwise.
1481 BOOLEAN
MyStriCmp(IN CONST CHAR16
*FirstString
, IN CONST CHAR16
*SecondString
) {
1482 if (FirstString
&& SecondString
) {
1483 while ((*FirstString
!= L
'\0') && ((*FirstString
& ~0x20) == (*SecondString
& ~0x20))) {
1487 return (*FirstString
== *SecondString
);
1491 } // BOOLEAN MyStriCmp()
1493 // Convert input string to all-lowercase.
1494 // DO NOT USE the standard StrLwr() function, since it's broken on some EFIs!
1495 VOID
ToLower(CHAR16
* MyString
) {
1499 while (MyString
[i
] != L
'\0') {
1500 if ((MyString
[i
] >= L
'A') && (MyString
[i
] <= L
'Z'))
1501 MyString
[i
] = MyString
[i
] - L
'A' + L
'a';
1507 // Merges two strings, creating a new one and returning a pointer to it.
1508 // If AddChar != 0, the specified character is placed between the two original
1509 // strings (unless the first string is NULL or empty). The original input
1510 // string *First is de-allocated and replaced by the new merged string.
1511 // This is similar to StrCat, but safer and more flexible because
1512 // MergeStrings allocates memory that's the correct size for the
1513 // new merged string, so it can take a NULL *First and it cleans
1514 // up the old memory. It should *NOT* be used with a constant
1515 // *First, though....
1516 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1517 UINTN Length1
= 0, Length2
= 0;
1521 Length1
= StrLen(*First
);
1523 Length2
= StrLen(Second
);
1524 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1525 if (NewString
!= NULL
) {
1526 if ((*First
!= NULL
) && (Length1
== 0)) {
1530 NewString
[0] = L
'\0';
1531 if (*First
!= NULL
) {
1532 StrCat(NewString
, *First
);
1534 NewString
[Length1
] = AddChar
;
1535 NewString
[Length1
+ 1] = '\0';
1537 } // if (*First != NULL)
1539 StrCat(NewString
, Second
);
1543 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1545 } // VOID MergeStrings()
1547 // Similar to MergeStrings, but breaks the input string into word chunks and
1548 // merges each word separately. Words are defined as string fragments separated
1549 // by ' ', '_', or '-'.
1550 VOID
MergeWords(CHAR16
**MergeTo
, CHAR16
*SourceString
, CHAR16 AddChar
) {
1551 CHAR16
*Temp
, *Word
, *p
;
1552 BOOLEAN LineFinished
= FALSE
;
1555 Temp
= Word
= p
= StrDuplicate(SourceString
);
1557 while (!LineFinished
) {
1558 if ((*p
== L
' ') || (*p
== L
'_') || (*p
== L
'-') || (*p
== L
'\0')) {
1560 LineFinished
= TRUE
;
1563 MergeStrings(MergeTo
, Word
, AddChar
);
1570 Print(L
"Error! Unable to allocate memory in MergeWords()!\n");
1573 } // VOID MergeWords()
1575 // Takes an input pathname (*Path) and returns the part of the filename from
1576 // the final dot onwards, converted to lowercase. If the filename includes
1577 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1578 // The calling function is responsible for freeing the memory associated with
1579 // the return value.
1580 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1582 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1585 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1588 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1589 if (Path
[i
] == L
'.')
1591 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1597 MergeStrings(&Extension
, &Path
[i
], 0);
1602 } // CHAR16 *FindExtension()
1604 // Takes an input pathname (*Path) and locates the final directory component
1605 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1606 // function returns the string 'foo'.
1607 // Assumes the pathname is separated with backslashes.
1608 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1609 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1610 CHAR16
*Found
= NULL
;
1615 PathLength
= StrLen(Path
);
1616 // Find start & end of target element
1617 for (i
= 0; i
< PathLength
; i
++) {
1618 if (Path
[i
] == '\\') {
1619 StartOfElement
= EndOfElement
;
1623 // Extract the target element
1624 if (EndOfElement
> 0) {
1625 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1629 if (EndOfElement
>= StartOfElement
) {
1630 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1631 Found
= StrDuplicate(&Path
[StartOfElement
]);
1633 Found
[CopyLength
] = 0;
1634 } // if (EndOfElement >= StartOfElement)
1635 } // if (EndOfElement > 0)
1637 } // CHAR16 *FindLastDirName()
1639 // Returns the directory portion of a pathname. For instance,
1640 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1641 // string 'EFI\foo'. The calling function is responsible for
1642 // freeing the returned string's memory.
1643 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1644 UINTN i
, LastBackslash
= 0;
1645 CHAR16
*PathOnly
= NULL
;
1647 if (FullPath
!= NULL
) {
1648 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1649 if (FullPath
[i
] == '\\')
1652 PathOnly
= StrDuplicate(FullPath
);
1653 if (PathOnly
!= NULL
)
1654 PathOnly
[LastBackslash
] = 0;
1661 * Routine Description:
1667 * String - Null-terminated string to search.
1668 * StrCharSet - Null-terminated string to search for.
1671 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1673 CHAR16
* MyStrStr (IN CHAR16
*String
, IN CHAR16
*StrCharSet
)
1678 if ((String
== NULL
) || (StrCharSet
== NULL
))
1684 while ((*String
!= L
'\0') && (*StrCharSet
!= L
'\0')) {
1685 if (*String
++ != *StrCharSet
) {
1692 if (*StrCharSet
== L
'\0') {
1697 } // CHAR16 *MyStrStr()
1699 // Restrict TheString to at most Limit characters.
1700 // Does this in two ways:
1701 // - Locates stretches of two or more spaces and compresses
1702 // them down to one space.
1703 // - Truncates TheString
1704 // Returns TRUE if changes were made, FALSE otherwise
1705 BOOLEAN
LimitStringLength(CHAR16
*TheString
, UINTN Limit
) {
1706 CHAR16
*SubString
, *TempString
;
1708 BOOLEAN HasChanged
= FALSE
;
1710 // SubString will be NULL or point WITHIN TheString
1711 SubString
= MyStrStr(TheString
, L
" ");
1712 while (SubString
!= NULL
) {
1714 while (SubString
[i
] == L
' ')
1716 if (i
>= StrLen(SubString
)) {
1717 SubString
[0] = '\0';
1720 TempString
= StrDuplicate(&SubString
[i
]);
1721 if (TempString
!= NULL
) {
1722 StrCpy(&SubString
[1], TempString
);
1723 MyFreePool(TempString
);
1726 // memory allocation problem; abort to avoid potentially infinite loop!
1730 SubString
= MyStrStr(TheString
, L
" ");
1733 // If the string is still too long, truncate it....
1734 if (StrLen(TheString
) > Limit
) {
1735 TheString
[Limit
] = '\0';
1740 } // BOOLEAN LimitStringLength()
1742 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1743 // DeviceVolume, and returns that and the filename (*loader).
1744 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1745 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1747 BOOLEAN Found
= FALSE
;
1749 MyFreePool(*loader
);
1750 MyFreePool(*DeviceVolume
);
1751 *DeviceVolume
= NULL
;
1752 DeviceString
= DevicePathToStr(loadpath
);
1753 *loader
= SplitDeviceString(DeviceString
);
1755 while ((i
< VolumesCount
) && (!Found
)) {
1756 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1757 Temp
= SplitDeviceString(VolumeDeviceString
);
1758 if (MyStriCmp(DeviceString
, VolumeDeviceString
)) {
1760 *DeviceVolume
= Volumes
[i
];
1763 MyFreePool(VolumeDeviceString
);
1767 MyFreePool(DeviceString
);
1768 } // VOID FindVolumeAndFilename()
1770 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1771 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1772 // the filename component in the original *Path variable and the split-off
1773 // volume component in the *VolName variable.
1774 // Returns TRUE if both components are found, FALSE otherwise.
1775 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1776 UINTN i
= 0, Length
;
1782 if (*VolName
!= NULL
) {
1783 MyFreePool(*VolName
);
1787 Length
= StrLen(*Path
);
1788 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1793 Filename
= StrDuplicate((*Path
) + i
+ 1);
1801 } // BOOLEAN SplitVolumeAndFilename()
1803 // Returns all the digits in the input string, including intervening
1804 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1805 // this function returns "3.3.4-7". If InString contains no digits,
1806 // the return value is NULL.
1807 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1808 UINTN i
, StartOfElement
, EndOfElement
= 0, CopyLength
;
1809 CHAR16
*Found
= NULL
;
1811 if (InString
== NULL
)
1814 StartOfElement
= StrLen(InString
);
1815 // Find start & end of target element
1816 for (i
= 0; InString
[i
] != L
'\0'; i
++) {
1817 if ((InString
[i
] >= L
'0') && (InString
[i
] <= L
'9')) {
1818 if (StartOfElement
> i
)
1820 if (EndOfElement
< i
)
1824 // Extract the target element
1825 if (EndOfElement
> 0) {
1826 if (EndOfElement
>= StartOfElement
) {
1827 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1828 Found
= StrDuplicate(&InString
[StartOfElement
]);
1830 Found
[CopyLength
] = 0;
1831 } // if (EndOfElement >= StartOfElement)
1832 } // if (EndOfElement > 0)
1834 } // CHAR16 *FindNumbers()
1836 // Find the #Index element (numbered from 0) in a comma-delimited string
1838 // Returns the found element, or NULL if Index is out of range or InString
1839 // is NULL. Note that the calling function is responsible for freeing the
1840 // memory associated with the returned string pointer.
1841 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1842 UINTN StartPos
= 0, CurPos
= 0, InLength
;
1843 BOOLEAN Found
= FALSE
;
1844 CHAR16
*FoundString
= NULL
;
1846 if (InString
!= NULL
) {
1847 InLength
= StrLen(InString
);
1848 // After while() loop, StartPos marks start of item #Index
1849 while ((Index
> 0) && (CurPos
< InLength
)) {
1850 if (InString
[CurPos
] == L
',') {
1852 StartPos
= CurPos
+ 1;
1856 // After while() loop, CurPos is one past the end of the element
1857 while ((CurPos
< InLength
) && (!Found
)) {
1858 if (InString
[CurPos
] == L
',')
1864 FoundString
= StrDuplicate(&InString
[StartPos
]);
1865 if (FoundString
!= NULL
)
1866 FoundString
[CurPos
- StartPos
] = 0;
1868 return (FoundString
);
1869 } // CHAR16 *FindCommaDelimited()
1871 // Take an input path name, which may include a volume specification and/or
1872 // a path, and return separate volume, path, and file names. For instance,
1873 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1874 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1875 // the returned pointer is NULL. The calling function is responsible for
1876 // freeing the allocated memory.
1877 VOID
SplitPathName(CHAR16
*InPath
, CHAR16
**VolName
, CHAR16
**Path
, CHAR16
**Filename
) {
1878 CHAR16
*Temp
= NULL
;
1880 MyFreePool(*VolName
);
1882 MyFreePool(*Filename
);
1883 *VolName
= *Path
= *Filename
= NULL
;
1884 Temp
= StrDuplicate(InPath
);
1885 SplitVolumeAndFilename(&Temp
, VolName
); // VolName is NULL or has volume; Temp has rest of path
1886 CleanUpPathNameSlashes(Temp
);
1887 *Path
= FindPath(Temp
); // *Path has path (may be 0-length); Temp unchanged.
1888 *Filename
= StrDuplicate(Temp
+ StrLen(*Path
));
1889 CleanUpPathNameSlashes(*Filename
);
1890 if (StrLen(*Path
) == 0) {
1894 if (StrLen(*Filename
) == 0) {
1895 MyFreePool(*Filename
);
1899 } // VOID SplitPathName
1901 // Returns TRUE if SmallString is an element in the comma-delimited List,
1902 // FALSE otherwise. Performs comparison case-insensitively.
1903 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1905 BOOLEAN Found
= FALSE
;
1908 if (SmallString
&& List
) {
1909 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1910 if (MyStriCmp(OneElement
, SmallString
))
1917 // Returns TRUE if any element of List can be found as a substring of
1918 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1919 BOOLEAN
IsInSubstring(IN CHAR16
*BigString
, IN CHAR16
*List
) {
1920 UINTN i
= 0, ElementLength
;
1921 BOOLEAN Found
= FALSE
;
1924 if (BigString
&& List
) {
1925 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1926 ElementLength
= StrLen(OneElement
);
1927 if ((ElementLength
<= StrLen(BigString
)) && (StriSubCmp(OneElement
, BigString
)))
1932 } // BOOLEAN IsSubstringIn()
1934 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1935 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1936 // Filename must *NOT* include a volume or path specification (that's part of
1937 // the Volume variable), but the List elements may. Performs comparison
1938 // case-insensitively.
1939 BOOLEAN
FilenameIn(REFIT_VOLUME
*Volume
, CHAR16
*Directory
, CHAR16
*Filename
, CHAR16
*List
) {
1941 BOOLEAN Found
= FALSE
;
1943 CHAR16
*TargetVolName
= NULL
, *TargetPath
= NULL
, *TargetFilename
= NULL
;
1945 if (Filename
&& List
) {
1946 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1948 SplitPathName(OneElement
, &TargetVolName
, &TargetPath
, &TargetFilename
);
1949 VolumeNumberToName(Volume
, &TargetVolName
);
1950 if (((TargetVolName
!= NULL
) && ((Volume
== NULL
) || (!MyStriCmp(TargetVolName
, Volume
->VolName
)))) ||
1951 ((TargetPath
!= NULL
) && (!MyStriCmp(TargetPath
, Directory
))) ||
1952 ((TargetFilename
!= NULL
) && (!MyStriCmp(TargetFilename
, Filename
)))) {
1955 MyFreePool(OneElement
);
1959 MyFreePool(TargetVolName
);
1960 MyFreePool(TargetPath
);
1961 MyFreePool(TargetFilename
);
1963 } // BOOLEAN FilenameIn()
1965 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1966 // to this volume number, returns with *VolName changed to the volume name, as
1967 // stored in the Volume data structure.
1968 // Returns TRUE if this substitution was made, FALSE otherwise.
1969 BOOLEAN
VolumeNumberToName(REFIT_VOLUME
*Volume
, CHAR16
**VolName
) {
1970 BOOLEAN MadeSubstitution
= FALSE
;
1973 if ((VolName
== NULL
) || (*VolName
== NULL
))
1976 if ((StrLen(*VolName
) > 2) && (*VolName
[0] == L
'f') && (*VolName
[1] == L
's') && (*VolName
[2] >= L
'0') && (*VolName
[2] <= L
'9')) {
1977 VolNum
= Atoi(*VolName
+ 2);
1978 if (VolNum
== Volume
->VolNumber
) {
1979 MyFreePool(*VolName
);
1980 *VolName
= StrDuplicate(Volume
->VolName
);
1981 MadeSubstitution
= TRUE
;
1984 return MadeSubstitution
;
1985 } // BOOLEAN VolumeMatchesNumber()
1987 // Implement FreePool the way it should have been done to begin with, so that
1988 // it doesn't throw an ASSERT message if fed a NULL pointer....
1989 VOID
MyFreePool(IN VOID
*Pointer
) {
1990 if (Pointer
!= NULL
)
1994 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1996 // Eject all removable media.
1997 // Returns TRUE if any media were ejected, FALSE otherwise.
1998 BOOLEAN
EjectMedia(VOID
) {
2000 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
2001 EFI_HANDLE
*Handles
, Handle
;
2002 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
2004 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
2005 if (EFI_ERROR(Status
) || HandleCount
== 0)
2006 return (FALSE
); // probably not an Apple system
2008 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
2009 Handle
= Handles
[HandleIndex
];
2010 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
2011 if (EFI_ERROR(Status
))
2013 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
2014 if (!EFI_ERROR(Status
))
2017 MyFreePool(Handles
);
2018 return (Ejected
> 0);
2019 } // VOID EjectMedia()
2021 // Converts consecutive characters in the input string into a
2022 // number, interpreting the string as a hexadecimal number, starting
2023 // at the specified position and continuing for the specified number
2024 // of characters or until the end of the string, whichever is first.
2025 // NumChars must be between 1 and 16. Ignores invalid characters.
2026 UINT64
StrToHex(CHAR16
*Input
, UINTN Pos
, UINTN NumChars
) {
2027 UINT64 retval
= 0x00;
2028 UINTN NumDone
= 0, InputLength
;
2031 if ((Input
== NULL
) || (NumChars
== 0) || (NumChars
> 16)) {
2035 InputLength
= StrLen(Input
);
2036 while ((Pos
<= InputLength
) && (NumDone
< NumChars
)) {
2038 if ((a
>= '0') && (a
<= '9')) {
2040 retval
+= (a
- '0');
2043 if ((a
>= 'a') && (a
<= 'f')) {
2045 retval
+= (a
- 'a' + 0x0a);
2048 if ((a
>= 'A') && (a
<= 'F')) {
2050 retval
+= (a
- 'A' + 0x0a);
2058 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2059 // Note that the input string must have no extraneous spaces and must be
2060 // conventionally formatted as a 36-character GUID, complete with dashes in
2061 // appropriate places.
2062 BOOLEAN
IsGuid(CHAR16
*UnknownString
) {
2064 BOOLEAN retval
= TRUE
;
2067 if (UnknownString
== NULL
)
2070 Length
= StrLen(UnknownString
);
2074 for (i
= 0; i
< Length
; i
++) {
2075 a
= UnknownString
[i
];
2076 if ((i
== 8) || (i
== 13) || (i
== 18) || (i
== 23)) {
2079 } else if (((a
< L
'a') || (a
> L
'f')) &&
2080 ((a
< L
'A') || (a
> L
'F')) &&
2081 ((a
< L
'0') && (a
> L
'9'))) {
2086 } // BOOLEAN IsGuid()
2088 // Return the GUID as a string, suitable for display to the user. Note that the calling
2089 // function is responsible for freeing the allocated memory.
2090 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
2093 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
2094 if (TheString
!= 0) {
2095 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2096 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
2097 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
2098 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
2099 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
2102 } // GuidAsString(EFI_GUID *GuidData)
2104 EFI_GUID
StringAsGuid(CHAR16
* InString
) {
2105 EFI_GUID Guid
= NULL_GUID_VALUE
;
2107 if (!IsGuid(InString
)) {
2111 Guid
.Data1
= (UINT32
) StrToHex(InString
, 0, 8);
2112 Guid
.Data2
= (UINT16
) StrToHex(InString
, 9, 4);
2113 Guid
.Data3
= (UINT16
) StrToHex(InString
, 14, 4);
2114 Guid
.Data4
[0] = (UINT8
) StrToHex(InString
, 19, 2);
2115 Guid
.Data4
[1] = (UINT8
) StrToHex(InString
, 21, 2);
2116 Guid
.Data4
[2] = (UINT8
) StrToHex(InString
, 23, 2);
2117 Guid
.Data4
[3] = (UINT8
) StrToHex(InString
, 26, 2);
2118 Guid
.Data4
[4] = (UINT8
) StrToHex(InString
, 28, 2);
2119 Guid
.Data4
[5] = (UINT8
) StrToHex(InString
, 30, 2);
2120 Guid
.Data4
[6] = (UINT8
) StrToHex(InString
, 32, 2);
2121 Guid
.Data4
[7] = (UINT8
) StrToHex(InString
, 34, 2);
2124 } // EFI_GUID StringAsGuid()
2126 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2127 BOOLEAN
GuidsAreEqual(EFI_GUID
*Guid1
, EFI_GUID
*Guid2
) {
2128 return (CompareMem(Guid1
, Guid2
, 16) == 0);
2129 } // BOOLEAN GuidsAreEqual()