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-2013 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
)
206 if (SelfDir
!= NULL
) {
207 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
211 if (SelfRootDir
!= NULL
) {
212 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
217 // called after running external programs to re-open file handles
218 EFI_STATUS
ReinitRefitLib(VOID
)
222 if ((ST
->Hdr
.Revision
>> 16) == 1) {
223 // Below two lines were in rEFIt, but seem to cause system crashes or
224 // reboots when launching OSes after returning from programs on most
225 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
226 // installation volume" (see the next function) when returning from
227 // programs when these two lines are removed, and it often crashes
228 // when returning from a program or when launching a second program
229 // with these lines removed. Therefore, the preceding if() statement
230 // executes these lines only on EFIs with a major version number of 1
231 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
232 // of hardware on which to test is limited, though, so this may be the
233 // wrong test, or there may be a better way to fix this problem.
234 // TODO: Figure out cause of above weirdness and fix it more
236 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
237 SelfRootDir
= SelfVolume
->RootDir
;
240 return FinishInitRefitLib();
243 static EFI_STATUS
FinishInitRefitLib(VOID
)
247 if (SelfRootDir
== NULL
) {
248 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
249 if (SelfRootDir
== NULL
) {
250 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
251 return EFI_LOAD_ERROR
;
255 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
256 if (CheckFatalError(Status
, L
"while opening our installation directory"))
257 return EFI_LOAD_ERROR
;
266 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
270 *ElementCount
= InitialElementCount
;
271 if (*ElementCount
> 0) {
272 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
273 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
279 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
283 if ((*ElementCount
& 7) == 0) {
284 AllocateCount
= *ElementCount
+ 8;
285 if (*ElementCount
== 0)
286 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
288 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
290 (*ListPtr
)[*ElementCount
] = NewElement
;
292 } /* VOID AddListElement() */
294 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
298 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
299 for (i
= 0; i
< *ElementCount
; i
++) {
300 // TODO: call a user-provided routine for each element here
301 MyFreePool((*ListPtr
)[i
]);
303 MyFreePool(*ListPtr
);
308 // firmware device path discovery
311 static UINT8 LegacyLoaderMediaPathData
[] = {
312 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
313 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
314 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
316 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
318 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
321 UINTN HandleCount
= 0;
322 UINTN HandleIndex
, HardcodedIndex
;
327 EFI_LOADED_IMAGE
*LoadedImage
;
328 EFI_DEVICE_PATH
*DevicePath
;
331 MaxPaths
--; // leave space for the terminating NULL pointer
333 // get all LoadedImage handles
334 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
335 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
336 if (HardcodedPathList
) {
337 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
338 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
340 PathList
[PathCount
] = NULL
;
343 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
344 Handle
= Handles
[HandleIndex
];
346 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
347 if (EFI_ERROR(Status
))
348 continue; // This can only happen if the firmware scewed up, ignore it.
350 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
351 if (EFI_ERROR(Status
))
352 continue; // This happens, ignore it.
354 // Only grab memory range nodes
355 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
358 // Check if we have this device path in the list already
359 // WARNING: This assumes the first node in the device path is unique!
361 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
362 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
364 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
372 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
376 if (HardcodedPathList
) {
377 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
378 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
380 PathList
[PathCount
] = NULL
;
387 // Return a pointer to a string containing a filesystem type name. If the
388 // filesystem type is unknown, a blank (but non-null) string is returned.
389 // The returned variable is a constant that should NOT be freed.
390 static CHAR16
*FSTypeName(IN UINT32 TypeCode
) {
391 CHAR16
*retval
= NULL
;
397 case FS_TYPE_HFSPLUS
:
409 case FS_TYPE_REISERFS
:
410 retval
= L
" ReiserFS";
415 case FS_TYPE_ISO9660
:
416 retval
= L
" ISO-9660";
423 } // CHAR16 *FSTypeName()
425 // Identify the filesystem type, if possible. Expects a Buffer containing
426 // the first few (normally 4096) bytes of the filesystem, and outputs a
427 // code representing the identified filesystem type.
428 static UINT32
IdentifyFilesystemType(IN UINT8
*Buffer
, IN UINTN BufferSize
) {
429 UINT32 FoundType
= FS_TYPE_UNKNOWN
;
430 UINT32
*Ext2Incompat
, *Ext2Compat
;
434 if (Buffer
!= NULL
) {
436 if (BufferSize
>= 512) {
437 Magic16
= (UINT16
*) (Buffer
+ 510);
438 if (*Magic16
== FAT_MAGIC
)
440 } // search for FAT magic
442 if (BufferSize
>= (1024 + 100)) {
443 Magic16
= (UINT16
*) (Buffer
+ 1024 + 56);
444 if (*Magic16
== EXT2_SUPER_MAGIC
) { // ext2/3/4
445 Ext2Compat
= (UINT32
*) (Buffer
+ 1024 + 92);
446 Ext2Incompat
= (UINT32
*) (Buffer
+ 1024 + 96);
447 if ((*Ext2Incompat
& 0x0040) || (*Ext2Incompat
& 0x0200)) { // check for extents or flex_bg
449 } else if (*Ext2Compat
& 0x0004) { // check for journal
451 } else { // none of these features; presume it's ext2...
455 } // search for ext2/3/4 magic
457 if (BufferSize
>= (65536 + 62)) {
458 MagicString
= (char*) (Buffer
+ 65536 + 52);
459 if ((CompareMem(MagicString
, REISERFS_SUPER_MAGIC_STRING
, 8) == 0) ||
460 (CompareMem(MagicString
, REISER2FS_SUPER_MAGIC_STRING
, 9) == 0) ||
461 (CompareMem(MagicString
, REISER2FS_JR_SUPER_MAGIC_STRING
, 9) == 0)) {
462 return FS_TYPE_REISERFS
;
464 } // search for ReiserFS magic
466 if (BufferSize
>= (65536 + 64 + 8)) {
467 MagicString
= (char*) (Buffer
+ 65536 + 64);
468 if (CompareMem(MagicString
, BTRFS_SIGNATURE
, 8) == 0)
469 return FS_TYPE_BTRFS
;
470 } // search for Btrfs magic
472 if (BufferSize
>= (1024 + 2)) {
473 Magic16
= (UINT16
*) (Buffer
+ 1024);
474 if ((*Magic16
== HFSPLUS_MAGIC1
) || (*Magic16
== HFSPLUS_MAGIC2
)) {
475 return FS_TYPE_HFSPLUS
;
477 } // search for HFS+ magic
478 } // if (Buffer != NULL)
481 } // UINT32 IdentifyFilesystemType()
483 static VOID
ScanVolumeBootcode(REFIT_VOLUME
*Volume
, BOOLEAN
*Bootable
)
486 UINT8 Buffer
[SAMPLE_SIZE
];
488 MBR_PARTITION_INFO
*MbrTable
;
489 BOOLEAN MbrTableFound
;
491 Volume
->HasBootCode
= FALSE
;
492 Volume
->OSIconName
= NULL
;
493 Volume
->OSName
= NULL
;
496 if (Volume
->BlockIO
== NULL
)
498 if (Volume
->BlockIO
->Media
->BlockSize
> SAMPLE_SIZE
)
499 return; // our buffer is too small...
501 // look at the boot sector (this is used for both hard disks and El Torito images!)
502 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
503 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
504 Volume
->BlockIOOffset
, SAMPLE_SIZE
, Buffer
);
505 if (!EFI_ERROR(Status
)) {
507 Volume
->FSType
= IdentifyFilesystemType(Buffer
, SAMPLE_SIZE
);
508 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55 && Buffer
[0] != 0) {
510 Volume
->HasBootCode
= TRUE
;
513 // detect specific boot codes
514 if (CompareMem(Buffer
+ 2, "LILO", 4) == 0 ||
515 CompareMem(Buffer
+ 6, "LILO", 4) == 0 ||
516 CompareMem(Buffer
+ 3, "SYSLINUX", 8) == 0 ||
517 FindMem(Buffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
518 Volume
->HasBootCode
= TRUE
;
519 Volume
->OSIconName
= L
"linux";
520 Volume
->OSName
= L
"Linux";
522 } else if (FindMem(Buffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
523 Volume
->HasBootCode
= TRUE
;
524 Volume
->OSIconName
= L
"grub,linux";
525 Volume
->OSName
= L
"Linux";
527 // // Below doesn't produce a bootable entry, so commented out for the moment....
528 // // GRUB in BIOS boot partition:
529 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
530 // Volume->HasBootCode = TRUE;
531 // Volume->OSIconName = L"grub,linux";
532 // Volume->OSName = L"Linux";
533 // Volume->VolName = L"BIOS Boot Partition";
536 } else if ((*((UINT32
*)(Buffer
+ 502)) == 0 &&
537 *((UINT32
*)(Buffer
+ 506)) == 50000 &&
538 *((UINT16
*)(Buffer
+ 510)) == 0xaa55) ||
539 FindMem(Buffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
540 Volume
->HasBootCode
= TRUE
;
541 Volume
->OSIconName
= L
"freebsd";
542 Volume
->OSName
= L
"FreeBSD";
544 } else if (FindMem(Buffer
, 512, "!Loading", 8) >= 0 ||
545 FindMem(Buffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
546 Volume
->HasBootCode
= TRUE
;
547 Volume
->OSIconName
= L
"openbsd";
548 Volume
->OSName
= L
"OpenBSD";
550 } else if (FindMem(Buffer
, 512, "Not a bootxx image", 18) >= 0 ||
551 *((UINT32
*)(Buffer
+ 1028)) == 0x7886b6d1) {
552 Volume
->HasBootCode
= TRUE
;
553 Volume
->OSIconName
= L
"netbsd";
554 Volume
->OSName
= L
"NetBSD";
556 } else if (FindMem(Buffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
557 Volume
->HasBootCode
= TRUE
;
558 Volume
->OSIconName
= L
"win";
559 Volume
->OSName
= L
"Windows";
561 } else if (FindMem(Buffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
562 Volume
->HasBootCode
= TRUE
;
563 Volume
->OSIconName
= L
"winvista,win";
564 Volume
->OSName
= L
"Windows";
566 } else if (FindMem(Buffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
567 FindMem(Buffer
, 512, "KERNEL SYS", 11) >= 0) {
568 Volume
->HasBootCode
= TRUE
;
569 Volume
->OSIconName
= L
"freedos";
570 Volume
->OSName
= L
"FreeDOS";
572 } else if (FindMem(Buffer
, 512, "OS2LDR", 6) >= 0 ||
573 FindMem(Buffer
, 512, "OS2BOOT", 7) >= 0) {
574 Volume
->HasBootCode
= TRUE
;
575 Volume
->OSIconName
= L
"ecomstation";
576 Volume
->OSName
= L
"eComStation";
578 } else if (FindMem(Buffer
, 512, "Be Boot Loader", 14) >= 0) {
579 Volume
->HasBootCode
= TRUE
;
580 Volume
->OSIconName
= L
"beos";
581 Volume
->OSName
= L
"BeOS";
583 } else if (FindMem(Buffer
, 512, "yT Boot Loader", 14) >= 0) {
584 Volume
->HasBootCode
= TRUE
;
585 Volume
->OSIconName
= L
"zeta,beos";
586 Volume
->OSName
= L
"ZETA";
588 } else if (FindMem(Buffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
589 FindMem(Buffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
590 Volume
->HasBootCode
= TRUE
;
591 Volume
->OSIconName
= L
"haiku,beos";
592 Volume
->OSName
= L
"Haiku";
596 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
597 // need to fix AddLegacyEntry in main.c.
600 Print(L
" Result of bootcode detection: %s %s (%s)\n",
601 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
602 Volume
->OSName
, Volume
->OSIconName
);
605 // dummy FAT boot sector (created by OS X's newfs_msdos)
606 if (FindMem(Buffer
, 512, "Non-system disk", 15) >= 0)
607 Volume
->HasBootCode
= FALSE
;
609 // dummy FAT boot sector (created by Linux's mkdosfs)
610 if (FindMem(Buffer
, 512, "This is not a bootable disk", 27) >= 0)
611 Volume
->HasBootCode
= FALSE
;
613 // dummy FAT boot sector (created by Windows)
614 if (FindMem(Buffer
, 512, "Press any key to restart", 24) >= 0)
615 Volume
->HasBootCode
= FALSE
;
617 // check for MBR partition table
618 if (*((UINT16
*)(Buffer
+ 510)) == 0xaa55) {
619 MbrTableFound
= FALSE
;
620 MbrTable
= (MBR_PARTITION_INFO
*)(Buffer
+ 446);
621 for (i
= 0; i
< 4; i
++)
622 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
623 MbrTableFound
= TRUE
;
624 for (i
= 0; i
< 4; i
++)
625 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
626 MbrTableFound
= FALSE
;
628 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
629 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
635 CheckError(Status
, L
"while reading boot sector");
638 } /* VOID ScanVolumeBootcode() */
640 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
641 VOID
SetVolumeBadgeIcon(REFIT_VOLUME
*Volume
)
643 if (Volume
->VolBadgeImage
== NULL
) {
644 Volume
->VolBadgeImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeBadge", 128);
647 if (Volume
->VolBadgeImage
== NULL
) {
648 switch (Volume
->DiskKind
) {
649 case DISK_KIND_INTERNAL
:
650 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
652 case DISK_KIND_EXTERNAL
:
653 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
655 case DISK_KIND_OPTICAL
:
656 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
660 } // VOID SetVolumeBadgeIcon()
662 // Return a string representing the input size in IEEE-1541 units.
663 // The calling function is responsible for freeing the allocated memory.
664 static CHAR16
*SizeInIEEEUnits(UINT64 SizeInBytes
) {
666 UINTN Index
= 0, NumPrefixes
;
667 CHAR16
*Units
, *Prefixes
= L
" KMGTPEZ";
670 TheValue
= AllocateZeroPool(sizeof(CHAR16
) * 256);
671 if (TheValue
!= NULL
) {
672 NumPrefixes
= StrLen(Prefixes
);
673 SizeInIeee
= SizeInBytes
;
674 while ((SizeInIeee
> 1024) && (Index
< (NumPrefixes
- 1))) {
678 if (Prefixes
[Index
] == ' ') {
679 Units
= StrDuplicate(L
"-byte");
681 Units
= StrDuplicate(L
" iB");
682 Units
[1] = Prefixes
[Index
];
684 SPrint(TheValue
, 255, L
"%ld%s", SizeInIeee
, Units
);
687 } // CHAR16 *SizeInSIUnits()
689 // Return a name for the volume. Ideally this should be the label for the
690 // filesystem it contains, but this function falls back to describing the
691 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
692 // this information can be extracted.
693 // The calling function is responsible for freeing the memory allocated
694 // for the name string.
695 static CHAR16
*GetVolumeName(IN REFIT_VOLUME
*Volume
) {
696 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
697 CHAR16
*FoundName
= NULL
;
698 CHAR16
*SISize
, *TypeName
;
700 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
701 if (FileSystemInfoPtr
!= NULL
) { // we have filesystem information (size, label)....
702 if ((FileSystemInfoPtr
->VolumeLabel
!= NULL
) && (StrLen(FileSystemInfoPtr
->VolumeLabel
) > 0)) {
703 FoundName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
706 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
707 // this so that we can build a new name that includes the size....
708 if ((FoundName
!= NULL
) && (StrCmp(FoundName
, L
"HFS+ volume") == 0) && (Volume
->FSType
== FS_TYPE_HFSPLUS
)) {
709 MyFreePool(FoundName
);
711 } // if rEFInd HFS+ driver suspected
713 if (FoundName
== NULL
) { // filesystem has no name, so use fs type and size
714 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
715 if (FoundName
!= NULL
) {
716 SISize
= SizeInIEEEUnits(FileSystemInfoPtr
->VolumeSize
);
717 SPrint(FoundName
, 255, L
"%s%s volume", SISize
, FSTypeName(Volume
->FSType
));
719 } // if allocated memory OK
720 } // if (FoundName == NULL)
722 FreePool(FileSystemInfoPtr
);
724 } else { // fs driver not returning info; fall back on our own information....
725 FoundName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
726 if (FoundName
!= NULL
) {
727 TypeName
= FSTypeName(Volume
->FSType
); // NOTE: Don't free TypeName; function returns constant
728 if (StrLen(TypeName
) > 0)
729 SPrint(FoundName
, 255, L
"%s volume", FSTypeName(Volume
->FSType
));
731 SPrint(FoundName
, 255, L
"unknown volume");
732 } // if allocated memory OK
735 // TODO: Above could be improved/extended, in case filesystem name is not found,
737 // - use partition label
738 // - use or add disk/partition number (e.g., "(hd0,2)")
740 // Desperate fallback name....
741 if (FoundName
== NULL
) {
742 FoundName
= StrDuplicate(L
"unknown volume");
745 } // static CHAR16 *GetVolumeName()
747 VOID
ScanVolume(REFIT_VOLUME
*Volume
)
750 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
751 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
752 EFI_HANDLE WholeDiskHandle
;
757 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
759 if (Volume
->DevicePath
!= NULL
) {
760 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
762 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
767 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
770 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
771 if (EFI_ERROR(Status
)) {
772 Volume
->BlockIO
= NULL
;
773 Print(L
"Warning: Can't get BlockIO protocol.\n");
775 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
776 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
779 // scan for bootcode and MBR table
781 ScanVolumeBootcode(Volume
, &Bootable
);
783 // detect device type
784 DevicePath
= Volume
->DevicePath
;
785 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
786 NextDevicePath
= NextDevicePathNode(DevicePath
);
788 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
789 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
790 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
791 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
792 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
793 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
794 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
795 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
796 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
800 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
801 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
802 // TODO: also check for Boot Camp GUID
803 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
806 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
807 // make a device path for the whole device
808 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
809 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
810 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
811 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
813 // get the handle for that path
814 RemainingDevicePath
= DiskDevicePath
;
815 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
816 FreePool(DiskDevicePath
);
818 if (!EFI_ERROR(Status
)) {
819 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
821 // get the device path for later
822 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
823 if (!EFI_ERROR(Status
)) {
824 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
827 // look at the BlockIO protocol
828 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
829 if (!EFI_ERROR(Status
)) {
831 // check the media block size
832 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
833 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
836 Volume
->WholeDiskBlockIO
= NULL
;
837 //CheckError(Status, L"from HandleProtocol");
840 // CheckError(Status, L"from LocateDevicePath");
843 DevicePath
= NextDevicePath
;
848 if (Volume
->HasBootCode
)
849 Print(L
" Volume considered non-bootable, but boot code is present\n");
851 Volume
->HasBootCode
= FALSE
;
854 // open the root directory of the volume
855 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
857 // Set volume icon based on .VolumeBadge icon or disk kind
858 SetVolumeBadgeIcon(Volume
);
860 if (Volume
->RootDir
== NULL
) {
861 Volume
->IsReadable
= FALSE
;
864 Volume
->IsReadable
= TRUE
;
867 Volume
->VolName
= GetVolumeName(Volume
);
869 // get custom volume icons if present
870 if (!Volume
->VolIconImage
)
871 Volume
->VolIconImage
= egLoadIconAnyType(Volume
->RootDir
, L
"", L
".VolumeIcon", 128);
874 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
877 REFIT_VOLUME
*Volume
;
878 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
880 UINTN LogicalPartitionIndex
= 4;
881 UINT8 SectorBuffer
[512];
883 MBR_PARTITION_INFO
*EMbrTable
;
885 ExtBase
= MbrEntry
->StartLBA
;
887 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
889 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
890 WholeDiskVolume
->BlockIO
,
891 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
892 ExtCurrent
, 512, SectorBuffer
);
893 if (EFI_ERROR(Status
))
895 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
897 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
899 // scan logical partitions in this EMBR
901 for (i
= 0; i
< 4; i
++) {
902 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
903 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
905 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
906 // set next ExtCurrent
907 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
911 // found a logical partition
912 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
913 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
914 Volume
->IsMbrPartition
= TRUE
;
915 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
916 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
917 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
918 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
919 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
920 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
923 ScanVolumeBootcode(Volume
, &Bootable
);
925 Volume
->HasBootCode
= FALSE
;
927 SetVolumeBadgeIcon(Volume
);
929 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
934 } /* VOID ScanExtendedPartition() */
936 VOID
ScanVolumes(VOID
)
940 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
941 MBR_PARTITION_INFO
*MbrTable
;
942 UINTN HandleCount
= 0;
944 UINTN VolumeIndex
, VolumeIndex2
;
945 UINTN PartitionIndex
;
946 UINTN SectorSum
, i
, VolNumber
= 0;
947 UINT8
*SectorBuffer1
, *SectorBuffer2
;
953 // get all filesystem handles
954 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
955 // was: &FileSystemProtocol
956 if (Status
== EFI_NOT_FOUND
) {
957 return; // no filesystems. strange, but true...
959 if (CheckError(Status
, L
"while listing all file systems"))
962 // first pass: collect information about all handles
963 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
964 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
965 Volume
->DeviceHandle
= Handles
[HandleIndex
];
967 if (Volume
->IsReadable
)
968 Volume
->VolNumber
= VolNumber
++;
970 Volume
->VolNumber
= VOL_UNREADABLE
;
972 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
974 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
979 if (SelfVolume
== NULL
)
980 Print(L
"WARNING: SelfVolume not found");
982 // second pass: relate partitions and whole disk devices
983 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
984 Volume
= Volumes
[VolumeIndex
];
985 // check MBR partition table for extended partitions
986 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
987 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
988 Volume
->MbrPartitionTable
!= NULL
) {
989 MbrTable
= Volume
->MbrPartitionTable
;
990 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
991 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
992 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
997 // search for corresponding whole disk volume entry
998 WholeDiskVolume
= NULL
;
999 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
1000 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
1001 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
1002 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
1003 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
1004 WholeDiskVolume
= Volumes
[VolumeIndex2
];
1008 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
1009 // check if this volume is one of the partitions in the table
1010 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
1011 SectorBuffer1
= AllocatePool(512);
1012 SectorBuffer2
= AllocatePool(512);
1013 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
1015 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
1018 // compare boot sector read through offset vs. directly
1019 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
1020 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
1021 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
1022 if (EFI_ERROR(Status
))
1024 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
1025 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
1026 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
1027 if (EFI_ERROR(Status
))
1029 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
1032 for (i
= 0; i
< 512; i
++)
1033 SectorSum
+= SectorBuffer1
[i
];
1034 if (SectorSum
< 1000)
1037 // TODO: mark entry as non-bootable if it is an extended partition
1039 // now we're reasonably sure the association is correct...
1040 Volume
->IsMbrPartition
= TRUE
;
1041 Volume
->MbrPartitionIndex
= PartitionIndex
;
1042 if (Volume
->VolName
== NULL
) {
1043 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1044 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
1049 MyFreePool(SectorBuffer1
);
1050 MyFreePool(SectorBuffer2
);
1054 } /* VOID ScanVolumes() */
1056 static VOID
UninitVolumes(VOID
)
1058 REFIT_VOLUME
*Volume
;
1061 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1062 Volume
= Volumes
[VolumeIndex
];
1064 if (Volume
->RootDir
!= NULL
) {
1065 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
1066 Volume
->RootDir
= NULL
;
1069 Volume
->DeviceHandle
= NULL
;
1070 Volume
->BlockIO
= NULL
;
1071 Volume
->WholeDiskBlockIO
= NULL
;
1075 VOID
ReinitVolumes(VOID
)
1078 REFIT_VOLUME
*Volume
;
1080 EFI_DEVICE_PATH
*RemainingDevicePath
;
1081 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
1083 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1084 Volume
= Volumes
[VolumeIndex
];
1086 if (Volume
->DevicePath
!= NULL
) {
1087 // get the handle for that path
1088 RemainingDevicePath
= Volume
->DevicePath
;
1089 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
1091 if (!EFI_ERROR(Status
)) {
1092 Volume
->DeviceHandle
= DeviceHandle
;
1094 // get the root directory
1095 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
1098 CheckError(Status
, L
"from LocateDevicePath");
1101 if (Volume
->WholeDiskDevicePath
!= NULL
) {
1102 // get the handle for that path
1103 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
1104 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
1106 if (!EFI_ERROR(Status
)) {
1107 // get the BlockIO protocol
1108 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
1109 if (EFI_ERROR(Status
)) {
1110 Volume
->WholeDiskBlockIO
= NULL
;
1111 CheckError(Status
, L
"from HandleProtocol");
1114 CheckError(Status
, L
"from LocateDevicePath");
1120 // file and dir functions
1123 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
1126 EFI_FILE_HANDLE TestFile
;
1128 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
1129 if (Status
== EFI_SUCCESS
) {
1130 refit_call1_wrapper(TestFile
->Close
, TestFile
);
1136 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
1140 UINTN LastBufferSize
, BufferSize
;
1145 // free pointer from last call
1146 if (*DirEntry
!= NULL
) {
1147 FreePool(*DirEntry
);
1151 // read next directory entry
1152 LastBufferSize
= BufferSize
= 256;
1153 Buffer
= AllocatePool(BufferSize
);
1154 for (IterCount
= 0; ; IterCount
++) {
1155 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
1156 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
1158 if (BufferSize
<= LastBufferSize
) {
1159 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
1160 BufferSize
= LastBufferSize
* 2;
1163 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
1166 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
1167 LastBufferSize
= BufferSize
;
1169 if (EFI_ERROR(Status
)) {
1175 // check for end of listing
1176 if (BufferSize
== 0) { // end of directory listing
1182 // entry is ready to be returned
1183 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
1186 if (FilterMode
== 1) { // only return directories
1187 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
1189 } else if (FilterMode
== 2) { // only return files
1190 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
1192 } else // no filter or unknown filter -> return everything
1199 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
1201 if (RelativePath
== NULL
) {
1202 DirIter
->LastStatus
= EFI_SUCCESS
;
1203 DirIter
->DirHandle
= BaseDir
;
1204 DirIter
->CloseDirHandle
= FALSE
;
1206 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
1207 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
1209 DirIter
->LastFileInfo
= NULL
;
1212 #ifndef __MAKEWITH_GNUEFI
1213 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
1216 InitializeUnicodeCollationProtocol (VOID
)
1220 if (mUnicodeCollation
!= NULL
) {
1225 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1226 // instances first and then select one which support English language.
1227 // Current implementation just pick the first instance.
1229 Status
= gBS
->LocateProtocol (
1230 &gEfiUnicodeCollation2ProtocolGuid
,
1232 (VOID
**) &mUnicodeCollation
1234 if (EFI_ERROR(Status
)) {
1235 Status
= gBS
->LocateProtocol (
1236 &gEfiUnicodeCollationProtocolGuid
,
1238 (VOID
**) &mUnicodeCollation
1246 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1248 if (!mUnicodeCollation
) {
1249 InitializeUnicodeCollationProtocol();
1251 if (mUnicodeCollation
)
1252 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1253 return FALSE
; // Shouldn't happen
1256 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1257 if (!mUnicodeCollation
) {
1258 InitializeUnicodeCollationProtocol();
1260 if (mUnicodeCollation
)
1261 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1266 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1267 OUT EFI_FILE_INFO
**DirEntry
)
1269 BOOLEAN KeepGoing
= TRUE
;
1273 if (DirIter
->LastFileInfo
!= NULL
) {
1274 FreePool(DirIter
->LastFileInfo
);
1275 DirIter
->LastFileInfo
= NULL
;
1278 if (EFI_ERROR(DirIter
->LastStatus
))
1279 return FALSE
; // stop iteration
1282 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1283 if (EFI_ERROR(DirIter
->LastStatus
))
1285 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1287 if (FilePattern
!= NULL
) {
1288 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1291 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1292 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1295 // else continue loop
1298 } while (KeepGoing
&& FilePattern
);
1300 *DirEntry
= DirIter
->LastFileInfo
;
1304 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1306 if (DirIter
->LastFileInfo
!= NULL
) {
1307 FreePool(DirIter
->LastFileInfo
);
1308 DirIter
->LastFileInfo
= NULL
;
1310 if (DirIter
->CloseDirHandle
)
1311 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1312 return DirIter
->LastStatus
;
1316 // file name manipulation
1319 // Returns the filename portion (minus path name) of the
1321 CHAR16
* Basename(IN CHAR16
*Path
)
1329 for (i
= StrLen(Path
); i
> 0; i
--) {
1330 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1331 FileName
= Path
+ i
;
1340 // Remove the .efi extension from FileName -- for instance, if FileName is
1341 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1342 // returns a copy of the original input.
1343 CHAR16
* StripEfiExtension(CHAR16
*FileName
) {
1345 CHAR16
*Copy
= NULL
;
1347 if ((FileName
!= NULL
) && ((Copy
= StrDuplicate(FileName
)) != NULL
)) {
1348 Length
= StrLen(Copy
);
1349 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1350 if ((Length
>= 4) && ((StriCmp(&Copy
[Length
- 4], L
".efi") == 0) || (StriCmp(&Copy
[Length
- 4], L
".EFI") == 0))) {
1351 Copy
[Length
- 4] = 0;
1355 } // CHAR16 * StripExtension()
1358 // memory string search
1361 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1367 BufferLength
-= SearchStringLength
;
1368 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1369 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1370 return (INTN
)Offset
;
1376 // Performs a case-insensitive search of BigStr for SmallStr.
1377 // Returns TRUE if found, FALSE if not.
1378 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1379 CHAR16
*SmallCopy
, *BigCopy
;
1380 BOOLEAN Found
= FALSE
;
1381 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1383 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1384 SmallCopy
= StrDuplicate(SmallStr
);
1385 BigCopy
= StrDuplicate(BigStr
);
1388 SmallLen
= StrLen(SmallCopy
);
1389 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1390 while ((!Found
) && (StartPoint
< NumCompares
)) {
1391 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1393 MyFreePool(SmallCopy
);
1394 MyFreePool(BigCopy
);
1398 } // BOOLEAN StriSubCmp()
1400 // Merges two strings, creating a new one and returning a pointer to it.
1401 // If AddChar != 0, the specified character is placed between the two original
1402 // strings (unless the first string is NULL or empty). The original input
1403 // string *First is de-allocated and replaced by the new merged string.
1404 // This is similar to StrCat, but safer and more flexible because
1405 // MergeStrings allocates memory that's the correct size for the
1406 // new merged string, so it can take a NULL *First and it cleans
1407 // up the old memory. It should *NOT* be used with a constant
1408 // *First, though....
1409 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1410 UINTN Length1
= 0, Length2
= 0;
1414 Length1
= StrLen(*First
);
1416 Length2
= StrLen(Second
);
1417 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1418 if (NewString
!= NULL
) {
1419 if ((*First
!= NULL
) && (StrLen(*First
) == 0)) {
1423 NewString
[0] = L
'\0';
1424 if (*First
!= NULL
) {
1425 StrCat(NewString
, *First
);
1427 NewString
[Length1
] = AddChar
;
1428 NewString
[Length1
+ 1] = '\0';
1430 } // if (*First != NULL)
1432 StrCat(NewString
, Second
);
1436 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1438 } // static CHAR16* MergeStrings()
1440 // Takes an input pathname (*Path) and returns the part of the filename from
1441 // the final dot onwards, converted to lowercase. If the filename includes
1442 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1443 // The calling function is responsible for freeing the memory associated with
1444 // the return value.
1445 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1447 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1450 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1453 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1454 if (Path
[i
] == L
'.')
1456 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1462 MergeStrings(&Extension
, &Path
[i
], 0);
1467 } // CHAR16 *FindExtension
1469 // Takes an input pathname (*Path) and locates the final directory component
1470 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1471 // function returns the string 'foo'.
1472 // Assumes the pathname is separated with backslashes.
1473 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1474 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1475 CHAR16
*Found
= NULL
;
1480 PathLength
= StrLen(Path
);
1481 // Find start & end of target element
1482 for (i
= 0; i
< PathLength
; i
++) {
1483 if (Path
[i
] == '\\') {
1484 StartOfElement
= EndOfElement
;
1488 // Extract the target element
1489 if (EndOfElement
> 0) {
1490 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1494 if (EndOfElement
>= StartOfElement
) {
1495 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1496 Found
= StrDuplicate(&Path
[StartOfElement
]);
1498 Found
[CopyLength
] = 0;
1499 } // if (EndOfElement >= StartOfElement)
1500 } // if (EndOfElement > 0)
1502 } // CHAR16 *FindLastDirName
1504 // Returns the directory portion of a pathname. For instance,
1505 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1506 // string 'EFI\foo'. The calling function is responsible for
1507 // freeing the returned string's memory.
1508 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1509 UINTN i
, LastBackslash
= 0;
1510 CHAR16
*PathOnly
= NULL
;
1512 if (FullPath
!= NULL
) {
1513 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1514 if (FullPath
[i
] == '\\')
1517 PathOnly
= StrDuplicate(FullPath
);
1518 PathOnly
[LastBackslash
] = 0;
1523 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1524 // DeviceVolume, and returns that and the filename (*loader).
1525 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1526 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1528 BOOLEAN Found
= FALSE
;
1530 MyFreePool(*loader
);
1531 MyFreePool(*DeviceVolume
);
1532 *DeviceVolume
= NULL
;
1533 DeviceString
= DevicePathToStr(loadpath
);
1534 *loader
= SplitDeviceString(DeviceString
);
1536 while ((i
< VolumesCount
) && (!Found
)) {
1537 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1538 Temp
= SplitDeviceString(VolumeDeviceString
);
1539 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1541 *DeviceVolume
= Volumes
[i
];
1544 MyFreePool(VolumeDeviceString
);
1548 MyFreePool(DeviceString
);
1549 } // VOID FindVolumeAndFilename()
1551 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1552 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1553 // the filename component in the original *Path variable and the split-off
1554 // volume component in the *VolName variable.
1555 // Returns TRUE if both components are found, FALSE otherwise.
1556 BOOLEAN
SplitVolumeAndFilename(IN OUT CHAR16
**Path
, OUT CHAR16
**VolName
) {
1557 UINTN i
= 0, Length
;
1563 if (*VolName
!= NULL
) {
1564 MyFreePool(*VolName
);
1568 Length
= StrLen(*Path
);
1569 while ((i
< Length
) && ((*Path
)[i
] != L
':')) {
1574 Filename
= StrDuplicate((*Path
) + i
+ 1);
1582 } // BOOLEAN SplitVolumeAndFilename()
1584 // Returns all the digits in the input string, including intervening
1585 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1586 // this function returns "3.3.4-7". If InString contains no digits,
1587 // the return value is NULL.
1588 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1589 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1590 CHAR16
*Found
= NULL
;
1592 if (InString
== NULL
)
1595 InLength
= StartOfElement
= StrLen(InString
);
1596 // Find start & end of target element
1597 for (i
= 0; i
< InLength
; i
++) {
1598 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1599 if (StartOfElement
> i
)
1601 if (EndOfElement
< i
)
1605 // Extract the target element
1606 if (EndOfElement
> 0) {
1607 if (EndOfElement
>= StartOfElement
) {
1608 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1609 Found
= StrDuplicate(&InString
[StartOfElement
]);
1611 Found
[CopyLength
] = 0;
1612 } // if (EndOfElement >= StartOfElement)
1613 } // if (EndOfElement > 0)
1615 } // CHAR16 *FindNumbers()
1617 // Find the #Index element (numbered from 0) in a comma-delimited string
1619 // Returns the found element, or NULL if Index is out of range or InString
1620 // is NULL. Note that the calling function is responsible for freeing the
1621 // memory associated with the returned string pointer.
1622 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1623 UINTN StartPos
= 0, CurPos
= 0;
1624 BOOLEAN Found
= FALSE
;
1625 CHAR16
*FoundString
= NULL
;
1627 if (InString
!= NULL
) {
1628 // After while() loop, StartPos marks start of item #Index
1629 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1630 if (InString
[CurPos
] == L
',') {
1632 StartPos
= CurPos
+ 1;
1636 // After while() loop, CurPos is one past the end of the element
1637 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1638 if (InString
[CurPos
] == L
',')
1644 FoundString
= StrDuplicate(&InString
[StartPos
]);
1645 if (FoundString
!= NULL
)
1646 FoundString
[CurPos
- StartPos
] = 0;
1648 return (FoundString
);
1649 } // CHAR16 *FindCommaDelimited()
1651 // Returns TRUE if SmallString is an element in the comma-delimited List,
1652 // FALSE otherwise. Performs comparison case-insensitively (except on
1653 // buggy EFIs with case-sensitive StriCmp() functions).
1654 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1656 BOOLEAN Found
= FALSE
;
1659 if (SmallString
&& List
) {
1660 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1661 if (StriCmp(OneElement
, SmallString
) == 0)
1668 // Implement FreePool the way it should have been done to begin with, so that
1669 // it doesn't throw an ASSERT message if fed a NULL pointer....
1670 VOID
MyFreePool(IN VOID
*Pointer
) {
1671 if (Pointer
!= NULL
)
1675 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1677 // Eject all removable media.
1678 // Returns TRUE if any media were ejected, FALSE otherwise.
1679 BOOLEAN
EjectMedia(VOID
) {
1681 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1682 EFI_HANDLE
*Handles
, Handle
;
1683 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1685 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1686 if (EFI_ERROR(Status
) || HandleCount
== 0)
1687 return (FALSE
); // probably not an Apple system
1689 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1690 Handle
= Handles
[HandleIndex
];
1691 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1692 if (EFI_ERROR(Status
))
1694 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1695 if (!EFI_ERROR(Status
))
1698 MyFreePool(Handles
);
1699 return (Ejected
> 0);
1700 } // VOID EjectMedia()
1703 // Return the GUID as a string, suitable for display to the user. Note that the calling
1704 // function is responsible for freeing the allocated memory.
1705 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
1708 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
1709 if (TheString
!= 0) {
1710 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1711 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
1712 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
1713 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
1714 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
1717 } // GuidAsString(EFI_GUID *GuidData)