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-2014 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"
51 //#include "../include/UsbMass.h"
53 #ifdef __MAKEWITH_GNUEFI
54 #define EfiReallocatePool ReallocatePool
56 #define LibLocateHandle gBS->LocateHandleBuffer
57 #define DevicePathProtocol gEfiDevicePathProtocolGuid
58 #define BlockIoProtocol gEfiBlockIoProtocolGuid
59 #define LibFileSystemInfo EfiLibFileSystemInfo
60 #define LibOpenRoot EfiLibOpenRoot
61 EFI_DEVICE_PATH EndDevicePath
[] = {
62 {END_DEVICE_PATH_TYPE
, END_ENTIRE_DEVICE_PATH_SUBTYPE
, {END_DEVICE_PATH_LENGTH
, 0}}
65 //#define EndDevicePath DevicePath
68 // "Magic" signatures for various filesystems
69 #define FAT_MAGIC 0xAA55
70 #define EXT2_SUPER_MAGIC 0xEF53
71 #define HFSPLUS_MAGIC1 0x2B48
72 #define HFSPLUS_MAGIC2 0x5848
73 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
74 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
75 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
76 #define BTRFS_SIGNATURE "_BHRfS_M"
80 EFI_HANDLE SelfImageHandle
;
81 EFI_LOADED_IMAGE
*SelfLoadedImage
;
82 EFI_FILE
*SelfRootDir
;
86 REFIT_VOLUME
*SelfVolume
= NULL
;
87 REFIT_VOLUME
**Volumes
= NULL
;
88 UINTN VolumesCount
= 0;
90 // Maximum size for disk sectors
91 #define SECTOR_SIZE 4096
93 // Number of bytes to read from a partition to determine its filesystem type
94 // and identify its boot loader, and hence probable BIOS-mode OS installation
95 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
100 static EFI_STATUS
FinishInitRefitLib(VOID
);
102 static VOID
UninitVolumes(VOID
);
105 // self recognition stuff
108 // Converts forward slashes to backslashes, removes duplicate slashes, and
109 // removes slashes from both the start and end of the pathname.
110 // Necessary because some (buggy?) EFI implementations produce "\/" strings
111 // in pathnames, because some user inputs can produce duplicate directory
112 // separators, and because we want consistent start and end slashes for
113 // directory comparisons. A special case: If the PathName refers to root,
114 // return "/", since some firmware implementations flake out if this
116 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
118 UINTN i
, Length
, FinalChar
= 0;
119 BOOLEAN LastWasSlash
= FALSE
;
121 Length
= StrLen(PathName
);
122 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (Length
+ 2));
123 if (NewName
!= NULL
) {
124 for (i
= 0; i
< StrLen(PathName
); i
++) {
125 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
126 if ((!LastWasSlash
) && (FinalChar
!= 0))
127 NewName
[FinalChar
++] = L
'\\';
130 NewName
[FinalChar
++] = PathName
[i
];
131 LastWasSlash
= FALSE
;
134 NewName
[FinalChar
] = 0;
135 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
136 NewName
[--FinalChar
] = 0;
137 if (FinalChar
== 0) {
141 // Copy the transformed name back....
142 StrCpy(PathName
, NewName
);
144 } // if allocation OK
145 } // CleanUpPathNameSlashes()
147 // Splits an EFI device path into device and filename components. For instance, if InString is
148 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
149 // this function will truncate that input to
150 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
151 // and return bzImage-3.5.1.efi as its return value.
152 // It does this by searching for the last ")" character in InString, copying everything
153 // after that string (after some cleanup) as the return value, and truncating the original
155 // If InString contains no ")" character, this function leaves the original input string
156 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
157 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
159 CHAR16
*FileName
= NULL
;
160 BOOLEAN Found
= FALSE
;
162 if (InString
!= NULL
) {
163 i
= StrLen(InString
) - 1;
164 while ((i
>= 0) && (!Found
)) {
165 if (InString
[i
] == L
')') {
167 FileName
= StrDuplicate(&InString
[i
+ 1]);
168 CleanUpPathNameSlashes(FileName
);
169 InString
[i
+ 1] = '\0';
173 if (FileName
== NULL
)
174 FileName
= StrDuplicate(InString
);
177 } // static CHAR16* SplitDeviceString()
179 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
182 CHAR16
*DevicePathAsString
, *Temp
;
184 SelfImageHandle
= ImageHandle
;
185 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
186 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
187 return EFI_LOAD_ERROR
;
189 // find the current directory
190 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
191 CleanUpPathNameSlashes(DevicePathAsString
);
192 MyFreePool(SelfDirPath
);
193 Temp
= FindPath(DevicePathAsString
);
194 SelfDirPath
= SplitDeviceString(Temp
);
195 MyFreePool(DevicePathAsString
);
198 return FinishInitRefitLib();
201 // called before running external programs to close open file handles
202 VOID
UninitRefitLib(VOID
)
204 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
205 // See the comment on it there.
206 if(SelfRootDir
== SelfVolume
->RootDir
)
211 if (SelfDir
!= NULL
) {
212 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
216 if (SelfRootDir
!= NULL
) {
217 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
222 // called after running external programs to re-open file handles
223 EFI_STATUS
ReinitRefitLib(VOID
)
227 if ((ST
->Hdr
.Revision
>> 16) == 1) {
228 // Below two lines were in rEFIt, but seem to cause system crashes or
229 // reboots when launching OSes after returning from programs on most
230 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
231 // installation volume" (see the next function) when returning from
232 // programs when these two lines are removed, and it often crashes
233 // when returning from a program or when launching a second program
234 // with these lines removed. Therefore, the preceding if() statement
235 // executes these lines only on EFIs with a major version number of 1
236 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
237 // of hardware on which to test is limited, though, so this may be the
238 // wrong test, or there may be a better way to fix this problem.
239 // TODO: Figure out cause of above weirdness and fix it more
241 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
242 SelfRootDir
= SelfVolume
->RootDir
;
245 return FinishInitRefitLib();
248 static EFI_STATUS
FinishInitRefitLib(VOID
)
252 if (SelfRootDir
== NULL
) {
253 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
254 if (SelfRootDir
== NULL
) {
255 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
256 return EFI_LOAD_ERROR
;
260 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
261 if (CheckFatalError(Status
, L
"while opening our installation directory"))
262 return EFI_LOAD_ERROR
;
271 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
275 *ElementCount
= InitialElementCount
;
276 if (*ElementCount
> 0) {
277 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
278 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
284 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
288 if ((*ElementCount
& 7) == 0) {
289 AllocateCount
= *ElementCount
+ 8;
290 if (*ElementCount
== 0)
291 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
293 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
295 (*ListPtr
)[*ElementCount
] = NewElement
;
297 } /* VOID AddListElement() */
299 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
303 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
304 for (i
= 0; i
< *ElementCount
; i
++) {
305 // TODO: call a user-provided routine for each element here
306 MyFreePool((*ListPtr
)[i
]);
308 MyFreePool(*ListPtr
);
313 // firmware device path discovery
316 static UINT8 LegacyLoaderMediaPathData
[] = {
317 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
318 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
319 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
321 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
323 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
326 UINTN HandleCount
= 0;
327 UINTN HandleIndex
, HardcodedIndex
;
332 EFI_LOADED_IMAGE
*LoadedImage
;
333 EFI_DEVICE_PATH
*DevicePath
;
336 MaxPaths
--; // leave space for the terminating NULL pointer
338 // get all LoadedImage handles
339 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
340 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
341 if (HardcodedPathList
) {
342 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
343 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
345 PathList
[PathCount
] = NULL
;
348 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
349 Handle
= Handles
[HandleIndex
];
351 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
352 if (EFI_ERROR(Status
))
353 continue; // This can only happen if the firmware scewed up, ignore it.
355 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
356 if (EFI_ERROR(Status
))
357 continue; // This happens, ignore it.
359 // Only grab memory range nodes
360 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
363 // Check if we have this device path in the list already
364 // WARNING: This assumes the first node in the device path is unique!
366 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
367 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
369 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
377 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
381 if (HardcodedPathList
) {
382 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
383 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
385 PathList
[PathCount
] = NULL
;
392 // Return a pointer to a string containing a filesystem type name. If the
393 // filesystem type is unknown, a blank (but non-null) string is returned.
394 // The returned variable is a constant that should NOT be freed.
395 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
396 CHAR16
*retval
= NULL
;
402 case FS_TYPE_HFSPLUS
:
414 case FS_TYPE_REISERFS
:
415 retval
= L
" ReiserFS";
420 case FS_TYPE_ISO9660
:
421 retval
= L
" ISO-9660";
428 } // CHAR16 *FSTypeName()
430 // Identify the filesystem type and record the filesystem's UUID/serial number,
431 // if possible. Expects a Buffer containing the first few (normally 4096) bytes
432 // of the filesystem. Sets the filesystem type code in Volume->FSType and the
433 // UUID/serial number in Volume->VolUuid. Note that the UUID value is recognized
434 // differently for each filesystem, and is currently supported only for
435 // ext2/3/4fs and ReiserFS. If the UUID can't be determined, it's set to 0. Also, the UUID
436 // is just read directly into memory; it is *NOT* valid when displayed by
437 // GuidAsString() or used in other GUID/UUID-manipulating functions. (As I
438 // write, it's being used merely to detect partitions that are part of a
440 static VOID
SetFilesystemData(IN UINT8
*Buffer
, IN UINTN BufferSize
, IN OUT REFIT_VOLUME
*Volume
) {
441 UINT32
*Ext2Incompat
, *Ext2Compat
;
445 if ((Buffer
!= NULL
) && (Volume
!= NULL
)) {
446 SetMem(&(Volume
->VolUuid
), sizeof(EFI_GUID
), 0);
447 Volume
->FSType
= FS_TYPE_UNKNOWN
;
449 if (BufferSize
>= 512) {
450 Magic16
= (UINT16
*) (Buffer
+ 510);
451 if (*Magic16
== FAT_MAGIC
) {
452 Volume
->FSType
= FS_TYPE_FAT
;
455 } // search for FAT magic
457 if (BufferSize
>= (1024 + 100)) {
458 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
459 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
460 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
461 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
462 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
463 Volume
->FSType
= FS_TYPE_EXT4
;
464 } else if (*Ext2Compat
& 0x0004) { // check for journal
465 Volume
->FSType
= FS_TYPE_EXT3
;
466 } else { // none of these features; presume it's ext2...
467 Volume
->FSType
= FS_TYPE_EXT2
;
469 CopyMem(&(Volume
->VolUuid
), Buffer
+ 1024 + 104, sizeof(EFI_GUID
));
472 } // search for ext2/3/4 magic
474 if (BufferSize
>= (65536 + 100)) {
475 MagicString
= (char*) (Buffer
+ 65536 + 52);
476 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
477 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
478 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
479 Volume
->FSType
= FS_TYPE_REISERFS
;
480 CopyMem(&(Volume
->VolUuid
), Buffer
+ 65536 + 84, sizeof(EFI_GUID
));
483 } // search for ReiserFS magic
485 if (BufferSize
>= (65536 + 64 + 8)) {
486 MagicString
= (char*) (Buffer
+ 65536 + 64);
487 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0) {
488 Volume
->FSType
= FS_TYPE_BTRFS
;
491 } // search for Btrfs magic
493 if (BufferSize
>= (1024 + 2)) {
494 Magic16
= (UINT16
*) (Buffer
+ 1024);
495 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
496 Volume
->FSType
= FS_TYPE_HFSPLUS
;
499 } // search for HFS+ magic
500 } // if (Buffer != NULL)
502 } // UINT32 SetFilesystemData()
504 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
507 UINT8 Buffer
[SAMPLE_SIZE
];
509 MBR_PARTITION_INFO
*MbrTable
;
510 BOOLEAN MbrTableFound
= FALSE
;
512 Volume
->HasBootCode
= FALSE
;
513 Volume
->OSIconName
= NULL
;
514 Volume
->OSName
= NULL
;
517 if (Volume
->BlockIO
== NULL
)
519 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
520 return; // our buffer is too small...
522 // look at the boot sector (this is used for both hard disks and El Torito images!)
523 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
524 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
525 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
526 if (!EFI_ERROR(Status
)) {
528 SetFilesystemData(Buffer
, SAMPLE_SIZE
, Volume
);
529 if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) && (FindMem(Buffer
, 512, "EXFAT", 5) == -1)) {
531 Volume
->HasBootCode
= TRUE
;
534 // detect specific boot codes
535 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
536 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
537 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
538 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
539 Volume
->HasBootCode
= TRUE
;
540 Volume
->OSIconName
= L
"linux";
541 Volume
->OSName
= L
"Linux";
543 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
544 Volume
->HasBootCode
= TRUE
;
545 Volume
->OSIconName
= L
"grub,linux";
546 Volume
->OSName
= L
"Linux";
548 // // Below doesn't produce a bootable entry, so commented out for the moment....
549 // // GRUB in BIOS boot partition:
550 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
551 // Volume->HasBootCode = TRUE;
552 // Volume->OSIconName = L"grub,linux";
553 // Volume->OSName = L"Linux";
554 // Volume->VolName = L"BIOS Boot Partition";
557 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
558 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
559 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
560 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
561 Volume
->HasBootCode
= TRUE
;
562 Volume
->OSIconName
= L
"freebsd";
563 Volume
->OSName
= L
"FreeBSD";
565 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
566 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
567 Volume
->HasBootCode
= TRUE
;
568 Volume
->OSIconName
= L
"openbsd";
569 Volume
->OSName
= L
"OpenBSD";
571 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
572 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
573 Volume
->HasBootCode
= TRUE
;
574 Volume
->OSIconName
= L
"netbsd";
575 Volume
->OSName
= L
"NetBSD";
577 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
578 Volume
->HasBootCode
= TRUE
;
579 Volume
->OSIconName
= L
"win";
580 Volume
->OSName
= L
"Windows";
582 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
583 Volume
->HasBootCode
= TRUE
;
584 Volume
->OSIconName
= L
"winvista,win";
585 Volume
->OSName
= L
"Windows";
587 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
588 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
589 Volume
->HasBootCode
= TRUE
;
590 Volume
->OSIconName
= L
"freedos";
591 Volume
->OSName
= L
"FreeDOS";
593 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
594 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
595 Volume
->HasBootCode
= TRUE
;
596 Volume
->OSIconName
= L
"ecomstation";
597 Volume
->OSName
= L
"eComStation";
599 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
600 Volume
->HasBootCode
= TRUE
;
601 Volume
->OSIconName
= L
"beos";
602 Volume
->OSName
= L
"BeOS";
604 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
605 Volume
->HasBootCode
= TRUE
;
606 Volume
->OSIconName
= L
"zeta,beos";
607 Volume
->OSName
= L
"ZETA";
609 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
610 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
611 Volume
->HasBootCode
= TRUE
;
612 Volume
->OSIconName
= L
"haiku,beos";
613 Volume
->OSName
= L
"Haiku";
617 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
618 // need to fix AddLegacyEntry in main.c.
621 Print(L
" Result of bootcode detection: %s %s (%s)\n",
622 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
623 Volume
->OSName
, Volume
->OSIconName
);
626 // dummy FAT boot sector (created by OS X's newfs_msdos)
627 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
628 Volume
->HasBootCode
= FALSE
;
630 // dummy FAT boot sector (created by Linux's mkdosfs)
631 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
632 Volume
->HasBootCode
= FALSE
;
634 // dummy FAT boot sector (created by Windows)
635 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
636 Volume
->HasBootCode
= FALSE
;
638 // dummy FAT boot sector (created by iPartition)
639 if ((FindMem(Buffer
, 512, "Medienfehler", 12) >= 0) &&
640 (FindMem(Buffer
, 512, "Neustart: Taste dr\x81" "ken", 22) >= 0))
641 Volume
->HasBootCode
= FALSE
;
643 // check for MBR partition table
644 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
645 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
646 for (i
= 0; i
< 4; i
++)
647 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
648 MbrTableFound
= TRUE
;
649 for (i
= 0; i
< 4; i
++)
650 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
651 MbrTableFound
= FALSE
;
653 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
654 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
660 CheckError(Status
, L
"while reading boot sector");
663 } /* VOID ScanVolumeBootcode() */
665 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
666 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
668 if (Volume
->VolBadgeImage
== NULL
) {
669 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", GlobalConfig
.IconSizes
[ICON_SIZE_BADGE
]);
672 if (Volume
->VolBadgeImage
== NULL
) {
673 switch (Volume
->DiskKind
) {
674 case DISK_KIND_INTERNAL
:
675 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
677 case DISK_KIND_EXTERNAL
:
678 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
680 case DISK_KIND_OPTICAL
:
681 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
685 } // VOID SetVolumeBadgeIcon()
687 // Return a string representing the input size in IEEE-1541 units.
688 // The calling function is responsible for freeing the allocated memory.
689 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
691 UINTN Index
= 0, NumPrefixes
;
692 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
695 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
696 if (TheValue
!= NULL
) {
697 NumPrefixes
= StrLen(Prefixes
);
698 SizeInIeee
= SizeInBytes
;
699 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
703 if (Prefixes
[Index
] == ' ') {
704 Units
= StrDuplicate(L
"-byte");
706 Units
= StrDuplicate(L
" iB");
707 Units
[1] = Prefixes
[Index
];
709 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
712 } // CHAR16 *SizeInSIUnits()
714 // Return a name for the volume. Ideally this should be the label for the
715 // filesystem it contains, but this function falls back to describing the
716 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
717 // this information can be extracted.
718 // The calling function is responsible for freeing the memory allocated
719 // for the name string.
720 static CHAR16
*GetVolumeName(IN REFIT_VOLUME
*Volume
) {
721 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
722 CHAR16
*FoundName
= NULL
;
723 CHAR16
*SISize
, *TypeName
;
725 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
726 if (FileSystemInfoPtr
!= NULL
) { // we have filesystem information (size, label)....
727 if ((FileSystemInfoPtr
->VolumeLabel
!= NULL
) && (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
728 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
731 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
732 // this so that we can build a new name that includes the size....
733 if ((FoundName
!= NULL
) && (StrCmp(FoundName
, L
"HFS+ volume") == 0) && (Volume
->FSType
== FS_TYPE_HFSPLUS
)) {
734 MyFreePool(FoundName
);
736 } // if rEFInd HFS+ driver suspected
738 if (FoundName
== NULL
) { // filesystem has no name, so use fs type and size
739 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
740 if (FoundName
!= NULL
) {
741 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
742 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
744 } // if allocated memory OK
745 } // if (FoundName == NULL)
747 FreePool(FileSystemInfoPtr
);
749 } else { // fs driver not returning info; fall back on our own information....
750 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
751 if (FoundName
!= NULL
) {
752 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
753 if (StrLen(TypeName
) > 0)
754 SPrint(FoundName
, 255, L
"%s volume", TypeName
);
756 SPrint(FoundName
, 255, L
"unknown volume");
757 } // if allocated memory OK
760 // TODO: Above could be improved/extended, in case filesystem name is not found,
762 // - use partition label
763 // - use or add disk/partition number (e.g., "(hd0,2)")
765 // Desperate fallback name....
766 if (FoundName
== NULL
) {
767 FoundName
= StrDuplicate(L
"unknown volume");
770 } // static CHAR16 *GetVolumeName()
772 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
775 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
776 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
777 EFI_HANDLE WholeDiskHandle
;
782 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
784 if (Volume
->DevicePath
!= NULL
) {
785 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
787 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
792 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
795 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
796 if (EFI_ERROR(Status
)) {
797 Volume
->BlockIO
= NULL
;
798 Print(L
"Warning: Can't get BlockIO protocol.\n");
800 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
801 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
804 // scan for bootcode and MBR table
806 ScanVolumeBootcode(Volume
, &Bootable
);
808 // detect device type
809 DevicePath
= Volume
->DevicePath
;
810 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
811 NextDevicePath
= NextDevicePathNode(DevicePath
);
813 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
814 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
815 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
816 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
817 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
818 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
819 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
820 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
821 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
825 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
826 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
827 // TODO: also check for Boot Camp GUID
828 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
831 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
832 // make a device path for the whole device
833 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
834 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
835 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
836 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
838 // get the handle for that path
839 RemainingDevicePath
= DiskDevicePath
;
840 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
841 FreePool(DiskDevicePath
);
843 if (!EFI_ERROR(Status
)) {
844 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
846 // get the device path for later
847 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
848 if (!EFI_ERROR(Status
)) {
849 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
852 // look at the BlockIO protocol
853 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
854 if (!EFI_ERROR(Status
)) {
856 // check the media block size
857 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
858 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
861 Volume
->WholeDiskBlockIO
= NULL
;
862 //CheckError(Status, L"from HandleProtocol");
865 // CheckError(Status, L"from LocateDevicePath");
868 DevicePath
= NextDevicePath
;
873 if (Volume
->HasBootCode
)
874 Print(L
" Volume considered non-bootable, but boot code is present\n");
876 Volume
->HasBootCode
= FALSE
;
879 // open the root directory of the volume
880 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
882 // Set volume icon based on .VolumeBadge icon or disk kind
883 SetVolumeBadgeIcon(Volume
);
885 if (Volume
->RootDir
== NULL
) {
886 Volume
->IsReadable
= FALSE
;
889 Volume
->IsReadable
= TRUE
;
892 Volume
->VolName
= GetVolumeName(Volume
);
894 // get custom volume icons if present
895 if (!Volume
->VolIconImage
)
896 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
899 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
902 REFIT_VOLUME
*Volume
;
903 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
905 UINTN LogicalPartitionIndex
= 4;
906 UINT8 SectorBuffer
[512];
908 MBR_PARTITION_INFO
*EMbrTable
;
910 ExtBase
= MbrEntry
->StartLBA
;
912 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
914 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
915 WholeDiskVolume
->BlockIO
,
916 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
917 ExtCurrent
, 512, SectorBuffer
);
918 if (EFI_ERROR(Status
))
920 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
922 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
924 // scan logical partitions in this EMBR
926 for (i
= 0; i
< 4; i
++) {
927 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
928 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
930 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
931 // set next ExtCurrent
932 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
936 // found a logical partition
937 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
938 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
939 Volume
->IsMbrPartition
= TRUE
;
940 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
941 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
942 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
943 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
944 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
945 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
948 ScanVolumeBootcode(Volume
, &Bootable
);
950 Volume
->HasBootCode
= FALSE
;
952 SetVolumeBadgeIcon(Volume
);
954 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
959 } /* VOID ScanExtendedPartition() */
961 VOID
ScanVolumes(VOID
)
965 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
966 MBR_PARTITION_INFO
*MbrTable
;
967 UINTN HandleCount
= 0;
969 UINTN VolumeIndex
, VolumeIndex2
;
970 UINTN PartitionIndex
;
971 UINTN SectorSum
, i
, VolNumber
= 0;
972 UINT8
*SectorBuffer1
, *SectorBuffer2
;
974 EFI_GUID NullUuid
= { 00000000, 0000, 0000, {0000, 0000, 0000, 0000} };
980 // get all filesystem handles
981 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
982 UuidList
= AllocateZeroPool(sizeof(EFI_GUID
) * HandleCount
);
983 // was: &FileSystemProtocol
984 if (Status
== EFI_NOT_FOUND
) {
985 return; // no filesystems. strange, but true...
987 if (CheckError(Status
, L
"while listing all file systems"))
990 // first pass: collect information about all handles
991 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
992 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
993 Volume
->DeviceHandle
= Handles
[HandleIndex
];
996 UuidList
[HandleIndex
] = Volume
->VolUuid
;
997 for (i
= 0; i
< HandleIndex
; i
++) {
998 if ((CompareMem(&(Volume
->VolUuid
), &(UuidList
[i
]), sizeof(EFI_GUID
)) == 0) &&
999 (CompareMem(&(Volume
->VolUuid
), &NullUuid
, sizeof(EFI_GUID
)) != 0)) { // Duplicate filesystem UUID
1000 Volume
->IsReadable
= FALSE
;
1004 if (Volume
->IsReadable
)
1005 Volume
->VolNumber
= VolNumber
++;
1007 Volume
->VolNumber
= VOL_UNREADABLE
;
1009 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1011 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
1012 SelfVolume
= Volume
;
1014 MyFreePool(Handles
);
1016 if (SelfVolume
== NULL
)
1017 Print(L
"WARNING: SelfVolume not found");
1019 // second pass: relate partitions and whole disk devices
1020 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1021 Volume
= Volumes
[VolumeIndex
];
1022 // check MBR partition table for extended partitions
1023 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1024 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
1025 Volume
->MbrPartitionTable
!= NULL
) {
1026 MbrTable
= Volume
->MbrPartitionTable
;
1027 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1028 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
1029 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
1034 // search for corresponding whole disk volume entry
1035 WholeDiskVolume
= NULL
;
1036 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1037 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1038 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1039 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1040 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
1041 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1045 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1046 // check if this volume is one of the partitions in the table
1047 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1048 SectorBuffer1
= AllocatePool(512);
1049 SectorBuffer2
= AllocatePool(512);
1050 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1052 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1055 // compare boot sector read through offset vs. directly
1056 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1057 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1058 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1059 if (EFI_ERROR(Status
))
1061 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1062 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1063 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1064 if (EFI_ERROR(Status
))
1066 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1069 for (i
= 0; i
< 512; i
++)
1070 SectorSum
+= SectorBuffer1
[i
];
1071 if (SectorSum
< 1000)
1074 // TODO: mark entry as non-bootable if it is an extended partition
1076 // now we're reasonably sure the association is correct...
1077 Volume
->IsMbrPartition
= TRUE
;
1078 Volume
->MbrPartitionIndex
= PartitionIndex
;
1079 if (Volume
->VolName
== NULL
) {
1080 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1081 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1086 MyFreePool(SectorBuffer1
);
1087 MyFreePool(SectorBuffer2
);
1091 } /* VOID ScanVolumes() */
1093 static VOID
UninitVolumes(VOID
)
1095 REFIT_VOLUME
*Volume
;
1098 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1099 Volume
= Volumes
[VolumeIndex
];
1101 if (Volume
->RootDir
!= NULL
) {
1102 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
1103 Volume
->RootDir
= NULL
;
1106 Volume
->DeviceHandle
= NULL
;
1107 Volume
->BlockIO
= NULL
;
1108 Volume
->WholeDiskBlockIO
= NULL
;
1112 VOID
ReinitVolumes(VOID
)
1115 REFIT_VOLUME
*Volume
;
1117 EFI_DEVICE_PATH
*RemainingDevicePath
;
1118 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
1120 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1121 Volume
= Volumes
[VolumeIndex
];
1123 if (Volume
->DevicePath
!= NULL
) {
1124 // get the handle for that path
1125 RemainingDevicePath
= Volume
->DevicePath
;
1126 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
1128 if (!EFI_ERROR(Status
)) {
1129 Volume
->DeviceHandle
= DeviceHandle
;
1131 // get the root directory
1132 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1135 CheckError(Status
, L
"from LocateDevicePath");
1138 if (Volume
->WholeDiskDevicePath
!= NULL
) {
1139 // get the handle for that path
1140 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
1141 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
1143 if (!EFI_ERROR(Status
)) {
1144 // get the BlockIO protocol
1145 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
1146 (VOID
**) &Volume
->WholeDiskBlockIO
);
1147 if (EFI_ERROR(Status
)) {
1148 Volume
->WholeDiskBlockIO
= NULL
;
1149 CheckError(Status
, L
"from HandleProtocol");
1152 CheckError(Status
, L
"from LocateDevicePath");
1158 // file and dir functions
1161 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1164 EFI_FILE_HANDLE TestFile
;
1166 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1167 if (Status
== EFI_SUCCESS
) {
1168 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1174 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1178 UINTN LastBufferSize
, BufferSize
;
1183 // free pointer from last call
1184 if (*DirEntry
!= NULL
) {
1185 FreePool(*DirEntry
);
1189 // read next directory entry
1190 LastBufferSize
= BufferSize
= 256;
1191 Buffer
= AllocatePool(BufferSize
);
1192 for (IterCount
= 0; ; IterCount
++) {
1193 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1194 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1196 if (BufferSize
<= LastBufferSize
) {
1197 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1198 BufferSize
= LastBufferSize
* 2;
1201 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1204 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1205 LastBufferSize
= BufferSize
;
1207 if (EFI_ERROR(Status
)) {
1213 // check for end of listing
1214 if (BufferSize
== 0) { // end of directory listing
1220 // entry is ready to be returned
1221 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1224 if (FilterMode
== 1) { // only return directories
1225 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1227 } else if (FilterMode
== 2) { // only return files
1228 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1230 } else // no filter or unknown filter -> return everything
1237 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1239 if (RelativePath
== NULL
) {
1240 DirIter
->LastStatus
= EFI_SUCCESS
;
1241 DirIter
->DirHandle
= BaseDir
;
1242 DirIter
->CloseDirHandle
= FALSE
;
1244 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1245 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1247 DirIter
->LastFileInfo
= NULL
;
1250 #ifndef __MAKEWITH_GNUEFI
1251 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1254 InitializeUnicodeCollationProtocol (VOID
)
1258 if (mUnicodeCollation
!= NULL
) {
1263 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1264 // instances first and then select one which support English language.
1265 // Current implementation just pick the first instance.
1267 Status
= gBS
->LocateProtocol (
1268 &gEfiUnicodeCollation2ProtocolGuid
,
1270 (VOID
**) &mUnicodeCollation
1272 if (EFI_ERROR(Status
)) {
1273 Status
= gBS
->LocateProtocol (
1274 &gEfiUnicodeCollationProtocolGuid
,
1276 (VOID
**) &mUnicodeCollation
1284 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1286 if (!mUnicodeCollation
) {
1287 InitializeUnicodeCollationProtocol();
1289 if (mUnicodeCollation
)
1290 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1291 return FALSE
; // Shouldn't happen
1294 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1295 if (!mUnicodeCollation
) {
1296 InitializeUnicodeCollationProtocol();
1298 if (mUnicodeCollation
)
1299 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1304 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1305 OUT EFI_FILE_INFO
**DirEntry
)
1307 BOOLEAN KeepGoing
= TRUE
;
1311 if (DirIter
->LastFileInfo
!= NULL
) {
1312 FreePool(DirIter
->LastFileInfo
);
1313 DirIter
->LastFileInfo
= NULL
;
1316 if (EFI_ERROR(DirIter
->LastStatus
))
1317 return FALSE
; // stop iteration
1320 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1321 if (EFI_ERROR(DirIter
->LastStatus
))
1323 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1325 if (FilePattern
!= NULL
) {
1326 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1329 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1330 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1333 // else continue loop
1336 } while (KeepGoing
&& FilePattern
);
1338 *DirEntry
= DirIter
->LastFileInfo
;
1342 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1344 if (DirIter
->LastFileInfo
!= NULL
) {
1345 FreePool(DirIter
->LastFileInfo
);
1346 DirIter
->LastFileInfo
= NULL
;
1348 if (DirIter
->CloseDirHandle
)
1349 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1350 return DirIter
->LastStatus
;
1354 // file name manipulation
1357 // Returns the filename portion (minus path name) of the
1359 CHAR16
* Basename(IN CHAR16
*Path
)
1367 for (i
= StrLen(Path
); i
> 0; i
--) {
1368 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1369 FileName
= Path
+ i
;
1378 // Remove the .efi extension from FileName -- for instance, if FileName is
1379 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1380 // returns a copy of the original input.
1381 CHAR16
* StripEfiExtension(CHAR16
*FileName
) {
1383 CHAR16
*Copy
= NULL
;
1385 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1386 Length
= StrLen(Copy
);
1387 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1388 if ((Length
>= 4) && ((StriCmp(&Copy
[Length
- 4], L
".efi") == 0) || (StriCmp(&Copy
[Length
- 4], L
".EFI") == 0))) {
1389 Copy
[Length
- 4] = 0;
1393 } // CHAR16 * StripExtension()
1396 // memory string search
1399 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1405 BufferLength
-= SearchStringLength
;
1406 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1407 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1408 return (INTN
)Offset
;
1414 // Performs a case-insensitive search of BigStr for SmallStr.
1415 // Returns TRUE if found, FALSE if not.
1416 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1417 CHAR16
*SmallCopy
, *BigCopy
;
1418 BOOLEAN Found
= FALSE
;
1419 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1421 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1422 SmallCopy
= StrDuplicate(SmallStr
);
1423 BigCopy
= StrDuplicate(BigStr
);
1426 SmallLen
= StrLen(SmallCopy
);
1427 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1428 while ((!Found
) && (StartPoint
< NumCompares
)) {
1429 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1431 MyFreePool(SmallCopy
);
1432 MyFreePool(BigCopy
);
1436 } // BOOLEAN StriSubCmp()
1438 // Merges two strings, creating a new one and returning a pointer to it.
1439 // If AddChar != 0, the specified character is placed between the two original
1440 // strings (unless the first string is NULL or empty). The original input
1441 // string *First is de-allocated and replaced by the new merged string.
1442 // This is similar to StrCat, but safer and more flexible because
1443 // MergeStrings allocates memory that's the correct size for the
1444 // new merged string, so it can take a NULL *First and it cleans
1445 // up the old memory. It should *NOT* be used with a constant
1446 // *First, though....
1447 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1448 UINTN Length1
= 0, Length2
= 0;
1452 Length1
= StrLen(*First
);
1454 Length2
= StrLen(Second
);
1455 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1456 if (NewString
!= NULL
) {
1457 if ((*First
!= NULL
) && (StrLen(*First
) == 0)) {
1461 NewString
[0] = L
'\0';
1462 if (*First
!= NULL
) {
1463 StrCat(NewString
, *First
);
1465 NewString
[Length1
] = AddChar
;
1466 NewString
[Length1
+ 1] = '\0';
1468 } // if (*First != NULL)
1470 StrCat(NewString
, Second
);
1474 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1476 } // static CHAR16* MergeStrings()
1478 // Takes an input pathname (*Path) and returns the part of the filename from
1479 // the final dot onwards, converted to lowercase. If the filename includes
1480 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1481 // The calling function is responsible for freeing the memory associated with
1482 // the return value.
1483 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1485 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1488 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1491 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1492 if (Path
[i
] == L
'.')
1494 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1500 MergeStrings(&Extension
, &Path
[i
], 0);
1505 } // CHAR16 *FindExtension
1507 // Takes an input pathname (*Path) and locates the final directory component
1508 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1509 // function returns the string 'foo'.
1510 // Assumes the pathname is separated with backslashes.
1511 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1512 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1513 CHAR16
*Found
= NULL
;
1518 PathLength
= StrLen(Path
);
1519 // Find start & end of target element
1520 for (i
= 0; i
< PathLength
; i
++) {
1521 if (Path
[i
] == '\\') {
1522 StartOfElement
= EndOfElement
;
1526 // Extract the target element
1527 if (EndOfElement
> 0) {
1528 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1532 if (EndOfElement
>= StartOfElement
) {
1533 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1534 Found
= StrDuplicate(&Path
[StartOfElement
]);
1536 Found
[CopyLength
] = 0;
1537 } // if (EndOfElement >= StartOfElement)
1538 } // if (EndOfElement > 0)
1540 } // CHAR16 *FindLastDirName
1542 // Returns the directory portion of a pathname. For instance,
1543 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1544 // string 'EFI\foo'. The calling function is responsible for
1545 // freeing the returned string's memory.
1546 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1547 UINTN i
, LastBackslash
= 0;
1548 CHAR16
*PathOnly
= NULL
;
1550 if (FullPath
!= NULL
) {
1551 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1552 if (FullPath
[i
] == '\\')
1555 PathOnly
= StrDuplicate(FullPath
);
1556 if (PathOnly
!= NULL
)
1557 PathOnly
[LastBackslash
] = 0;
1562 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1563 // DeviceVolume, and returns that and the filename (*loader).
1564 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1565 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1567 BOOLEAN Found
= FALSE
;
1569 MyFreePool(*loader
);
1570 MyFreePool(*DeviceVolume
);
1571 *DeviceVolume
= NULL
;
1572 DeviceString
= DevicePathToStr(loadpath
);
1573 *loader
= SplitDeviceString(DeviceString
);
1575 while ((i
< VolumesCount
) && (!Found
)) {
1576 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1577 Temp
= SplitDeviceString(VolumeDeviceString
);
1578 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1580 *DeviceVolume
= Volumes
[i
];
1583 MyFreePool(VolumeDeviceString
);
1587 MyFreePool(DeviceString
);
1588 } // VOID FindVolumeAndFilename()
1590 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1591 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1592 // the filename component in the original *Path variable and the split-off
1593 // volume component in the *VolName variable.
1594 // Returns TRUE if both components are found, FALSE otherwise.
1595 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1596 UINTN i
= 0, Length
;
1602 if (*VolName
!= NULL
) {
1603 MyFreePool(*VolName
);
1607 Length
= StrLen(*Path
);
1608 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1613 Filename
= StrDuplicate((*Path
) + i
+ 1);
1621 } // BOOLEAN SplitVolumeAndFilename()
1623 // Returns all the digits in the input string, including intervening
1624 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1625 // this function returns "3.3.4-7". If InString contains no digits,
1626 // the return value is NULL.
1627 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1628 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1629 CHAR16
*Found
= NULL
;
1631 if (InString
== NULL
)
1634 InLength
= StartOfElement
= StrLen(InString
);
1635 // Find start & end of target element
1636 for (i
= 0; i
< InLength
; i
++) {
1637 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1638 if (StartOfElement
> i
)
1640 if (EndOfElement
< i
)
1644 // Extract the target element
1645 if (EndOfElement
> 0) {
1646 if (EndOfElement
>= StartOfElement
) {
1647 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1648 Found
= StrDuplicate(&InString
[StartOfElement
]);
1650 Found
[CopyLength
] = 0;
1651 } // if (EndOfElement >= StartOfElement)
1652 } // if (EndOfElement > 0)
1654 } // CHAR16 *FindNumbers()
1656 // Find the #Index element (numbered from 0) in a comma-delimited string
1658 // Returns the found element, or NULL if Index is out of range or InString
1659 // is NULL. Note that the calling function is responsible for freeing the
1660 // memory associated with the returned string pointer.
1661 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1662 UINTN StartPos
= 0, CurPos
= 0;
1663 BOOLEAN Found
= FALSE
;
1664 CHAR16
*FoundString
= NULL
;
1666 if (InString
!= NULL
) {
1667 // After while() loop, StartPos marks start of item #Index
1668 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1669 if (InString
[CurPos
] == L
',') {
1671 StartPos
= CurPos
+ 1;
1675 // After while() loop, CurPos is one past the end of the element
1676 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1677 if (InString
[CurPos
] == L
',')
1683 FoundString
= StrDuplicate(&InString
[StartPos
]);
1684 if (FoundString
!= NULL
)
1685 FoundString
[CurPos
- StartPos
] = 0;
1687 return (FoundString
);
1688 } // CHAR16 *FindCommaDelimited()
1690 // Return the position of SmallString within BigString, or -1 if
1692 INTN
FindSubString(IN CHAR16
*SmallString
, IN CHAR16
*BigString
) {
1694 UINTN i
= 0, SmallSize
, BigSize
;
1695 BOOLEAN Found
= FALSE
;
1697 if ((SmallString
== NULL
) || (BigString
== NULL
))
1700 SmallSize
= StrLen(SmallString
);
1701 BigSize
= StrLen(BigString
);
1702 if ((SmallSize
> BigSize
) || (SmallSize
== 0) || (BigSize
== 0))
1705 while ((i
<= (BigSize
- SmallSize
) && !Found
)) {
1706 if (CompareMem(BigString
+ i
, SmallString
, SmallSize
) == 0) {
1713 } // INTN FindSubString()
1715 // Take an input path name, which may include a volume specification and/or
1716 // a path, and return separate volume, path, and file names. For instance,
1717 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1718 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1719 // the returned pointer is NULL. The calling function is responsible for
1720 // freeing the allocated memory.
1721 VOID
SplitPathName(CHAR16
*InPath
, CHAR16
**VolName
, CHAR16
**Path
, CHAR16
**Filename
) {
1722 CHAR16
*Temp
= NULL
;
1724 MyFreePool(*VolName
);
1726 MyFreePool(*Filename
);
1727 *VolName
= *Path
= *Filename
= NULL
;
1728 Temp
= StrDuplicate(InPath
);
1729 SplitVolumeAndFilename(&Temp
, VolName
); // VolName is NULL or has volume; Temp has rest of path
1730 CleanUpPathNameSlashes(Temp
);
1731 *Path
= FindPath(Temp
); // *Path has path (may be 0-length); Temp unchanged.
1732 *Filename
= StrDuplicate(Temp
+ StrLen(*Path
));
1733 CleanUpPathNameSlashes(*Filename
);
1734 if (StrLen(*Path
) == 0) {
1738 if (StrLen(*Filename
) == 0) {
1739 MyFreePool(*Filename
);
1743 } // VOID SplitPathName
1745 // Returns TRUE if SmallString is an element in the comma-delimited List,
1746 // FALSE otherwise. Performs comparison case-insensitively (except on
1747 // buggy EFIs with case-sensitive StriCmp() functions).
1748 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1750 BOOLEAN Found
= FALSE
;
1753 if (SmallString
&& List
) {
1754 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1755 if (StriCmp(OneElement
, SmallString
) == 0)
1762 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1763 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1764 // Filename must *NOT* include a volume or path specification (that's part of
1765 // the Volume variable), but the List elements may. Performs comparison
1766 // case-insensitively (except on buggy EFIs with case-sensitive StriCmp()
1768 BOOLEAN
FilenameIn(REFIT_VOLUME
*Volume
, CHAR16
*Directory
, CHAR16
*Filename
, CHAR16
*List
) {
1770 BOOLEAN Found
= FALSE
;
1772 CHAR16
*TargetVolName
= NULL
, *TargetPath
= NULL
, *TargetFilename
= NULL
;
1774 if (Filename
&& List
) {
1775 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1777 SplitPathName(OneElement
, &TargetVolName
, &TargetPath
, &TargetFilename
);
1778 VolumeNumberToName(Volume
, &TargetVolName
);
1779 if (((TargetVolName
!= NULL
) && ((Volume
== NULL
) || (StriCmp(TargetVolName
, Volume
->VolName
) != 0))) ||
1780 ((TargetPath
!= NULL
) && (StriCmp(TargetPath
, Directory
) != 0)) ||
1781 ((TargetFilename
!= NULL
) && (StriCmp(TargetFilename
, Filename
) != 0))) {
1784 MyFreePool(OneElement
);
1788 MyFreePool(TargetVolName
);
1789 MyFreePool(TargetPath
);
1790 MyFreePool(TargetFilename
);
1792 } // BOOLEAN FilenameIn()
1794 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1795 // to this volume number, returns with *VolName changed to the volume name, as
1796 // stored in the Volume data structure.
1797 // Returns TRUE if this substitution was made, FALSE otherwise.
1798 BOOLEAN
VolumeNumberToName(REFIT_VOLUME
*Volume
, CHAR16
**VolName
) {
1799 BOOLEAN MadeSubstitution
= FALSE
;
1802 if ((VolName
== NULL
) || (*VolName
== NULL
))
1805 if ((StrLen(*VolName
) > 2) && (*VolName
[0] == L
'f') && (*VolName
[1] == L
's') && (*VolName
[2] >= L
'0') && (*VolName
[2] <= L
'9')) {
1806 VolNum
= Atoi(*VolName
+ 2);
1807 if (VolNum
== Volume
->VolNumber
) {
1808 MyFreePool(*VolName
);
1809 *VolName
= StrDuplicate(Volume
->VolName
);
1810 MadeSubstitution
= TRUE
;
1813 return MadeSubstitution
;
1814 } // BOOLEAN VolumeMatchesNumber()
1816 // Implement FreePool the way it should have been done to begin with, so that
1817 // it doesn't throw an ASSERT message if fed a NULL pointer....
1818 VOID
MyFreePool(IN VOID
*Pointer
) {
1819 if (Pointer
!= NULL
)
1823 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1825 // Eject all removable media.
1826 // Returns TRUE if any media were ejected, FALSE otherwise.
1827 BOOLEAN
EjectMedia(VOID
) {
1829 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1830 EFI_HANDLE
*Handles
, Handle
;
1831 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1833 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1834 if (EFI_ERROR(Status
) || HandleCount
== 0)
1835 return (FALSE
); // probably not an Apple system
1837 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1838 Handle
= Handles
[HandleIndex
];
1839 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1840 if (EFI_ERROR(Status
))
1842 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1843 if (!EFI_ERROR(Status
))
1846 MyFreePool(Handles
);
1847 return (Ejected
> 0);
1848 } // VOID EjectMedia()
1851 // Return the GUID as a string, suitable for display to the user. Note that the calling
1852 // function is responsible for freeing the allocated memory.
1853 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
1856 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
1857 if (TheString
!= 0) {
1858 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1859 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
1860 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
1861 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
1862 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
1865 } // GuidAsString(EFI_GUID *GuidData)