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"
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;
89 extern GPT_DATA
*gPartitions
;
91 // Maximum size for disk sectors
92 #define SECTOR_SIZE 4096
94 // Number of bytes to read from a partition to determine its filesystem type
95 // and identify its boot loader, and hence probable BIOS-mode OS installation
96 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
101 static EFI_STATUS
FinishInitRefitLib(VOID
);
103 static VOID
UninitVolumes(VOID
);
106 // self recognition stuff
109 // Converts forward slashes to backslashes, removes duplicate slashes, and
110 // removes slashes from both the start and end of the pathname.
111 // Necessary because some (buggy?) EFI implementations produce "\/" strings
112 // in pathnames, because some user inputs can produce duplicate directory
113 // separators, and because we want consistent start and end slashes for
114 // directory comparisons. A special case: If the PathName refers to root,
115 // return "/", since some firmware implementations flake out if this
117 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
119 UINTN i
, Length
, FinalChar
= 0;
120 BOOLEAN LastWasSlash
= FALSE
;
122 Length
= StrLen(PathName
);
123 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (Length
+ 2));
124 if (NewName
!= NULL
) {
125 for (i
= 0; i
< StrLen(PathName
); i
++) {
126 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
127 if ((!LastWasSlash
) && (FinalChar
!= 0))
128 NewName
[FinalChar
++] = L
'\\';
131 NewName
[FinalChar
++] = PathName
[i
];
132 LastWasSlash
= FALSE
;
135 NewName
[FinalChar
] = 0;
136 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
137 NewName
[--FinalChar
] = 0;
138 if (FinalChar
== 0) {
142 // Copy the transformed name back....
143 StrCpy(PathName
, NewName
);
145 } // if allocation OK
146 } // CleanUpPathNameSlashes()
148 // Splits an EFI device path into device and filename components. For instance, if InString is
149 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
150 // this function will truncate that input to
151 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
152 // and return bzImage-3.5.1.efi as its return value.
153 // It does this by searching for the last ")" character in InString, copying everything
154 // after that string (after some cleanup) as the return value, and truncating the original
156 // If InString contains no ")" character, this function leaves the original input string
157 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
158 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
160 CHAR16
*FileName
= NULL
;
161 BOOLEAN Found
= FALSE
;
163 if (InString
!= NULL
) {
164 i
= StrLen(InString
) - 1;
165 while ((i
>= 0) && (!Found
)) {
166 if (InString
[i
] == L
')') {
168 FileName
= StrDuplicate(&InString
[i
+ 1]);
169 CleanUpPathNameSlashes(FileName
);
170 InString
[i
+ 1] = '\0';
174 if (FileName
== NULL
)
175 FileName
= StrDuplicate(InString
);
178 } // static CHAR16* SplitDeviceString()
180 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
183 CHAR16
*DevicePathAsString
, *Temp
;
185 SelfImageHandle
= ImageHandle
;
186 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
187 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
188 return EFI_LOAD_ERROR
;
190 // find the current directory
191 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
192 CleanUpPathNameSlashes(DevicePathAsString
);
193 MyFreePool(SelfDirPath
);
194 Temp
= FindPath(DevicePathAsString
);
195 SelfDirPath
= SplitDeviceString(Temp
);
196 MyFreePool(DevicePathAsString
);
199 return FinishInitRefitLib();
202 // called before running external programs to close open file handles
203 VOID
UninitRefitLib(VOID
)
205 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
206 // See the comment on it there.
207 if(SelfRootDir
== SelfVolume
->RootDir
)
212 if (SelfDir
!= NULL
) {
213 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
217 if (SelfRootDir
!= NULL
) {
218 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
223 // called after running external programs to re-open file handles
224 EFI_STATUS
ReinitRefitLib(VOID
)
228 if ((ST
->Hdr
.Revision
>> 16) == 1) {
229 // Below two lines were in rEFIt, but seem to cause system crashes or
230 // reboots when launching OSes after returning from programs on most
231 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
232 // installation volume" (see the next function) when returning from
233 // programs when these two lines are removed, and it often crashes
234 // when returning from a program or when launching a second program
235 // with these lines removed. Therefore, the preceding if() statement
236 // executes these lines only on EFIs with a major version number of 1
237 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
238 // of hardware on which to test is limited, though, so this may be the
239 // wrong test, or there may be a better way to fix this problem.
240 // TODO: Figure out cause of above weirdness and fix it more
242 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
243 SelfRootDir
= SelfVolume
->RootDir
;
246 return FinishInitRefitLib();
249 static EFI_STATUS
FinishInitRefitLib(VOID
)
253 if (SelfRootDir
== NULL
) {
254 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
255 if (SelfRootDir
== NULL
) {
256 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
257 return EFI_LOAD_ERROR
;
261 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
262 if (CheckFatalError(Status
, L
"while opening our installation directory"))
263 return EFI_LOAD_ERROR
;
269 // EFI variable read and write functions
272 // From gummiboot: Retrieve a raw EFI variable.
273 // Returns EFI status
274 EFI_STATUS
EfivarGetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
**buffer
, UINTN
*size
) {
279 l
= sizeof(CHAR16
*) * EFI_MAXIMUM_VARIABLE_SIZE
;
280 buf
= AllocatePool(l
);
282 return EFI_OUT_OF_RESOURCES
;
284 err
= refit_call5_wrapper(RT
->GetVariable
, name
, vendor
, NULL
, &l
, buf
);
285 if (EFI_ERROR(err
) == EFI_SUCCESS
) {
292 } // EFI_STATUS EfivarGetRaw()
294 // From gummiboot: Set an EFI variable
295 EFI_STATUS
EfivarSetRaw(EFI_GUID
*vendor
, CHAR16
*name
, CHAR8
*buf
, UINTN size
, BOOLEAN persistent
) {
298 flags
= EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
300 flags
|= EFI_VARIABLE_NON_VOLATILE
;
302 return refit_call5_wrapper(RT
->SetVariable
, name
, vendor
, flags
, size
, buf
);
303 } // EFI_STATUS EfivarSetRaw()
309 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
313 *ElementCount
= InitialElementCount
;
314 if (*ElementCount
> 0) {
315 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
316 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
322 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
326 if ((*ElementCount
& 7) == 0) {
327 AllocateCount
= *ElementCount
+ 8;
328 if (*ElementCount
== 0)
329 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
331 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
333 (*ListPtr
)[*ElementCount
] = NewElement
;
335 } /* VOID AddListElement() */
337 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
341 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
342 for (i
= 0; i
< *ElementCount
; i
++) {
343 // TODO: call a user-provided routine for each element here
344 MyFreePool((*ListPtr
)[i
]);
346 MyFreePool(*ListPtr
);
351 // firmware device path discovery
354 static UINT8 LegacyLoaderMediaPathData
[] = {
355 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
356 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
357 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
359 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
361 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
364 UINTN HandleCount
= 0;
365 UINTN HandleIndex
, HardcodedIndex
;
370 EFI_LOADED_IMAGE
*LoadedImage
;
371 EFI_DEVICE_PATH
*DevicePath
;
374 MaxPaths
--; // leave space for the terminating NULL pointer
376 // get all LoadedImage handles
377 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
378 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
379 if (HardcodedPathList
) {
380 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
381 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
383 PathList
[PathCount
] = NULL
;
386 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
387 Handle
= Handles
[HandleIndex
];
389 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
390 if (EFI_ERROR(Status
))
391 continue; // This can only happen if the firmware scewed up, ignore it.
393 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
394 if (EFI_ERROR(Status
))
395 continue; // This happens, ignore it.
397 // Only grab memory range nodes
398 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
401 // Check if we have this device path in the list already
402 // WARNING: This assumes the first node in the device path is unique!
404 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
405 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
407 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
415 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
419 if (HardcodedPathList
) {
420 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
421 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
423 PathList
[PathCount
] = NULL
;
430 // Return a pointer to a string containing a filesystem type name. If the
431 // filesystem type is unknown, a blank (but non-null) string is returned.
432 // The returned variable is a constant that should NOT be freed.
433 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
434 CHAR16
*retval
= NULL
;
440 case FS_TYPE_HFSPLUS
:
452 case FS_TYPE_REISERFS
:
453 retval
= L
" ReiserFS";
458 case FS_TYPE_ISO9660
:
459 retval
= L
" ISO-9660";
466 } // CHAR16 *FSTypeName()
468 // Identify the filesystem type and record the filesystem's UUID/serial number,
469 // if possible. Expects a Buffer containing the first few (normally 4096) bytes
470 // of the filesystem. Sets the filesystem type code in Volume->FSType and the
471 // UUID/serial number in Volume->VolUuid. Note that the UUID value is recognized
472 // differently for each filesystem, and is currently supported only for
473 // ext2/3/4fs and ReiserFS. If the UUID can't be determined, it's set to 0. Also, the UUID
474 // is just read directly into memory; it is *NOT* valid when displayed by
475 // GuidAsString() or used in other GUID/UUID-manipulating functions. (As I
476 // write, it's being used merely to detect partitions that are part of a
478 static VOID
SetFilesystemData(IN UINT8
*Buffer
, IN UINTN BufferSize
, IN OUT REFIT_VOLUME
*Volume
) {
479 UINT32
*Ext2Incompat
, *Ext2Compat
;
483 if ((Buffer
!= NULL
) && (Volume
!= NULL
)) {
484 SetMem(&(Volume
->VolUuid
), sizeof(EFI_GUID
), 0);
485 Volume
->FSType
= FS_TYPE_UNKNOWN
;
487 if (BufferSize
>= 512) {
488 Magic16
= (UINT16
*) (Buffer
+ 510);
489 if (*Magic16
== FAT_MAGIC
) {
490 Volume
->FSType
= FS_TYPE_FAT
;
493 } // search for FAT magic
495 if (BufferSize
>= (1024 + 100)) {
496 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
497 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
498 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
499 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
500 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
501 Volume
->FSType
= FS_TYPE_EXT4
;
502 } else if (*Ext2Compat
& 0x0004) { // check for journal
503 Volume
->FSType
= FS_TYPE_EXT3
;
504 } else { // none of these features; presume it's ext2...
505 Volume
->FSType
= FS_TYPE_EXT2
;
507 CopyMem(&(Volume
->VolUuid
), Buffer
+ 1024 + 104, sizeof(EFI_GUID
));
510 } // search for ext2/3/4 magic
512 if (BufferSize
>= (65536 + 100)) {
513 MagicString
= (char*) (Buffer
+ 65536 + 52);
514 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
515 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
516 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
517 Volume
->FSType
= FS_TYPE_REISERFS
;
518 CopyMem(&(Volume
->VolUuid
), Buffer
+ 65536 + 84, sizeof(EFI_GUID
));
521 } // search for ReiserFS magic
523 if (BufferSize
>= (65536 + 64 + 8)) {
524 MagicString
= (char*) (Buffer
+ 65536 + 64);
525 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0) {
526 Volume
->FSType
= FS_TYPE_BTRFS
;
529 } // search for Btrfs magic
531 if (BufferSize
>= (1024 + 2)) {
532 Magic16
= (UINT16
*) (Buffer
+ 1024);
533 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
534 Volume
->FSType
= FS_TYPE_HFSPLUS
;
537 } // search for HFS+ magic
538 } // if (Buffer != NULL)
540 } // UINT32 SetFilesystemData()
542 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
545 UINT8 Buffer
[SAMPLE_SIZE
];
547 MBR_PARTITION_INFO
*MbrTable
;
548 BOOLEAN MbrTableFound
= FALSE
;
550 Volume
->HasBootCode
= FALSE
;
551 Volume
->OSIconName
= NULL
;
552 Volume
->OSName
= NULL
;
555 if (Volume
->BlockIO
== NULL
)
557 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
558 return; // our buffer is too small...
560 // look at the boot sector (this is used for both hard disks and El Torito images!)
561 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
562 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
563 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
564 if (!EFI_ERROR(Status
)) {
566 SetFilesystemData(Buffer
, SAMPLE_SIZE
, Volume
);
567 if ((*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) && (FindMem(Buffer
, 512, "EXFAT", 5) == -1)) {
569 Volume
->HasBootCode
= TRUE
;
572 // detect specific boot codes
573 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
574 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
575 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
576 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
577 Volume
->HasBootCode
= TRUE
;
578 Volume
->OSIconName
= L
"linux";
579 Volume
->OSName
= L
"Linux";
581 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
582 Volume
->HasBootCode
= TRUE
;
583 Volume
->OSIconName
= L
"grub,linux";
584 Volume
->OSName
= L
"Linux";
586 // // Below doesn't produce a bootable entry, so commented out for the moment....
587 // // GRUB in BIOS boot partition:
588 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
589 // Volume->HasBootCode = TRUE;
590 // Volume->OSIconName = L"grub,linux";
591 // Volume->OSName = L"Linux";
592 // Volume->VolName = L"BIOS Boot Partition";
595 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
596 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
597 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
598 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
599 Volume
->HasBootCode
= TRUE
;
600 Volume
->OSIconName
= L
"freebsd";
601 Volume
->OSName
= L
"FreeBSD";
603 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
604 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
605 Volume
->HasBootCode
= TRUE
;
606 Volume
->OSIconName
= L
"openbsd";
607 Volume
->OSName
= L
"OpenBSD";
609 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
610 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
611 Volume
->HasBootCode
= TRUE
;
612 Volume
->OSIconName
= L
"netbsd";
613 Volume
->OSName
= L
"NetBSD";
615 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
616 Volume
->HasBootCode
= TRUE
;
617 Volume
->OSIconName
= L
"win";
618 Volume
->OSName
= L
"Windows";
620 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
621 Volume
->HasBootCode
= TRUE
;
622 Volume
->OSIconName
= L
"winvista,win";
623 Volume
->OSName
= L
"Windows";
625 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
626 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
627 Volume
->HasBootCode
= TRUE
;
628 Volume
->OSIconName
= L
"freedos";
629 Volume
->OSName
= L
"FreeDOS";
631 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
632 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
633 Volume
->HasBootCode
= TRUE
;
634 Volume
->OSIconName
= L
"ecomstation";
635 Volume
->OSName
= L
"eComStation";
637 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
638 Volume
->HasBootCode
= TRUE
;
639 Volume
->OSIconName
= L
"beos";
640 Volume
->OSName
= L
"BeOS";
642 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
643 Volume
->HasBootCode
= TRUE
;
644 Volume
->OSIconName
= L
"zeta,beos";
645 Volume
->OSName
= L
"ZETA";
647 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
648 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
649 Volume
->HasBootCode
= TRUE
;
650 Volume
->OSIconName
= L
"haiku,beos";
651 Volume
->OSName
= L
"Haiku";
655 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
656 // need to fix AddLegacyEntry in main.c.
659 Print(L
" Result of bootcode detection: %s %s (%s)\n",
660 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
661 Volume
->OSName
, Volume
->OSIconName
);
664 // dummy FAT boot sector (created by OS X's newfs_msdos)
665 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
666 Volume
->HasBootCode
= FALSE
;
668 // dummy FAT boot sector (created by Linux's mkdosfs)
669 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
670 Volume
->HasBootCode
= FALSE
;
672 // dummy FAT boot sector (created by Windows)
673 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
674 Volume
->HasBootCode
= FALSE
;
676 // check for MBR partition table
677 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
678 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
679 for (i
= 0; i
< 4; i
++)
680 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
681 MbrTableFound
= TRUE
;
682 for (i
= 0; i
< 4; i
++)
683 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
684 MbrTableFound
= FALSE
;
686 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
687 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
693 CheckError(Status
, L
"while reading boot sector");
696 } /* VOID ScanVolumeBootcode() */
698 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
699 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
701 if (Volume
->VolBadgeImage
== NULL
) {
702 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", GlobalConfig
.IconSizes
[ICON_SIZE_BADGE
]);
705 if (Volume
->VolBadgeImage
== NULL
) {
706 switch (Volume
->DiskKind
) {
707 case DISK_KIND_INTERNAL
:
708 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
710 case DISK_KIND_EXTERNAL
:
711 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
713 case DISK_KIND_OPTICAL
:
714 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
718 } // VOID SetVolumeBadgeIcon()
720 // Return a string representing the input size in IEEE-1541 units.
721 // The calling function is responsible for freeing the allocated memory.
722 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
724 UINTN Index
= 0, NumPrefixes
;
725 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
728 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
729 if (TheValue
!= NULL
) {
730 NumPrefixes
= StrLen(Prefixes
);
731 SizeInIeee
= SizeInBytes
;
732 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
736 if (Prefixes
[Index
] == ' ') {
737 Units
= StrDuplicate(L
"-byte");
739 Units
= StrDuplicate(L
" iB");
740 Units
[1] = Prefixes
[Index
];
742 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
745 } // CHAR16 *SizeInIEEEUnits()
747 // Return a name for the volume. Ideally this should be the label for the
748 // filesystem it contains, but this function falls back to describing the
749 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
750 // this information can be extracted.
751 // The calling function is responsible for freeing the memory allocated
752 // for the name string.
753 static CHAR16
*GetVolumeName(REFIT_VOLUME
*Volume
) {
754 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
= NULL
;
755 CHAR16
*FoundName
= NULL
;
756 CHAR16
*SISize
, *TypeName
;
758 if (Volume
->RootDir
!= NULL
) {
759 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
762 if ((FileSystemInfoPtr
!= NULL
) && (FileSystemInfoPtr
->VolumeLabel
!= NULL
) &&
763 (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
764 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
767 // Special case: Old versions of the rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
768 // this so that we can build a new name that includes the size....
769 if ((FoundName
!= NULL
) && (StrCmp(FoundName
, L
"HFS+ volume") == 0) && (Volume
->FSType
== FS_TYPE_HFSPLUS
)) {
770 MyFreePool(FoundName
);
772 } // if rEFInd HFS+ driver suspected
774 // If no filesystem name, try to use the partition name....
775 if ((FoundName
== NULL
) && (Volume
->PartName
!= NULL
) && (StrLen(Volume
->PartName
) > 0) &&
776 !IsIn(Volume
->PartName
, IGNORE_PARTITION_NAMES
)) {
777 FoundName
= StrDuplicate(Volume
->PartName
);
778 } // if use partition name
780 // No filesystem or acceptable partition name, so use fs type and size
781 if ((FoundName
== NULL
) && (FileSystemInfoPtr
!= NULL
)) {
782 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
783 if (FoundName
!= NULL
) {
784 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
785 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
787 } // if allocated memory OK
788 } // if (FoundName == NULL)
790 MyFreePool(FileSystemInfoPtr
);
792 if (FoundName
== NULL
) {
793 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
794 if (FoundName
!= NULL
) {
795 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
796 if (StrLen(TypeName
) > 0)
797 SPrint(FoundName
, 255, L
"%s volume", TypeName
);
799 SPrint(FoundName
, 255, L
"unknown volume");
800 } // if allocated memory OK
803 // TODO: Above could be improved/extended, in case filesystem name is not found,
805 // - use or add disk/partition number (e.g., "(hd0,2)")
807 // Desperate fallback name....
808 if (FoundName
== NULL
) {
809 FoundName
= StrDuplicate(L
"unknown volume");
812 } // static CHAR16 *GetVolumeName()
814 // Determine the unique GUID of the volume and store it.
815 static VOID
SetPartGuidAndName(REFIT_VOLUME
*Volume
, EFI_DEVICE_PATH_PROTOCOL
*DevicePath
) {
816 HARDDRIVE_DEVICE_PATH
*HdDevicePath
;
821 if ((DevicePath
->Type
== MEDIA_DEVICE_PATH
) && (DevicePath
->SubType
== MEDIA_HARDDRIVE_DP
)) {
822 HdDevicePath
= (HARDDRIVE_DEVICE_PATH
*) DevicePath
;
823 if (HdDevicePath
->SignatureType
== SIGNATURE_TYPE_GUID
) {
824 Volume
->PartGuid
= *((EFI_GUID
*) HdDevicePath
->Signature
);
825 Volume
->PartName
= PartNameFromGuid(&(Volume
->PartGuid
));
828 } // VOID SetPartGuid()
830 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
833 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
834 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
835 EFI_HANDLE WholeDiskHandle
;
840 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
842 if (Volume
->DevicePath
!= NULL
) {
843 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
845 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
850 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
853 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
854 if (EFI_ERROR(Status
)) {
855 Volume
->BlockIO
= NULL
;
856 Print(L
"Warning: Can't get BlockIO protocol.\n");
858 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
859 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
862 // scan for bootcode and MBR table
864 ScanVolumeBootcode(Volume
, &Bootable
);
866 // detect device type
867 DevicePath
= Volume
->DevicePath
;
868 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
869 NextDevicePath
= NextDevicePathNode(DevicePath
);
871 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
) {
872 SetPartGuidAndName(Volume
, DevicePath
);
874 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
875 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
876 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
877 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
878 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
879 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
880 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
881 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
882 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
886 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
887 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
888 // TODO: also check for Boot Camp GUID
889 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
892 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
893 // make a device path for the whole device
894 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
895 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
896 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
897 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
899 // get the handle for that path
900 RemainingDevicePath
= DiskDevicePath
;
901 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
902 FreePool(DiskDevicePath
);
904 if (!EFI_ERROR(Status
)) {
905 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
907 // get the device path for later
908 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
909 if (!EFI_ERROR(Status
)) {
910 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
913 // look at the BlockIO protocol
914 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
915 (VOID
**) &Volume
->WholeDiskBlockIO
);
916 if (!EFI_ERROR(Status
)) {
918 // check the media block size
919 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
920 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
923 Volume
->WholeDiskBlockIO
= NULL
;
924 //CheckError(Status, L"from HandleProtocol");
927 // CheckError(Status, L"from LocateDevicePath");
930 DevicePath
= NextDevicePath
;
935 if (Volume
->HasBootCode
)
936 Print(L
" Volume considered non-bootable, but boot code is present\n");
938 Volume
->HasBootCode
= FALSE
;
941 // open the root directory of the volume
942 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
944 // Set volume icon based on .VolumeBadge icon or disk kind
945 SetVolumeBadgeIcon(Volume
);
947 Volume
->VolName
= GetVolumeName(Volume
);
949 if (Volume
->RootDir
== NULL
) {
950 Volume
->IsReadable
= FALSE
;
953 Volume
->IsReadable
= TRUE
;
956 // get custom volume icons if present
957 if (!Volume
->VolIconImage
)
958 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
961 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
964 REFIT_VOLUME
*Volume
;
965 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
967 UINTN LogicalPartitionIndex
= 4;
968 UINT8 SectorBuffer
[512];
970 MBR_PARTITION_INFO
*EMbrTable
;
972 ExtBase
= MbrEntry
->StartLBA
;
974 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
976 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
977 WholeDiskVolume
->BlockIO
,
978 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
979 ExtCurrent
, 512, SectorBuffer
);
980 if (EFI_ERROR(Status
))
982 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
984 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
986 // scan logical partitions in this EMBR
988 for (i
= 0; i
< 4; i
++) {
989 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
990 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
992 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
993 // set next ExtCurrent
994 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
998 // found a logical partition
999 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1000 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
1001 Volume
->IsMbrPartition
= TRUE
;
1002 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
1003 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
1004 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
1005 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
1006 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
1007 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
1010 ScanVolumeBootcode(Volume
, &Bootable
);
1012 Volume
->HasBootCode
= FALSE
;
1014 SetVolumeBadgeIcon(Volume
);
1016 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1021 } /* VOID ScanExtendedPartition() */
1023 VOID
ScanVolumes(VOID
)
1026 EFI_HANDLE
*Handles
;
1027 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
1028 MBR_PARTITION_INFO
*MbrTable
;
1029 UINTN HandleCount
= 0;
1031 UINTN VolumeIndex
, VolumeIndex2
;
1032 UINTN PartitionIndex
;
1033 UINTN SectorSum
, i
, VolNumber
= 0;
1034 UINT8
*SectorBuffer1
, *SectorBuffer2
;
1036 EFI_GUID NullUuid
= NULL_GUID_VALUE
;
1038 MyFreePool(Volumes
);
1041 ForgetPartitionTables();
1043 // get all filesystem handles
1044 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
1045 UuidList
= AllocateZeroPool(sizeof(EFI_GUID
) * HandleCount
);
1046 if (Status
== EFI_NOT_FOUND
) {
1047 return; // no filesystems. strange, but true...
1049 if (CheckError(Status
, L
"while listing all file systems"))
1052 // first pass: collect information about all handles
1053 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1054 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
1055 Volume
->DeviceHandle
= Handles
[HandleIndex
];
1056 AddPartitionTable(Volume
);
1059 UuidList
[HandleIndex
] = Volume
->VolUuid
;
1060 for (i
= 0; i
< HandleIndex
; i
++) {
1061 if ((CompareMem(&(Volume
->VolUuid
), &(UuidList
[i
]), sizeof(EFI_GUID
)) == 0) &&
1062 (CompareMem(&(Volume
->VolUuid
), &NullUuid
, sizeof(EFI_GUID
)) != 0)) { // Duplicate filesystem UUID
1063 Volume
->IsReadable
= FALSE
;
1067 if (Volume
->IsReadable
)
1068 Volume
->VolNumber
= VolNumber
++;
1070 Volume
->VolNumber
= VOL_UNREADABLE
;
1072 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
1074 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
1075 SelfVolume
= Volume
;
1077 MyFreePool(Handles
);
1079 if (SelfVolume
== NULL
)
1080 Print(L
"WARNING: SelfVolume not found");
1082 // second pass: relate partitions and whole disk devices
1083 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1084 Volume
= Volumes
[VolumeIndex
];
1085 // check MBR partition table for extended partitions
1086 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1087 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
1088 Volume
->MbrPartitionTable
!= NULL
) {
1089 MbrTable
= Volume
->MbrPartitionTable
;
1090 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1091 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
1092 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
1097 // search for corresponding whole disk volume entry
1098 WholeDiskVolume
= NULL
;
1099 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1100 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1101 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1102 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1103 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0) {
1104 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1109 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1110 // check if this volume is one of the partitions in the table
1111 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1112 SectorBuffer1
= AllocatePool(512);
1113 SectorBuffer2
= AllocatePool(512);
1114 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1116 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1119 // compare boot sector read through offset vs. directly
1120 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1121 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1122 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1123 if (EFI_ERROR(Status
))
1125 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1126 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1127 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1128 if (EFI_ERROR(Status
))
1130 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1133 for (i
= 0; i
< 512; i
++)
1134 SectorSum
+= SectorBuffer1
[i
];
1135 if (SectorSum
< 1000)
1138 // TODO: mark entry as non-bootable if it is an extended partition
1140 // now we're reasonably sure the association is correct...
1141 Volume
->IsMbrPartition
= TRUE
;
1142 Volume
->MbrPartitionIndex
= PartitionIndex
;
1143 if (Volume
->VolName
== NULL
) {
1144 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1145 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1150 MyFreePool(SectorBuffer1
);
1151 MyFreePool(SectorBuffer2
);
1154 } /* VOID ScanVolumes() */
1156 static VOID
UninitVolumes(VOID
)
1158 REFIT_VOLUME
*Volume
;
1161 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1162 Volume
= Volumes
[VolumeIndex
];
1164 if (Volume
->RootDir
!= NULL
) {
1165 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
1166 Volume
->RootDir
= NULL
;
1169 Volume
->DeviceHandle
= NULL
;
1170 Volume
->BlockIO
= NULL
;
1171 Volume
->WholeDiskBlockIO
= NULL
;
1175 VOID
ReinitVolumes(VOID
)
1178 REFIT_VOLUME
*Volume
;
1180 EFI_DEVICE_PATH
*RemainingDevicePath
;
1181 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
1183 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1184 Volume
= Volumes
[VolumeIndex
];
1186 if (Volume
->DevicePath
!= NULL
) {
1187 // get the handle for that path
1188 RemainingDevicePath
= Volume
->DevicePath
;
1189 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
1191 if (!EFI_ERROR(Status
)) {
1192 Volume
->DeviceHandle
= DeviceHandle
;
1194 // get the root directory
1195 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1198 CheckError(Status
, L
"from LocateDevicePath");
1201 if (Volume
->WholeDiskDevicePath
!= NULL
) {
1202 // get the handle for that path
1203 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
1204 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
1206 if (!EFI_ERROR(Status
)) {
1207 // get the BlockIO protocol
1208 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
,
1209 (VOID
**) &Volume
->WholeDiskBlockIO
);
1210 if (EFI_ERROR(Status
)) {
1211 Volume
->WholeDiskBlockIO
= NULL
;
1212 CheckError(Status
, L
"from HandleProtocol");
1215 CheckError(Status
, L
"from LocateDevicePath");
1221 // file and dir functions
1224 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1227 EFI_FILE_HANDLE TestFile
;
1229 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1230 if (Status
== EFI_SUCCESS
) {
1231 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1237 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1241 UINTN LastBufferSize
, BufferSize
;
1246 // free pointer from last call
1247 if (*DirEntry
!= NULL
) {
1248 FreePool(*DirEntry
);
1252 // read next directory entry
1253 LastBufferSize
= BufferSize
= 256;
1254 Buffer
= AllocatePool(BufferSize
);
1255 for (IterCount
= 0; ; IterCount
++) {
1256 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1257 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1259 if (BufferSize
<= LastBufferSize
) {
1260 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1261 BufferSize
= LastBufferSize
* 2;
1264 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1267 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1268 LastBufferSize
= BufferSize
;
1270 if (EFI_ERROR(Status
)) {
1276 // check for end of listing
1277 if (BufferSize
== 0) { // end of directory listing
1283 // entry is ready to be returned
1284 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1287 if (FilterMode
== 1) { // only return directories
1288 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1290 } else if (FilterMode
== 2) { // only return files
1291 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1293 } else // no filter or unknown filter -> return everything
1300 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1302 if (RelativePath
== NULL
) {
1303 DirIter
->LastStatus
= EFI_SUCCESS
;
1304 DirIter
->DirHandle
= BaseDir
;
1305 DirIter
->CloseDirHandle
= FALSE
;
1307 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1308 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1310 DirIter
->LastFileInfo
= NULL
;
1313 #ifndef __MAKEWITH_GNUEFI
1314 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1317 InitializeUnicodeCollationProtocol (VOID
)
1321 if (mUnicodeCollation
!= NULL
) {
1326 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1327 // instances first and then select one which support English language.
1328 // Current implementation just pick the first instance.
1330 Status
= gBS
->LocateProtocol (
1331 &gEfiUnicodeCollation2ProtocolGuid
,
1333 (VOID
**) &mUnicodeCollation
1335 if (EFI_ERROR(Status
)) {
1336 Status
= gBS
->LocateProtocol (
1337 &gEfiUnicodeCollationProtocolGuid
,
1339 (VOID
**) &mUnicodeCollation
1347 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1349 if (!mUnicodeCollation
) {
1350 InitializeUnicodeCollationProtocol();
1352 if (mUnicodeCollation
)
1353 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1354 return FALSE
; // Shouldn't happen
1357 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1358 if (!mUnicodeCollation
) {
1359 InitializeUnicodeCollationProtocol();
1361 if (mUnicodeCollation
)
1362 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1367 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1368 OUT EFI_FILE_INFO
**DirEntry
)
1370 BOOLEAN KeepGoing
= TRUE
;
1374 if (DirIter
->LastFileInfo
!= NULL
) {
1375 FreePool(DirIter
->LastFileInfo
);
1376 DirIter
->LastFileInfo
= NULL
;
1379 if (EFI_ERROR(DirIter
->LastStatus
))
1380 return FALSE
; // stop iteration
1383 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1384 if (EFI_ERROR(DirIter
->LastStatus
))
1386 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1388 if (FilePattern
!= NULL
) {
1389 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1392 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1393 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1396 // else continue loop
1399 } while (KeepGoing
&& FilePattern
);
1401 *DirEntry
= DirIter
->LastFileInfo
;
1405 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1407 if (DirIter
->LastFileInfo
!= NULL
) {
1408 FreePool(DirIter
->LastFileInfo
);
1409 DirIter
->LastFileInfo
= NULL
;
1411 if (DirIter
->CloseDirHandle
)
1412 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1413 return DirIter
->LastStatus
;
1417 // file name manipulation
1420 // Returns the filename portion (minus path name) of the
1422 CHAR16
* Basename(IN CHAR16
*Path
)
1430 for (i
= StrLen(Path
); i
> 0; i
--) {
1431 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1432 FileName
= Path
+ i
;
1441 // Remove the .efi extension from FileName -- for instance, if FileName is
1442 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1443 // returns a copy of the original input.
1444 CHAR16
* StripEfiExtension(CHAR16
*FileName
) {
1446 CHAR16
*Copy
= NULL
;
1448 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1449 Length
= StrLen(Copy
);
1450 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1451 if ((Length
>= 4) && ((StriCmp(&Copy
[Length
- 4], L
".efi") == 0) || (StriCmp(&Copy
[Length
- 4], L
".EFI") == 0))) {
1452 Copy
[Length
- 4] = 0;
1456 } // CHAR16 * StripExtension()
1459 // memory string search
1462 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1468 BufferLength
-= SearchStringLength
;
1469 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1470 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1471 return (INTN
)Offset
;
1477 // Performs a case-insensitive search of BigStr for SmallStr.
1478 // Returns TRUE if found, FALSE if not.
1479 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1480 CHAR16
*SmallCopy
, *BigCopy
;
1481 BOOLEAN Found
= FALSE
;
1482 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1484 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1485 SmallCopy
= StrDuplicate(SmallStr
);
1486 BigCopy
= StrDuplicate(BigStr
);
1489 SmallLen
= StrLen(SmallCopy
);
1490 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1491 while ((!Found
) && (StartPoint
< NumCompares
)) {
1492 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1494 MyFreePool(SmallCopy
);
1495 MyFreePool(BigCopy
);
1499 } // BOOLEAN StriSubCmp()
1501 // Merges two strings, creating a new one and returning a pointer to it.
1502 // If AddChar != 0, the specified character is placed between the two original
1503 // strings (unless the first string is NULL or empty). The original input
1504 // string *First is de-allocated and replaced by the new merged string.
1505 // This is similar to StrCat, but safer and more flexible because
1506 // MergeStrings allocates memory that's the correct size for the
1507 // new merged string, so it can take a NULL *First and it cleans
1508 // up the old memory. It should *NOT* be used with a constant
1509 // *First, though....
1510 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1511 UINTN Length1
= 0, Length2
= 0;
1515 Length1
= StrLen(*First
);
1517 Length2
= StrLen(Second
);
1518 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1519 if (NewString
!= NULL
) {
1520 if ((*First
!= NULL
) && (StrLen(*First
) == 0)) {
1524 NewString
[0] = L
'\0';
1525 if (*First
!= NULL
) {
1526 StrCat(NewString
, *First
);
1528 NewString
[Length1
] = AddChar
;
1529 NewString
[Length1
+ 1] = '\0';
1531 } // if (*First != NULL)
1533 StrCat(NewString
, Second
);
1537 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1539 } // static CHAR16* MergeStrings()
1541 // Takes an input pathname (*Path) and returns the part of the filename from
1542 // the final dot onwards, converted to lowercase. If the filename includes
1543 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1544 // The calling function is responsible for freeing the memory associated with
1545 // the return value.
1546 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1548 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1551 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1554 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1555 if (Path
[i
] == L
'.')
1557 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1563 MergeStrings(&Extension
, &Path
[i
], 0);
1568 } // CHAR16 *FindExtension
1570 // Takes an input pathname (*Path) and locates the final directory component
1571 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1572 // function returns the string 'foo'.
1573 // Assumes the pathname is separated with backslashes.
1574 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1575 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1576 CHAR16
*Found
= NULL
;
1581 PathLength
= StrLen(Path
);
1582 // Find start & end of target element
1583 for (i
= 0; i
< PathLength
; i
++) {
1584 if (Path
[i
] == '\\') {
1585 StartOfElement
= EndOfElement
;
1589 // Extract the target element
1590 if (EndOfElement
> 0) {
1591 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1595 if (EndOfElement
>= StartOfElement
) {
1596 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1597 Found
= StrDuplicate(&Path
[StartOfElement
]);
1599 Found
[CopyLength
] = 0;
1600 } // if (EndOfElement >= StartOfElement)
1601 } // if (EndOfElement > 0)
1603 } // CHAR16 *FindLastDirName
1605 // Returns the directory portion of a pathname. For instance,
1606 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1607 // string 'EFI\foo'. The calling function is responsible for
1608 // freeing the returned string's memory.
1609 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1610 UINTN i
, LastBackslash
= 0;
1611 CHAR16
*PathOnly
= NULL
;
1613 if (FullPath
!= NULL
) {
1614 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1615 if (FullPath
[i
] == '\\')
1618 PathOnly
= StrDuplicate(FullPath
);
1619 if (PathOnly
!= NULL
)
1620 PathOnly
[LastBackslash
] = 0;
1627 * Routine Description:
1633 * String - Null-terminated string to search.
1634 * StrCharSet - Null-terminated string to search for.
1637 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1639 CHAR16
* MyStrStr (CHAR16
*String
, CHAR16
*StrCharSet
)
1644 if ((String
== NULL
) || (StrCharSet
== NULL
))
1650 while ((*String
!= L
'\0') && (*StrCharSet
!= L
'\0')) {
1651 if (*String
++ != *StrCharSet
) {
1658 if (*StrCharSet
== L
'\0') {
1663 } // CHAR16 *MyStrStr()
1665 // Restrict TheString to at most Limit characters.
1666 // Does this in two ways:
1667 // - Locates stretches of two or more spaces and compresses
1668 // them down to one space.
1669 // - Truncates TheString
1670 // Returns TRUE if changes were made, FALSE otherwise
1671 BOOLEAN
LimitStringLength(CHAR16
*TheString
, UINTN Limit
) {
1672 CHAR16
*SubString
, *TempString
;
1674 BOOLEAN HasChanged
= FALSE
;
1676 // SubString will be NULL or point WITHIN TheString
1677 SubString
= MyStrStr(TheString
, L
" ");
1678 while (SubString
!= NULL
) {
1680 while (SubString
[i
] == L
' ')
1682 if (i
>= StrLen(SubString
)) {
1683 SubString
[0] = '\0';
1686 TempString
= StrDuplicate(&SubString
[i
]);
1687 if (TempString
!= NULL
) {
1688 StrCpy(&SubString
[1], TempString
);
1689 MyFreePool(TempString
);
1692 // memory allocation problem; abort to avoid potentially infinite loop!
1696 SubString
= MyStrStr(TheString
, L
" ");
1699 // If the string is still too long, truncate it....
1700 if (StrLen(TheString
) > Limit
) {
1701 TheString
[Limit
] = '\0';
1706 } // BOOLEAN LimitStringLength()
1708 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1709 // DeviceVolume, and returns that and the filename (*loader).
1710 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1711 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1713 BOOLEAN Found
= FALSE
;
1715 MyFreePool(*loader
);
1716 MyFreePool(*DeviceVolume
);
1717 *DeviceVolume
= NULL
;
1718 DeviceString
= DevicePathToStr(loadpath
);
1719 *loader
= SplitDeviceString(DeviceString
);
1721 while ((i
< VolumesCount
) && (!Found
)) {
1722 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1723 Temp
= SplitDeviceString(VolumeDeviceString
);
1724 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1726 *DeviceVolume
= Volumes
[i
];
1729 MyFreePool(VolumeDeviceString
);
1733 MyFreePool(DeviceString
);
1734 } // VOID FindVolumeAndFilename()
1736 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1737 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1738 // the filename component in the original *Path variable and the split-off
1739 // volume component in the *VolName variable.
1740 // Returns TRUE if both components are found, FALSE otherwise.
1741 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1742 UINTN i
= 0, Length
;
1748 if (*VolName
!= NULL
) {
1749 MyFreePool(*VolName
);
1753 Length
= StrLen(*Path
);
1754 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1759 Filename
= StrDuplicate((*Path
) + i
+ 1);
1767 } // BOOLEAN SplitVolumeAndFilename()
1769 // Returns all the digits in the input string, including intervening
1770 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1771 // this function returns "3.3.4-7". If InString contains no digits,
1772 // the return value is NULL.
1773 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1774 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1775 CHAR16
*Found
= NULL
;
1777 if (InString
== NULL
)
1780 InLength
= StartOfElement
= StrLen(InString
);
1781 // Find start & end of target element
1782 for (i
= 0; i
< InLength
; i
++) {
1783 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1784 if (StartOfElement
> i
)
1786 if (EndOfElement
< i
)
1790 // Extract the target element
1791 if (EndOfElement
> 0) {
1792 if (EndOfElement
>= StartOfElement
) {
1793 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1794 Found
= StrDuplicate(&InString
[StartOfElement
]);
1796 Found
[CopyLength
] = 0;
1797 } // if (EndOfElement >= StartOfElement)
1798 } // if (EndOfElement > 0)
1800 } // CHAR16 *FindNumbers()
1802 // Find the #Index element (numbered from 0) in a comma-delimited string
1804 // Returns the found element, or NULL if Index is out of range or InString
1805 // is NULL. Note that the calling function is responsible for freeing the
1806 // memory associated with the returned string pointer.
1807 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1808 UINTN StartPos
= 0, CurPos
= 0;
1809 BOOLEAN Found
= FALSE
;
1810 CHAR16
*FoundString
= NULL
;
1812 if (InString
!= NULL
) {
1813 // After while() loop, StartPos marks start of item #Index
1814 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1815 if (InString
[CurPos
] == L
',') {
1817 StartPos
= CurPos
+ 1;
1821 // After while() loop, CurPos is one past the end of the element
1822 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1823 if (InString
[CurPos
] == L
',')
1829 FoundString
= StrDuplicate(&InString
[StartPos
]);
1830 if (FoundString
!= NULL
)
1831 FoundString
[CurPos
- StartPos
] = 0;
1833 return (FoundString
);
1834 } // CHAR16 *FindCommaDelimited()
1836 // Return the position of SmallString within BigString, or -1 if
1838 INTN
FindSubString(IN CHAR16
*SmallString
, IN CHAR16
*BigString
) {
1840 UINTN i
= 0, SmallSize
, BigSize
;
1841 BOOLEAN Found
= FALSE
;
1843 if ((SmallString
== NULL
) || (BigString
== NULL
))
1846 SmallSize
= StrLen(SmallString
);
1847 BigSize
= StrLen(BigString
);
1848 if ((SmallSize
> BigSize
) || (SmallSize
== 0) || (BigSize
== 0))
1851 while ((i
<= (BigSize
- SmallSize
) && !Found
)) {
1852 if (CompareMem(BigString
+ i
, SmallString
, SmallSize
) == 0) {
1859 } // INTN FindSubString()
1861 // Take an input path name, which may include a volume specification and/or
1862 // a path, and return separate volume, path, and file names. For instance,
1863 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1864 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1865 // the returned pointer is NULL. The calling function is responsible for
1866 // freeing the allocated memory.
1867 VOID
SplitPathName(CHAR16
*InPath
, CHAR16
**VolName
, CHAR16
**Path
, CHAR16
**Filename
) {
1868 CHAR16
*Temp
= NULL
;
1870 MyFreePool(*VolName
);
1872 MyFreePool(*Filename
);
1873 *VolName
= *Path
= *Filename
= NULL
;
1874 Temp
= StrDuplicate(InPath
);
1875 SplitVolumeAndFilename(&Temp
, VolName
); // VolName is NULL or has volume; Temp has rest of path
1876 CleanUpPathNameSlashes(Temp
);
1877 *Path
= FindPath(Temp
); // *Path has path (may be 0-length); Temp unchanged.
1878 *Filename
= StrDuplicate(Temp
+ StrLen(*Path
));
1879 CleanUpPathNameSlashes(*Filename
);
1880 if (StrLen(*Path
) == 0) {
1884 if (StrLen(*Filename
) == 0) {
1885 MyFreePool(*Filename
);
1889 } // VOID SplitPathName
1891 // Returns TRUE if SmallString is an element in the comma-delimited List,
1892 // FALSE otherwise. Performs comparison case-insensitively (except on
1893 // buggy EFIs with case-sensitive StriCmp() functions).
1894 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1896 BOOLEAN Found
= FALSE
;
1899 if (SmallString
&& List
) {
1900 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1901 if (StriCmp(OneElement
, SmallString
) == 0)
1908 // Returns TRUE if any element of List can be found as a substring of
1909 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1910 BOOLEAN
IsInSubstring(IN CHAR16
*BigString
, IN CHAR16
*List
) {
1911 UINTN i
= 0, ElementLength
;
1912 BOOLEAN Found
= FALSE
;
1915 if (BigString
&& List
) {
1916 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1917 ElementLength
= StrLen(OneElement
);
1918 if ((ElementLength
<= StrLen(BigString
)) && (StriSubCmp(OneElement
, BigString
)))
1923 } // BOOLEAN IsSubstringIn()
1925 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1926 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1927 // Filename must *NOT* include a volume or path specification (that's part of
1928 // the Volume variable), but the List elements may. Performs comparison
1929 // case-insensitively (except on buggy EFIs with case-sensitive StriCmp()
1931 BOOLEAN
FilenameIn(REFIT_VOLUME
*Volume
, CHAR16
*Directory
, CHAR16
*Filename
, CHAR16
*List
) {
1933 BOOLEAN Found
= FALSE
;
1935 CHAR16
*TargetVolName
= NULL
, *TargetPath
= NULL
, *TargetFilename
= NULL
;
1937 if (Filename
&& List
) {
1938 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1940 SplitPathName(OneElement
, &TargetVolName
, &TargetPath
, &TargetFilename
);
1941 VolumeNumberToName(Volume
, &TargetVolName
);
1942 if (((TargetVolName
!= NULL
) && ((Volume
== NULL
) || (StriCmp(TargetVolName
, Volume
->VolName
) != 0))) ||
1943 ((TargetPath
!= NULL
) && (StriCmp(TargetPath
, Directory
) != 0)) ||
1944 ((TargetFilename
!= NULL
) && (StriCmp(TargetFilename
, Filename
) != 0))) {
1947 MyFreePool(OneElement
);
1951 MyFreePool(TargetVolName
);
1952 MyFreePool(TargetPath
);
1953 MyFreePool(TargetFilename
);
1955 } // BOOLEAN FilenameIn()
1957 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1958 // to this volume number, returns with *VolName changed to the volume name, as
1959 // stored in the Volume data structure.
1960 // Returns TRUE if this substitution was made, FALSE otherwise.
1961 BOOLEAN
VolumeNumberToName(REFIT_VOLUME
*Volume
, CHAR16
**VolName
) {
1962 BOOLEAN MadeSubstitution
= FALSE
;
1965 if ((VolName
== NULL
) || (*VolName
== NULL
))
1968 if ((StrLen(*VolName
) > 2) && (*VolName
[0] == L
'f') && (*VolName
[1] == L
's') && (*VolName
[2] >= L
'0') && (*VolName
[2] <= L
'9')) {
1969 VolNum
= Atoi(*VolName
+ 2);
1970 if (VolNum
== Volume
->VolNumber
) {
1971 MyFreePool(*VolName
);
1972 *VolName
= StrDuplicate(Volume
->VolName
);
1973 MadeSubstitution
= TRUE
;
1976 return MadeSubstitution
;
1977 } // BOOLEAN VolumeMatchesNumber()
1979 // Implement FreePool the way it should have been done to begin with, so that
1980 // it doesn't throw an ASSERT message if fed a NULL pointer....
1981 VOID
MyFreePool(IN VOID
*Pointer
) {
1982 if (Pointer
!= NULL
)
1986 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1988 // Eject all removable media.
1989 // Returns TRUE if any media were ejected, FALSE otherwise.
1990 BOOLEAN
EjectMedia(VOID
) {
1992 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1993 EFI_HANDLE
*Handles
, Handle
;
1994 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1996 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1997 if (EFI_ERROR(Status
) || HandleCount
== 0)
1998 return (FALSE
); // probably not an Apple system
2000 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
2001 Handle
= Handles
[HandleIndex
];
2002 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
2003 if (EFI_ERROR(Status
))
2005 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
2006 if (!EFI_ERROR(Status
))
2009 MyFreePool(Handles
);
2010 return (Ejected
> 0);
2011 } // VOID EjectMedia()
2013 // Converts consecutive characters in the input string into a
2014 // number, interpreting the string as a hexadecimal number, starting
2015 // at the specified position and continuing for the specified number
2016 // of characters or until the end of the string, whichever is first.
2017 // NumChars must be between 1 and 16. Ignores invalid characters.
2018 UINT64
StrToHex(CHAR16
*Input
, UINTN Pos
, UINTN NumChars
) {
2019 UINT64 retval
= 0x00;
2023 if ((Input
== NULL
) || (StrLen(Input
) < Pos
) || (NumChars
== 0) || (NumChars
> 16)) {
2027 while ((StrLen(Input
) >= Pos
) && (NumDone
< NumChars
)) {
2029 if ((a
>= '0') && (a
<= '9')) {
2031 retval
+= (a
- '0');
2034 if ((a
>= 'a') && (a
<= 'f')) {
2036 retval
+= (a
- 'a' + 0x0a);
2039 if ((a
>= 'A') && (a
<= 'F')) {
2041 retval
+= (a
- 'A' + 0x0a);
2049 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2050 // Note that the input string must have no extraneous spaces and must be
2051 // conventionally formatted as a 36-character GUID, complete with dashes in
2052 // appropriate places.
2053 BOOLEAN
IsGuid(CHAR16
*UnknownString
) {
2055 BOOLEAN retval
= TRUE
;
2058 if (UnknownString
== NULL
)
2061 Length
= StrLen(UnknownString
);
2065 for (i
= 0; i
< Length
; i
++) {
2066 a
= UnknownString
[i
];
2067 if ((i
== 8) || (i
== 13) || (i
== 18) || (i
== 23)) {
2070 } else if (((a
< 'a') || (a
> 'f')) && ((a
< 'A') || (a
> 'F')) && ((a
< '0') && (a
> '9'))) {
2075 } // BOOLEAN IsGuid()
2077 // Return the GUID as a string, suitable for display to the user. Note that the calling
2078 // function is responsible for freeing the allocated memory.
2079 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
2082 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
2083 if (TheString
!= 0) {
2084 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2085 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
2086 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
2087 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
2088 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
2091 } // GuidAsString(EFI_GUID *GuidData)
2093 EFI_GUID
StringAsGuid(CHAR16
* InString
) {
2094 EFI_GUID Guid
= NULL_GUID_VALUE
;
2096 if (!IsGuid(InString
)) {
2100 Guid
.Data1
= (UINT32
) StrToHex(InString
, 0, 8);
2101 Guid
.Data2
= (UINT16
) StrToHex(InString
, 9, 4);
2102 Guid
.Data3
= (UINT16
) StrToHex(InString
, 14, 4);
2103 Guid
.Data4
[0] = (UINT8
) StrToHex(InString
, 19, 2);
2104 Guid
.Data4
[1] = (UINT8
) StrToHex(InString
, 21, 2);
2105 Guid
.Data4
[2] = (UINT8
) StrToHex(InString
, 23, 2);
2106 Guid
.Data4
[3] = (UINT8
) StrToHex(InString
, 26, 2);
2107 Guid
.Data4
[4] = (UINT8
) StrToHex(InString
, 28, 2);
2108 Guid
.Data4
[5] = (UINT8
) StrToHex(InString
, 30, 2);
2109 Guid
.Data4
[6] = (UINT8
) StrToHex(InString
, 32, 2);
2110 Guid
.Data4
[7] = (UINT8
) StrToHex(InString
, 34, 2);
2113 } // EFI_GUID StringAsGuid()
2115 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2116 BOOLEAN
GuidsAreEqual(EFI_GUID
*Guid1
, EFI_GUID
*Guid2
) {
2117 return (CompareMem(Guid1
, Guid2
, 16) == 0);
2118 } // BOOLEAN CompareGuids()