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 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"
52 #ifdef __MAKEWITH_GNUEFI
53 #define EfiReallocatePool ReallocatePool
55 #define LibLocateHandle gBS->LocateHandleBuffer
56 #define DevicePathProtocol gEfiDevicePathProtocolGuid
57 #define BlockIoProtocol gEfiBlockIoProtocolGuid
58 #define LibFileSystemInfo EfiLibFileSystemInfo
59 #define LibOpenRoot EfiLibOpenRoot
60 EFI_DEVICE_PATH EndDevicePath
[] = {
61 {END_DEVICE_PATH_TYPE
, END_ENTIRE_DEVICE_PATH_SUBTYPE
, {END_DEVICE_PATH_LENGTH
, 0}}
64 //#define EndDevicePath DevicePath
69 EFI_HANDLE SelfImageHandle
;
70 EFI_LOADED_IMAGE
*SelfLoadedImage
;
71 EFI_FILE
*SelfRootDir
;
75 REFIT_VOLUME
*SelfVolume
= NULL
;
76 REFIT_VOLUME
**Volumes
= NULL
;
77 UINTN VolumesCount
= 0;
79 // Maximum size for disk sectors
80 #define SECTOR_SIZE 4096
82 // Default names for volume badges (mini-icon to define disk type) and icons
83 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
84 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
88 static EFI_STATUS
FinishInitRefitLib(VOID
);
90 static VOID
UninitVolumes(VOID
);
93 // self recognition stuff
96 // Converts forward slashes to backslashes, removes duplicate slashes, and
97 // removes slashes from the end of the pathname.
98 // Necessary because some (buggy?) EFI implementations produce "\/" strings
99 // in pathnames, because some user inputs can produce duplicate directory
100 // separators, and because we want consistent start and end slashes for
101 // directory comparisons. A special case: If the PathName refers to root,
102 // return "/", since some firmware implementations flake out if this
104 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
106 UINTN i
, FinalChar
= 0;
107 BOOLEAN LastWasSlash
= FALSE
;
109 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 4));
110 if (NewName
!= NULL
) {
111 for (i
= 0; i
< StrLen(PathName
); i
++) {
112 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
113 if ((!LastWasSlash
) /* && (FinalChar != 0) */)
114 NewName
[FinalChar
++] = L
'\\';
117 if (FinalChar
== 0) {
118 NewName
[FinalChar
++] = L
'\\';
120 NewName
[FinalChar
++] = PathName
[i
];
121 LastWasSlash
= FALSE
;
124 NewName
[FinalChar
] = 0;
125 if ((FinalChar
> 1) && (NewName
[FinalChar
- 1] == L
'\\'))
126 NewName
[--FinalChar
] = 0;
127 if (FinalChar
== 0) {
131 // Copy the transformed name back....
132 StrCpy(PathName
, NewName
);
134 } // if allocation OK
135 } // CleanUpPathNameSlashes()
137 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
140 CHAR16
*DevicePathAsString
;
142 SelfImageHandle
= ImageHandle
;
143 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
144 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
145 return EFI_LOAD_ERROR
;
147 // find the current directory
148 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
149 CleanUpPathNameSlashes(DevicePathAsString
);
150 MyFreePool(SelfDirPath
);
151 SelfDirPath
= FindPath(DevicePathAsString
);
152 MyFreePool(DevicePathAsString
);
154 return FinishInitRefitLib();
157 // called before running external programs to close open file handles
158 VOID
UninitRefitLib(VOID
)
162 if (SelfDir
!= NULL
) {
163 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
167 if (SelfRootDir
!= NULL
) {
168 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
173 // called after running external programs to re-open file handles
174 EFI_STATUS
ReinitRefitLib(VOID
)
178 if ((ST
->Hdr
.Revision
>> 16) == 1) {
179 // Below two lines were in rEFIt, but seem to cause system crashes or
180 // reboots when launching OSes after returning from programs on most
181 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
182 // installation volume" (see the next function) when returning from
183 // programs when these two lines are removed, and it often crashes
184 // when returning from a program or when launching a second program
185 // with these lines removed. Therefore, the preceding if() statement
186 // executes these lines only on EFIs with a major version number of 1
187 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
188 // of hardware on which to test is limited, though, so this may be the
189 // wrong test, or there may be a better way to fix this problem.
190 // TODO: Figure out cause of above weirdness and fix it more
192 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
193 SelfRootDir
= SelfVolume
->RootDir
;
196 return FinishInitRefitLib();
199 static EFI_STATUS
FinishInitRefitLib(VOID
)
203 if (SelfRootDir
== NULL
) {
204 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
205 if (SelfRootDir
== NULL
) {
206 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
207 return EFI_LOAD_ERROR
;
211 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
212 if (CheckFatalError(Status
, L
"while opening our installation directory"))
213 return EFI_LOAD_ERROR
;
222 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
226 *ElementCount
= InitialElementCount
;
227 if (*ElementCount
> 0) {
228 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
229 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
235 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
239 if ((*ElementCount
& 7) == 0) {
240 AllocateCount
= *ElementCount
+ 8;
241 if (*ElementCount
== 0)
242 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
244 *ListPtr
= EfiReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
246 (*ListPtr
)[*ElementCount
] = NewElement
;
248 } /* VOID AddListElement() */
250 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
254 if ((*ElementCount
> 0) && (**ListPtr
!= NULL
)) {
255 for (i
= 0; i
< *ElementCount
; i
++) {
256 // TODO: call a user-provided routine for each element here
257 MyFreePool((*ListPtr
)[i
]);
259 MyFreePool(*ListPtr
);
264 // firmware device path discovery
267 static UINT8 LegacyLoaderMediaPathData
[] = {
268 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
269 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
270 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
272 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
274 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
277 UINTN HandleCount
= 0;
278 UINTN HandleIndex
, HardcodedIndex
;
283 EFI_LOADED_IMAGE
*LoadedImage
;
284 EFI_DEVICE_PATH
*DevicePath
;
287 MaxPaths
--; // leave space for the terminating NULL pointer
289 // get all LoadedImage handles
290 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
, &HandleCount
, &Handles
);
291 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
292 if (HardcodedPathList
) {
293 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
294 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
296 PathList
[PathCount
] = NULL
;
299 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
300 Handle
= Handles
[HandleIndex
];
302 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
303 if (EFI_ERROR(Status
))
304 continue; // This can only happen if the firmware scewed up, ignore it.
306 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
307 if (EFI_ERROR(Status
))
308 continue; // This happens, ignore it.
310 // Only grab memory range nodes
311 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
314 // Check if we have this device path in the list already
315 // WARNING: This assumes the first node in the device path is unique!
317 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
318 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
320 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
328 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
332 if (HardcodedPathList
) {
333 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
334 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
336 PathList
[PathCount
] = NULL
;
343 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
346 UINT8 SectorBuffer
[SECTOR_SIZE
];
348 MBR_PARTITION_INFO
*MbrTable
;
349 BOOLEAN MbrTableFound
;
351 Volume
->HasBootCode
= FALSE
;
352 Volume
->OSIconName
= NULL
;
353 Volume
->OSName
= NULL
;
356 if (Volume
->BlockIO
== NULL
)
358 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
359 return; // our buffer is too small...
361 // look at the boot sector (this is used for both hard disks and El Torito images!)
362 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
363 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
364 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
365 if (!EFI_ERROR(Status
)) {
367 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
369 Volume
->HasBootCode
= TRUE
;
372 // detect specific boot codes
373 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
374 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
375 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
376 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
377 Volume
->HasBootCode
= TRUE
;
378 Volume
->OSIconName
= L
"linux";
379 Volume
->OSName
= L
"Linux";
381 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
382 Volume
->HasBootCode
= TRUE
;
383 Volume
->OSIconName
= L
"grub,linux";
384 Volume
->OSName
= L
"Linux";
386 // // Below doesn't produce a bootable entry, so commented out for the moment....
387 // // GRUB in BIOS boot partition:
388 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
389 // Volume->HasBootCode = TRUE;
390 // Volume->OSIconName = L"grub,linux";
391 // Volume->OSName = L"Linux";
392 // Volume->VolName = L"BIOS Boot Partition";
395 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
396 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
397 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
398 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
399 Volume
->HasBootCode
= TRUE
;
400 Volume
->OSIconName
= L
"freebsd";
401 Volume
->OSName
= L
"FreeBSD";
403 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
404 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
405 Volume
->HasBootCode
= TRUE
;
406 Volume
->OSIconName
= L
"openbsd";
407 Volume
->OSName
= L
"OpenBSD";
409 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
410 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
411 Volume
->HasBootCode
= TRUE
;
412 Volume
->OSIconName
= L
"netbsd";
413 Volume
->OSName
= L
"NetBSD";
415 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
416 Volume
->HasBootCode
= TRUE
;
417 Volume
->OSIconName
= L
"win";
418 Volume
->OSName
= L
"Windows";
420 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
421 Volume
->HasBootCode
= TRUE
;
422 Volume
->OSIconName
= L
"winvista,win";
423 Volume
->OSName
= L
"Windows";
425 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
426 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
427 Volume
->HasBootCode
= TRUE
;
428 Volume
->OSIconName
= L
"freedos";
429 Volume
->OSName
= L
"FreeDOS";
431 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
432 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
433 Volume
->HasBootCode
= TRUE
;
434 Volume
->OSIconName
= L
"ecomstation";
435 Volume
->OSName
= L
"eComStation";
437 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
438 Volume
->HasBootCode
= TRUE
;
439 Volume
->OSIconName
= L
"beos";
440 Volume
->OSName
= L
"BeOS";
442 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
443 Volume
->HasBootCode
= TRUE
;
444 Volume
->OSIconName
= L
"zeta,beos";
445 Volume
->OSName
= L
"ZETA";
447 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
448 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
449 Volume
->HasBootCode
= TRUE
;
450 Volume
->OSIconName
= L
"haiku,beos";
451 Volume
->OSName
= L
"Haiku";
455 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
456 // need to fix AddLegacyEntry in main.c.
459 Print(L
" Result of bootcode detection: %s %s (%s)\n",
460 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
461 Volume
->OSName
, Volume
->OSIconName
);
464 // dummy FAT boot sector (created by OS X's newfs_msdos)
465 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
466 Volume
->HasBootCode
= FALSE
;
468 // dummy FAT boot sector (created by Linux's mkdosfs)
469 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
470 Volume
->HasBootCode
= FALSE
;
472 // dummy FAT boot sector (created by Windows)
473 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
474 Volume
->HasBootCode
= FALSE
;
476 // check for MBR partition table
477 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
478 MbrTableFound
= FALSE
;
479 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
480 for (i
= 0; i
< 4; i
++)
481 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
482 MbrTableFound
= TRUE
;
483 for (i
= 0; i
< 4; i
++)
484 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
485 MbrTableFound
= FALSE
;
487 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
488 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
494 CheckError(Status
, L
"while reading boot sector");
499 // default volume badge icon based on disk kind
500 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
502 switch (Volume
->DiskKind
) {
503 case DISK_KIND_INTERNAL
:
504 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
506 case DISK_KIND_EXTERNAL
:
507 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
509 case DISK_KIND_OPTICAL
:
510 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
515 VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
518 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
519 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
520 EFI_HANDLE WholeDiskHandle
;
522 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
526 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
528 if (Volume
->DevicePath
!= NULL
) {
529 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
531 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
536 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
539 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
540 if (EFI_ERROR(Status
)) {
541 Volume
->BlockIO
= NULL
;
542 Print(L
"Warning: Can't get BlockIO protocol.\n");
544 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
545 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
548 // scan for bootcode and MBR table
550 ScanVolumeBootcode(Volume
, &Bootable
);
552 // detect device type
553 DevicePath
= Volume
->DevicePath
;
554 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
555 NextDevicePath
= NextDevicePathNode(DevicePath
);
557 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
558 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
559 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
560 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
561 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
562 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
563 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
564 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
565 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
569 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
570 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
571 // TODO: also check for Boot Camp GUID
572 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
575 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
576 // make a device path for the whole device
577 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
578 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
579 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
580 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
582 // get the handle for that path
583 RemainingDevicePath
= DiskDevicePath
;
584 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
585 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
586 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
587 FreePool(DiskDevicePath
);
589 if (!EFI_ERROR(Status
)) {
590 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
592 // get the device path for later
593 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
594 if (!EFI_ERROR(Status
)) {
595 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
598 // look at the BlockIO protocol
599 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
600 if (!EFI_ERROR(Status
)) {
602 // check the media block size
603 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
604 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
607 Volume
->WholeDiskBlockIO
= NULL
;
608 //CheckError(Status, L"from HandleProtocol");
611 // CheckError(Status, L"from LocateDevicePath");
614 DevicePath
= NextDevicePath
;
619 if (Volume
->HasBootCode
)
620 Print(L
" Volume considered non-bootable, but boot code is present\n");
622 Volume
->HasBootCode
= FALSE
;
625 // default volume icon based on disk kind
626 ScanVolumeDefaultIcon(Volume
);
628 // open the root directory of the volume
629 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
630 if (Volume
->RootDir
== NULL
) {
631 Volume
->IsReadable
= FALSE
;
634 Volume
->IsReadable
= TRUE
;
638 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
639 if (FileSystemInfoPtr
!= NULL
) {
640 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
641 FreePool(FileSystemInfoPtr
);
644 if (Volume
->VolName
== NULL
) {
645 Volume
->VolName
= StrDuplicate(L
"Unknown");
647 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
648 // - name from bytes 3 to 10 of the boot sector
649 // - partition number
650 // - name derived from file system type or partition type
652 // get custom volume icon if present
653 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
654 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
655 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
656 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
660 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
663 REFIT_VOLUME
*Volume
;
664 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
666 UINTN LogicalPartitionIndex
= 4;
667 UINT8 SectorBuffer
[512];
669 MBR_PARTITION_INFO
*EMbrTable
;
671 ExtBase
= MbrEntry
->StartLBA
;
673 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
675 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
676 WholeDiskVolume
->BlockIO
,
677 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
678 ExtCurrent
, 512, SectorBuffer
);
679 if (EFI_ERROR(Status
))
681 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
683 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
685 // scan logical partitions in this EMBR
687 for (i
= 0; i
< 4; i
++) {
688 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
689 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
691 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
692 // set next ExtCurrent
693 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
697 // found a logical partition
698 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
699 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
700 Volume
->IsMbrPartition
= TRUE
;
701 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
702 Volume
->VolName
= AllocateZeroPool(256 * sizeof(UINT16
));
703 SPrint(Volume
->VolName
, 255, L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
704 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
705 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
706 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
709 ScanVolumeBootcode(Volume
, &Bootable
);
711 Volume
->HasBootCode
= FALSE
;
713 ScanVolumeDefaultIcon(Volume
);
715 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
722 VOID
ScanVolumes(VOID
)
725 UINTN HandleCount
= 0;
728 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
729 UINTN VolumeIndex
, VolumeIndex2
;
730 MBR_PARTITION_INFO
*MbrTable
;
731 UINTN PartitionIndex
;
732 UINT8
*SectorBuffer1
, *SectorBuffer2
;
739 // get all filesystem handles
740 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
741 // was: &FileSystemProtocol
742 if (Status
== EFI_NOT_FOUND
) {
743 return; // no filesystems. strange, but true...
745 if (CheckError(Status
, L
"while listing all file systems"))
748 // first pass: collect information about all handles
749 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
750 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
751 Volume
->DeviceHandle
= Handles
[HandleIndex
];
754 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
756 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
761 if (SelfVolume
== NULL
)
762 Print(L
"WARNING: SelfVolume not found");
764 // second pass: relate partitions and whole disk devices
765 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
766 Volume
= Volumes
[VolumeIndex
];
767 // check MBR partition table for extended partitions
768 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
769 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
770 Volume
->MbrPartitionTable
!= NULL
) {
771 MbrTable
= Volume
->MbrPartitionTable
;
772 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
773 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
774 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
779 // search for corresponding whole disk volume entry
780 WholeDiskVolume
= NULL
;
781 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
782 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
783 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
784 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
785 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
786 WholeDiskVolume
= Volumes
[VolumeIndex2
];
790 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
791 // check if this volume is one of the partitions in the table
792 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
793 SectorBuffer1
= AllocatePool(512);
794 SectorBuffer2
= AllocatePool(512);
795 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
797 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
800 // compare boot sector read through offset vs. directly
801 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
802 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
803 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
804 if (EFI_ERROR(Status
))
806 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
807 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
808 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
809 if (EFI_ERROR(Status
))
811 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
814 for (i
= 0; i
< 512; i
++)
815 SectorSum
+= SectorBuffer1
[i
];
816 if (SectorSum
< 1000)
819 // TODO: mark entry as non-bootable if it is an extended partition
821 // now we're reasonably sure the association is correct...
822 Volume
->IsMbrPartition
= TRUE
;
823 Volume
->MbrPartitionIndex
= PartitionIndex
;
824 if (Volume
->VolName
== NULL
) {
825 Volume
->VolName
= AllocateZeroPool(sizeof(CHAR16
) * 256);
826 SPrint(Volume
->VolName
, 255, L
"Partition %d", PartitionIndex
+ 1);
831 MyFreePool(SectorBuffer1
);
832 MyFreePool(SectorBuffer2
);
836 } /* VOID ScanVolumes() */
838 static VOID
UninitVolumes(VOID
)
840 REFIT_VOLUME
*Volume
;
843 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
844 Volume
= Volumes
[VolumeIndex
];
846 if (Volume
->RootDir
!= NULL
) {
847 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
848 Volume
->RootDir
= NULL
;
851 Volume
->DeviceHandle
= NULL
;
852 Volume
->BlockIO
= NULL
;
853 Volume
->WholeDiskBlockIO
= NULL
;
857 VOID
ReinitVolumes(VOID
)
860 REFIT_VOLUME
*Volume
;
862 EFI_DEVICE_PATH
*RemainingDevicePath
;
863 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
865 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
866 Volume
= Volumes
[VolumeIndex
];
868 if (Volume
->DevicePath
!= NULL
) {
869 // get the handle for that path
870 RemainingDevicePath
= Volume
->DevicePath
;
871 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
873 if (!EFI_ERROR(Status
)) {
874 Volume
->DeviceHandle
= DeviceHandle
;
876 // get the root directory
877 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
880 CheckError(Status
, L
"from LocateDevicePath");
883 if (Volume
->WholeDiskDevicePath
!= NULL
) {
884 // get the handle for that path
885 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
886 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
888 if (!EFI_ERROR(Status
)) {
889 // get the BlockIO protocol
890 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
891 if (EFI_ERROR(Status
)) {
892 Volume
->WholeDiskBlockIO
= NULL
;
893 CheckError(Status
, L
"from HandleProtocol");
896 CheckError(Status
, L
"from LocateDevicePath");
902 // file and dir functions
905 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
908 EFI_FILE_HANDLE TestFile
;
910 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
911 if (Status
== EFI_SUCCESS
) {
912 refit_call1_wrapper(TestFile
->Close
, TestFile
);
918 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
922 UINTN LastBufferSize
, BufferSize
;
927 // free pointer from last call
928 if (*DirEntry
!= NULL
) {
933 // read next directory entry
934 LastBufferSize
= BufferSize
= 256;
935 Buffer
= AllocatePool(BufferSize
);
936 for (IterCount
= 0; ; IterCount
++) {
937 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
938 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
940 if (BufferSize
<= LastBufferSize
) {
941 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
942 BufferSize
= LastBufferSize
* 2;
945 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
948 Buffer
= EfiReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
949 LastBufferSize
= BufferSize
;
951 if (EFI_ERROR(Status
)) {
956 // check for end of listing
957 if (BufferSize
== 0) { // end of directory listing
962 // entry is ready to be returned
963 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
966 if (FilterMode
== 1) { // only return directories
967 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
969 } else if (FilterMode
== 2) { // only return files
970 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
972 } else // no filter or unknown filter -> return everything
979 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
981 if (RelativePath
== NULL
) {
982 DirIter
->LastStatus
= EFI_SUCCESS
;
983 DirIter
->DirHandle
= BaseDir
;
984 DirIter
->CloseDirHandle
= FALSE
;
986 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
987 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
989 DirIter
->LastFileInfo
= NULL
;
992 #ifndef __MAKEWITH_GNUEFI
993 EFI_UNICODE_COLLATION_PROTOCOL
*mUnicodeCollation
= NULL
;
996 InitializeUnicodeCollationProtocol (VOID
)
1000 if (mUnicodeCollation
!= NULL
) {
1005 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1006 // instances first and then select one which support English language.
1007 // Current implementation just pick the first instance.
1009 Status
= gBS
->LocateProtocol (
1010 &gEfiUnicodeCollation2ProtocolGuid
,
1012 (VOID
**) &mUnicodeCollation
1014 if (EFI_ERROR(Status
)) {
1015 Status
= gBS
->LocateProtocol (
1016 &gEfiUnicodeCollationProtocolGuid
,
1018 (VOID
**) &mUnicodeCollation
1026 MetaiMatch (IN CHAR16
*String
, IN CHAR16
*Pattern
)
1028 if (!mUnicodeCollation
) {
1029 InitializeUnicodeCollationProtocol();
1031 if (mUnicodeCollation
)
1032 return mUnicodeCollation
->MetaiMatch (mUnicodeCollation
, String
, Pattern
);
1033 return FALSE
; // Shouldn't happen
1036 static VOID
StrLwr (IN OUT CHAR16
*Str
) {
1037 if (!mUnicodeCollation
) {
1038 InitializeUnicodeCollationProtocol();
1040 if (mUnicodeCollation
)
1041 mUnicodeCollation
->StrLwr (mUnicodeCollation
, Str
);
1046 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
1047 OUT EFI_FILE_INFO
**DirEntry
)
1049 BOOLEAN KeepGoing
= TRUE
;
1053 if (DirIter
->LastFileInfo
!= NULL
) {
1054 FreePool(DirIter
->LastFileInfo
);
1055 DirIter
->LastFileInfo
= NULL
;
1058 if (EFI_ERROR(DirIter
->LastStatus
))
1059 return FALSE
; // stop iteration
1062 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
1063 if (EFI_ERROR(DirIter
->LastStatus
))
1065 if (DirIter
->LastFileInfo
== NULL
) // end of listing
1067 if (FilePattern
!= NULL
) {
1068 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
1071 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
1072 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1075 // else continue loop
1078 } while (KeepGoing
);
1080 *DirEntry
= DirIter
->LastFileInfo
;
1084 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1086 if (DirIter
->LastFileInfo
!= NULL
) {
1087 FreePool(DirIter
->LastFileInfo
);
1088 DirIter
->LastFileInfo
= NULL
;
1090 if (DirIter
->CloseDirHandle
)
1091 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1092 return DirIter
->LastStatus
;
1096 // file name manipulation
1099 // Returns the filename portion (minus path name) of the
1101 CHAR16
* Basename(IN CHAR16
*Path
)
1109 for (i
= StrLen(Path
); i
> 0; i
--) {
1110 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1111 FileName
= Path
+ i
;
1120 // Replaces a filename extension of ".efi" with the specified string
1121 // (Extension). If the input Path doesn't end in ".efi", Extension
1122 // is added to the existing filename.
1123 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1127 PathLen
= StrLen(Path
);
1128 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1129 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1130 Path
[PathLen
- 4] = 0;
1132 StrCat(Path
, Extension
);
1133 } // VOID ReplaceEfiExtension()
1136 // memory string search
1139 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1145 BufferLength
-= SearchStringLength
;
1146 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1147 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1148 return (INTN
)Offset
;
1154 // Performs a case-insensitive search of BigStr for SmallStr.
1155 // Returns TRUE if found, FALSE if not.
1156 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1157 CHAR16
*SmallCopy
, *BigCopy
;
1158 BOOLEAN Found
= FALSE
;
1159 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1161 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1162 SmallCopy
= StrDuplicate(SmallStr
);
1163 BigCopy
= StrDuplicate(BigStr
);
1166 SmallLen
= StrLen(SmallCopy
);
1167 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1168 while ((!Found
) && (StartPoint
< NumCompares
)) {
1169 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1171 MyFreePool(SmallCopy
);
1172 MyFreePool(BigCopy
);
1176 } // BOOLEAN StriSubCmp()
1178 // Merges two strings, creating a new one and returning a pointer to it.
1179 // If AddChar != 0, the specified character is placed between the two original
1180 // strings (unless the first string is NULL). The original input string
1181 // *First is de-allocated and replaced by the new merged string.
1182 // This is similar to StrCat, but safer and more flexible because
1183 // MergeStrings allocates memory that's the correct size for the
1184 // new merged string, so it can take a NULL *First and it cleans
1185 // up the old memory. It should *NOT* be used with a constant
1186 // *First, though....
1187 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1188 UINTN Length1
= 0, Length2
= 0;
1192 Length1
= StrLen(*First
);
1194 Length2
= StrLen(Second
);
1195 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1196 if (NewString
!= NULL
) {
1197 NewString
[0] = L
'\0';
1198 if (*First
!= NULL
) {
1199 StrCat(NewString
, *First
);
1201 NewString
[Length1
] = AddChar
;
1202 NewString
[Length1
+ 1] = 0;
1204 } // if (*First != NULL)
1206 StrCat(NewString
, Second
);
1210 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1212 } // static CHAR16* MergeStrings()
1214 // Takes an input pathname (*Path) and returns the part of the filename from
1215 // the final dot onwards, converted to lowercase. If the filename includes
1216 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1217 // The calling function is responsible for freeing the memory associated with
1218 // the return value.
1219 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1221 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1224 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1227 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1228 if (Path
[i
] == L
'.')
1230 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1236 MergeStrings(&Extension
, &Path
[i
], 0);
1241 } // CHAR16 *FindExtension
1243 // Takes an input pathname (*Path) and locates the final directory component
1244 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1245 // function returns the string 'foo'.
1246 // Assumes the pathname is separated with backslashes.
1247 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1248 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1249 CHAR16
*Found
= NULL
;
1251 PathLength
= StrLen(Path
);
1252 // Find start & end of target element
1253 for (i
= 0; i
< PathLength
; i
++) {
1254 if (Path
[i
] == '\\') {
1255 StartOfElement
= EndOfElement
;
1259 // Extract the target element
1260 if (EndOfElement
> 0) {
1261 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1265 if (EndOfElement
>= StartOfElement
) {
1266 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1267 Found
= StrDuplicate(&Path
[StartOfElement
]);
1269 Found
[CopyLength
] = 0;
1270 } // if (EndOfElement >= StartOfElement)
1271 } // if (EndOfElement > 0)
1273 } // CHAR16 *FindLastDirName
1275 // Returns the directory portion of a pathname. For instance,
1276 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1277 // string 'EFI\foo'. The calling function is responsible for
1278 // freeing the returned string's memory.
1279 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1280 UINTN i
, LastBackslash
= 0;
1283 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1284 if (FullPath
[i
] == '\\')
1287 PathOnly
= StrDuplicate(FullPath
);
1288 PathOnly
[LastBackslash
] = 0;
1292 // Splits an EFI device path into device and filename components. For instance, if InString is
1293 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
1294 // this function will truncate that input to
1295 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
1296 // and return bzImage-3.5.1.efi as its return value.
1297 // It does this by searching for the last ")" character in InString, copying everything
1298 // after that string (after some cleanup) as the return value, and truncating the original
1300 // If InString contains no ")" character, this function leaves the original input string
1301 // unmodified and returns a NULL value.
1302 static CHAR16
* SplitDeviceString(IN OUT CHAR16
*InString
) {
1304 CHAR16
*FileName
= NULL
;
1305 BOOLEAN Found
= FALSE
;
1307 i
= StrLen(InString
) - 1;
1308 while ((i
>= 0) && (!Found
)) {
1309 if (InString
[i
] == L
')') {
1311 FileName
= StrDuplicate(&InString
[i
+ 1]);
1312 CleanUpPathNameSlashes(FileName
);
1313 InString
[i
+ 1] = '\0';
1318 } // static CHAR16* SplitDeviceString()
1320 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1321 // DeviceVolume, and returns that and the filename (*loader).
1322 VOID
FindVolumeAndFilename(IN EFI_DEVICE_PATH
*loadpath
, OUT REFIT_VOLUME
**DeviceVolume
, OUT CHAR16
**loader
) {
1323 CHAR16
*DeviceString
, *VolumeDeviceString
, *Temp
;
1325 BOOLEAN Found
= FALSE
;
1327 MyFreePool(*loader
);
1328 MyFreePool(*DeviceVolume
);
1329 *DeviceVolume
= NULL
;
1330 DeviceString
= DevicePathToStr(loadpath
);
1331 *loader
= SplitDeviceString(DeviceString
);
1333 while ((i
< VolumesCount
) && (!Found
)) {
1334 VolumeDeviceString
= DevicePathToStr(Volumes
[i
]->DevicePath
);
1335 Temp
= SplitDeviceString(VolumeDeviceString
);
1336 if (StriCmp(DeviceString
, VolumeDeviceString
) == 0) {
1338 *DeviceVolume
= Volumes
[i
];
1341 MyFreePool(VolumeDeviceString
);
1345 MyFreePool(DeviceString
);
1346 } // VOID FindVolumeAndFilename()
1348 // Returns all the digits in the input string, including intervening
1349 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1350 // this function returns "3.3.4-7". If InString contains no digits,
1351 // the return value is NULL.
1352 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1353 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1354 CHAR16
*Found
= NULL
;
1356 InLength
= StartOfElement
= StrLen(InString
);
1357 // Find start & end of target element
1358 for (i
= 0; i
< InLength
; i
++) {
1359 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1360 if (StartOfElement
> i
)
1362 if (EndOfElement
< i
)
1366 // Extract the target element
1367 if (EndOfElement
> 0) {
1368 if (EndOfElement
>= StartOfElement
) {
1369 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1370 Found
= StrDuplicate(&InString
[StartOfElement
]);
1372 Found
[CopyLength
] = 0;
1373 } // if (EndOfElement >= StartOfElement)
1374 } // if (EndOfElement > 0)
1376 } // CHAR16 *FindNumbers()
1378 // Find the #Index element (numbered from 0) in a comma-delimited string
1380 // Returns the found element, or NULL if Index is out of range or InString
1381 // is NULL. Note that the calling function is responsible for freeing the
1382 // memory associated with the returned string pointer.
1383 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1384 UINTN StartPos
= 0, CurPos
= 0;
1385 BOOLEAN Found
= FALSE
;
1386 CHAR16
*FoundString
= NULL
;
1388 if (InString
!= NULL
) {
1389 // After while() loop, StartPos marks start of item #Index
1390 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1391 if (InString
[CurPos
] == L
',') {
1393 StartPos
= CurPos
+ 1;
1397 // After while() loop, CurPos is one past the end of the element
1398 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1399 if (InString
[CurPos
] == L
',')
1405 FoundString
= StrDuplicate(&InString
[StartPos
]);
1406 if (FoundString
!= NULL
)
1407 FoundString
[CurPos
- StartPos
] = 0;
1409 return (FoundString
);
1410 } // CHAR16 *FindCommaDelimited()
1412 // Returns TRUE if SmallString is an element in the comma-delimited List,
1413 // FALSE otherwise. Performs comparison case-insensitively (except on
1414 // buggy EFIs with case-sensitive StriCmp() functions).
1415 BOOLEAN
IsIn(IN CHAR16
*SmallString
, IN CHAR16
*List
) {
1417 BOOLEAN Found
= FALSE
;
1420 if (SmallString
&& List
) {
1421 while (!Found
&& (OneElement
= FindCommaDelimited(List
, i
++))) {
1422 if (StriCmp(OneElement
, SmallString
) == 0)
1429 // Implement FreePool the way it should have been done to begin with, so that
1430 // it doesn't throw an ASSERT message if fed a NULL pointer....
1431 VOID
MyFreePool(IN OUT VOID
*Pointer
) {
1432 if (Pointer
!= NULL
)
1436 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1438 // Eject all removable media.
1439 // Returns TRUE if any media were ejected, FALSE otherwise.
1440 BOOLEAN
EjectMedia(VOID
) {
1442 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1443 EFI_HANDLE
*Handles
, Handle
;
1444 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1446 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1447 if (EFI_ERROR(Status
) || HandleCount
== 0)
1448 return (FALSE
); // probably not an Apple system
1450 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1451 Handle
= Handles
[HandleIndex
];
1452 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1453 if (EFI_ERROR(Status
))
1455 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1456 if (!EFI_ERROR(Status
))
1459 MyFreePool(Handles
);
1460 return (Ejected
> 0);
1461 } // VOID EjectMedia()
1464 // Return the GUID as a string, suitable for display to the user. Note that the calling
1465 // function is responsible for freeing the allocated memory.
1466 CHAR16
* GuidAsString(EFI_GUID
*GuidData
) {
1469 TheString
= AllocateZeroPool(42 * sizeof(CHAR16
));
1470 if (TheString
!= 0) {
1471 SPrint (TheString
, 82, L
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1472 (UINTN
)GuidData
->Data1
, (UINTN
)GuidData
->Data2
, (UINTN
)GuidData
->Data3
,
1473 (UINTN
)GuidData
->Data4
[0], (UINTN
)GuidData
->Data4
[1], (UINTN
)GuidData
->Data4
[2],
1474 (UINTN
)GuidData
->Data4
[3], (UINTN
)GuidData
->Data4
[4], (UINTN
)GuidData
->Data4
[5],
1475 (UINTN
)GuidData
->Data4
[6], (UINTN
)GuidData
->Data4
[7]);
1478 } // GuidAsString(EFI_GUID *GuidData)