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 "refit_call_wrapper.h"
50 #include "RemovableMedia.h"
54 EFI_HANDLE SelfImageHandle
;
55 EFI_LOADED_IMAGE
*SelfLoadedImage
;
56 EFI_FILE
*SelfRootDir
;
60 REFIT_VOLUME
*SelfVolume
= NULL
;
61 REFIT_VOLUME
**Volumes
= NULL
;
62 UINTN VolumesCount
= 0;
64 // Maximum size for disk sectors
65 #define SECTOR_SIZE 4096
67 // Default names for volume badges (mini-icon to define disk type) and icons
68 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
69 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
73 static EFI_STATUS
FinishInitRefitLib(VOID
);
75 static VOID
UninitVolumes(VOID
);
78 // self recognition stuff
81 // Converts forward slashes to backslashes, removes duplicate slashes, and
82 // removes slashes from both the start and end of the pathname.
83 // Necessary because some (buggy?) EFI implementations produce "\/" strings
84 // in pathnames, because some user inputs can produce duplicate directory
85 // separators, and because we want consistent start and end slashes for
86 // directory comparisons. A special case: If the PathName refers to root,
87 // return "/", since some firmware implementations flake out if this
89 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
91 UINTN i
, FinalChar
= 0;
92 BOOLEAN LastWasSlash
= FALSE
;
94 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 2));
95 if (NewName
!= NULL
) {
96 for (i
= 0; i
< StrLen(PathName
); i
++) {
97 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
98 if ((!LastWasSlash
) && (FinalChar
!= 0))
99 NewName
[FinalChar
++] = L
'\\';
102 NewName
[FinalChar
++] = PathName
[i
];
103 LastWasSlash
= FALSE
;
106 NewName
[FinalChar
] = 0;
107 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
108 NewName
[--FinalChar
] = 0;
109 if (FinalChar
== 0) {
113 // Copy the transformed name back....
114 StrCpy(PathName
, NewName
);
116 } // if allocation OK
117 } // CleanUpPathNameSlashes()
119 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
122 CHAR16
*DevicePathAsString
;
124 SelfImageHandle
= ImageHandle
;
125 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
126 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
127 return EFI_LOAD_ERROR
;
129 // find the current directory
130 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
131 CleanUpPathNameSlashes(DevicePathAsString
);
132 if (SelfDirPath
!= NULL
)
133 FreePool(SelfDirPath
);
134 SelfDirPath
= FindPath(DevicePathAsString
);
135 FreePool(DevicePathAsString
);
137 return FinishInitRefitLib();
140 // called before running external programs to close open file handles
141 VOID
UninitRefitLib(VOID
)
145 if (SelfDir
!= NULL
) {
146 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
150 if (SelfRootDir
!= NULL
) {
151 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
156 // called after running external programs to re-open file handles
157 EFI_STATUS
ReinitRefitLib(VOID
)
161 if ((ST
->Hdr
.Revision
>> 16) == 1) {
162 // Below two lines were in rEFIt, but seem to cause system crashes or
163 // reboots when launching OSes after returning from programs on most
164 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
165 // installation volume" (see the next function) when returning from
166 // programs when these two lines are removed, and it often crashes
167 // when returning from a program or when launching a second program
168 // with these lines removed. Therefore, the preceding if() statement
169 // executes these lines only on EFIs with a major version number of 1
170 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
171 // of hardware on which to test is limited, though, so this may be the
172 // wrong test, or there may be a better way to fix this problem.
173 // TODO: Figure out cause of above weirdness and fix it more
175 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
176 SelfRootDir
= SelfVolume
->RootDir
;
179 return FinishInitRefitLib();
182 static EFI_STATUS
FinishInitRefitLib(VOID
)
186 if (SelfRootDir
== NULL
) {
187 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
188 if (SelfRootDir
== NULL
) {
189 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
190 return EFI_LOAD_ERROR
;
194 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
195 if (CheckFatalError(Status
, L
"while opening our installation directory"))
196 return EFI_LOAD_ERROR
;
205 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
209 *ElementCount
= InitialElementCount
;
210 if (*ElementCount
> 0) {
211 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
212 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
218 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
222 if ((*ElementCount
& 7) == 0) {
223 AllocateCount
= *ElementCount
+ 8;
224 if (*ElementCount
== 0)
225 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
227 *ListPtr
= ReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
229 (*ListPtr
)[*ElementCount
] = NewElement
;
231 } /* VOID AddListElement() */
233 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
237 if (*ElementCount
> 0) {
238 for (i
= 0; i
< *ElementCount
; i
++) {
239 // TODO: call a user-provided routine for each element here
240 FreePool((*ListPtr
)[i
]);
247 // firmware device path discovery
250 static UINT8 LegacyLoaderMediaPathData
[] = {
251 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
252 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
253 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
255 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
257 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
260 UINTN HandleCount
= 0;
261 UINTN HandleIndex
, HardcodedIndex
;
266 EFI_LOADED_IMAGE
*LoadedImage
;
267 EFI_DEVICE_PATH
*DevicePath
;
270 MaxPaths
--; // leave space for the terminating NULL pointer
272 // get all LoadedImage handles
273 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
,
274 &HandleCount
, &Handles
);
275 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
276 if (HardcodedPathList
) {
277 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
278 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
280 PathList
[PathCount
] = NULL
;
283 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
284 Handle
= Handles
[HandleIndex
];
286 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
287 if (EFI_ERROR(Status
))
288 continue; // This can only happen if the firmware scewed up, ignore it.
290 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
291 if (EFI_ERROR(Status
))
292 continue; // This happens, ignore it.
294 // Only grab memory range nodes
295 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
298 // Check if we have this device path in the list already
299 // WARNING: This assumes the first node in the device path is unique!
301 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
302 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
304 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
312 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
316 if (HardcodedPathList
) {
317 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
318 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
320 PathList
[PathCount
] = NULL
;
327 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
330 UINT8 SectorBuffer
[SECTOR_SIZE
];
332 MBR_PARTITION_INFO
*MbrTable
;
333 BOOLEAN MbrTableFound
;
335 Volume
->HasBootCode
= FALSE
;
336 Volume
->OSIconName
= NULL
;
337 Volume
->OSName
= NULL
;
340 if (Volume
->BlockIO
== NULL
)
342 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
343 return; // our buffer is too small...
345 // look at the boot sector (this is used for both hard disks and El Torito images!)
346 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
347 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
348 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
349 if (!EFI_ERROR(Status
)) {
351 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
353 Volume
->HasBootCode
= TRUE
;
356 // detect specific boot codes
357 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
358 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
359 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
360 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
361 Volume
->HasBootCode
= TRUE
;
362 Volume
->OSIconName
= L
"linux";
363 Volume
->OSName
= L
"Linux";
365 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
366 Volume
->HasBootCode
= TRUE
;
367 Volume
->OSIconName
= L
"grub,linux";
368 Volume
->OSName
= L
"Linux";
370 // // Below doesn't produce a bootable entry, so commented out for the moment....
371 // // GRUB in BIOS boot partition:
372 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
373 // Volume->HasBootCode = TRUE;
374 // Volume->OSIconName = L"grub,linux";
375 // Volume->OSName = L"Linux";
376 // Volume->VolName = L"BIOS Boot Partition";
379 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
380 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
381 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
382 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
383 Volume
->HasBootCode
= TRUE
;
384 Volume
->OSIconName
= L
"freebsd";
385 Volume
->OSName
= L
"FreeBSD";
387 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
388 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
389 Volume
->HasBootCode
= TRUE
;
390 Volume
->OSIconName
= L
"openbsd";
391 Volume
->OSName
= L
"OpenBSD";
393 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
394 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
395 Volume
->HasBootCode
= TRUE
;
396 Volume
->OSIconName
= L
"netbsd";
397 Volume
->OSName
= L
"NetBSD";
399 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
400 Volume
->HasBootCode
= TRUE
;
401 Volume
->OSIconName
= L
"win";
402 Volume
->OSName
= L
"Windows";
404 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
405 Volume
->HasBootCode
= TRUE
;
406 Volume
->OSIconName
= L
"winvista,win";
407 Volume
->OSName
= L
"Windows";
409 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
410 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
411 Volume
->HasBootCode
= TRUE
;
412 Volume
->OSIconName
= L
"freedos";
413 Volume
->OSName
= L
"FreeDOS";
415 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
416 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
417 Volume
->HasBootCode
= TRUE
;
418 Volume
->OSIconName
= L
"ecomstation";
419 Volume
->OSName
= L
"eComStation";
421 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
422 Volume
->HasBootCode
= TRUE
;
423 Volume
->OSIconName
= L
"beos";
424 Volume
->OSName
= L
"BeOS";
426 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
427 Volume
->HasBootCode
= TRUE
;
428 Volume
->OSIconName
= L
"zeta,beos";
429 Volume
->OSName
= L
"ZETA";
431 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
432 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
433 Volume
->HasBootCode
= TRUE
;
434 Volume
->OSIconName
= L
"haiku,beos";
435 Volume
->OSName
= L
"Haiku";
439 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
440 // need to fix AddLegacyEntry in main.c.
443 Print(L
" Result of bootcode detection: %s %s (%s)\n",
444 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
445 Volume
->OSName
, Volume
->OSIconName
);
448 // dummy FAT boot sector (created by OS X's newfs_msdos)
449 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
450 Volume
->HasBootCode
= FALSE
;
452 // dummy FAT boot sector (created by Linux's mkdosfs)
453 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
454 Volume
->HasBootCode
= FALSE
;
456 // dummy FAT boot sector (created by Windows)
457 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
458 Volume
->HasBootCode
= FALSE
;
460 // check for MBR partition table
461 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
462 MbrTableFound
= FALSE
;
463 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
464 for (i
= 0; i
< 4; i
++)
465 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
466 MbrTableFound
= TRUE
;
467 for (i
= 0; i
< 4; i
++)
468 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
469 MbrTableFound
= FALSE
;
471 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
472 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
478 CheckError(Status
, L
"while reading boot sector");
483 // default volume badge icon based on disk kind
484 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
486 switch (Volume
->DiskKind
) {
487 case DISK_KIND_INTERNAL
:
488 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
490 case DISK_KIND_EXTERNAL
:
491 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
493 case DISK_KIND_OPTICAL
:
494 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
499 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
502 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
503 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
504 EFI_HANDLE WholeDiskHandle
;
506 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
510 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
512 if (Volume
->DevicePath
!= NULL
) {
513 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
515 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
520 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
523 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
524 if (EFI_ERROR(Status
)) {
525 Volume
->BlockIO
= NULL
;
526 Print(L
"Warning: Can't get BlockIO protocol.\n");
528 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
529 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
532 // scan for bootcode and MBR table
534 ScanVolumeBootcode(Volume
, &Bootable
);
536 // detect device type
537 DevicePath
= Volume
->DevicePath
;
538 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
539 NextDevicePath
= NextDevicePathNode(DevicePath
);
541 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
542 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
543 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
544 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
545 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
546 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
547 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
548 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
549 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
553 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
554 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
555 // TODO: also check for Boot Camp GUID
556 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
559 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
560 // make a device path for the whole device
561 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
562 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
563 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
564 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
566 // get the handle for that path
567 RemainingDevicePath
= DiskDevicePath
;
568 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
569 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
570 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
571 FreePool(DiskDevicePath
);
573 if (!EFI_ERROR(Status
)) {
574 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
576 // get the device path for later
577 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
578 if (!EFI_ERROR(Status
)) {
579 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
582 // look at the BlockIO protocol
583 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
584 if (!EFI_ERROR(Status
)) {
586 // check the media block size
587 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
588 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
591 Volume
->WholeDiskBlockIO
= NULL
;
592 //CheckError(Status, L"from HandleProtocol");
595 // CheckError(Status, L"from LocateDevicePath");
598 DevicePath
= NextDevicePath
;
603 if (Volume
->HasBootCode
)
604 Print(L
" Volume considered non-bootable, but boot code is present\n");
606 Volume
->HasBootCode
= FALSE
;
609 // default volume icon based on disk kind
610 ScanVolumeDefaultIcon(Volume
);
612 // open the root directory of the volume
613 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
614 if (Volume
->RootDir
== NULL
) {
615 Volume
->IsReadable
= FALSE
;
618 Volume
->IsReadable
= TRUE
;
622 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
623 if (FileSystemInfoPtr
!= NULL
) {
624 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
625 FreePool(FileSystemInfoPtr
);
628 if (Volume
->VolName
== NULL
) {
629 Volume
->VolName
= StrDuplicate(L
"Unknown");
631 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
632 // - name from bytes 3 to 10 of the boot sector
633 // - partition number
634 // - name derived from file system type or partition type
636 // get custom volume icon if present
637 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
638 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
639 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
640 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
644 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
647 REFIT_VOLUME
*Volume
;
648 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
650 UINTN LogicalPartitionIndex
= 4;
651 UINT8 SectorBuffer
[512];
653 MBR_PARTITION_INFO
*EMbrTable
;
655 ExtBase
= MbrEntry
->StartLBA
;
657 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
659 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
660 WholeDiskVolume
->BlockIO
,
661 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
662 ExtCurrent
, 512, SectorBuffer
);
663 if (EFI_ERROR(Status
))
665 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
667 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
669 // scan logical partitions in this EMBR
671 for (i
= 0; i
< 4; i
++) {
672 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
673 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
675 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
676 // set next ExtCurrent
677 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
681 // found a logical partition
682 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
683 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
684 Volume
->IsMbrPartition
= TRUE
;
685 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
686 Volume
->VolName
= PoolPrint(L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
687 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
688 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
689 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
692 ScanVolumeBootcode(Volume
, &Bootable
);
694 Volume
->HasBootCode
= FALSE
;
696 ScanVolumeDefaultIcon(Volume
);
698 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
705 VOID
ScanVolumes(VOID
)
708 UINTN HandleCount
= 0;
711 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
712 UINTN VolumeIndex
, VolumeIndex2
;
713 MBR_PARTITION_INFO
*MbrTable
;
714 UINTN PartitionIndex
;
715 UINT8
*SectorBuffer1
, *SectorBuffer2
;
722 // get all filesystem handles
723 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
724 // was: &FileSystemProtocol
725 if (Status
== EFI_NOT_FOUND
)
726 return; // no filesystems. strange, but true...
727 if (CheckError(Status
, L
"while listing all file systems"))
730 // first pass: collect information about all handles
731 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
732 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
733 Volume
->DeviceHandle
= Handles
[HandleIndex
];
736 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
738 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
743 if (SelfVolume
== NULL
)
744 Print(L
"WARNING: SelfVolume not found");
746 // second pass: relate partitions and whole disk devices
747 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
748 Volume
= Volumes
[VolumeIndex
];
749 // check MBR partition table for extended partitions
750 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
751 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
752 Volume
->MbrPartitionTable
!= NULL
) {
753 MbrTable
= Volume
->MbrPartitionTable
;
754 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
755 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
756 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
761 // search for corresponding whole disk volume entry
762 WholeDiskVolume
= NULL
;
763 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
764 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
765 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
766 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
767 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
768 WholeDiskVolume
= Volumes
[VolumeIndex2
];
772 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
773 // check if this volume is one of the partitions in the table
774 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
775 SectorBuffer1
= AllocatePool(512);
776 SectorBuffer2
= AllocatePool(512);
777 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
779 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
782 // compare boot sector read through offset vs. directly
783 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
784 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
785 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
786 if (EFI_ERROR(Status
))
788 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
789 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
790 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
791 if (EFI_ERROR(Status
))
793 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
796 for (i
= 0; i
< 512; i
++)
797 SectorSum
+= SectorBuffer1
[i
];
798 if (SectorSum
< 1000)
801 // TODO: mark entry as non-bootable if it is an extended partition
803 // now we're reasonably sure the association is correct...
804 Volume
->IsMbrPartition
= TRUE
;
805 Volume
->MbrPartitionIndex
= PartitionIndex
;
806 if (Volume
->VolName
== NULL
)
807 Volume
->VolName
= PoolPrint(L
"Partition %d", PartitionIndex
+ 1);
811 FreePool(SectorBuffer1
);
812 FreePool(SectorBuffer2
);
816 } /* VOID ScanVolumes() */
818 static VOID
UninitVolumes(VOID
)
820 REFIT_VOLUME
*Volume
;
823 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
824 Volume
= Volumes
[VolumeIndex
];
826 if (Volume
->RootDir
!= NULL
) {
827 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
828 Volume
->RootDir
= NULL
;
831 Volume
->DeviceHandle
= NULL
;
832 Volume
->BlockIO
= NULL
;
833 Volume
->WholeDiskBlockIO
= NULL
;
837 VOID
ReinitVolumes(VOID
)
840 REFIT_VOLUME
*Volume
;
842 EFI_DEVICE_PATH
*RemainingDevicePath
;
843 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
845 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
846 Volume
= Volumes
[VolumeIndex
];
848 if (Volume
->DevicePath
!= NULL
) {
849 // get the handle for that path
850 RemainingDevicePath
= Volume
->DevicePath
;
851 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
853 if (!EFI_ERROR(Status
)) {
854 Volume
->DeviceHandle
= DeviceHandle
;
856 // get the root directory
857 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
860 CheckError(Status
, L
"from LocateDevicePath");
863 if (Volume
->WholeDiskDevicePath
!= NULL
) {
864 // get the handle for that path
865 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
866 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
868 if (!EFI_ERROR(Status
)) {
869 // get the BlockIO protocol
870 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
871 if (EFI_ERROR(Status
)) {
872 Volume
->WholeDiskBlockIO
= NULL
;
873 CheckError(Status
, L
"from HandleProtocol");
876 CheckError(Status
, L
"from LocateDevicePath");
882 // file and dir functions
885 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
888 EFI_FILE_HANDLE TestFile
;
890 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
891 if (Status
== EFI_SUCCESS
) {
892 refit_call1_wrapper(TestFile
->Close
, TestFile
);
898 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
902 UINTN LastBufferSize
, BufferSize
;
907 // free pointer from last call
908 if (*DirEntry
!= NULL
) {
913 // read next directory entry
914 LastBufferSize
= BufferSize
= 256;
915 Buffer
= AllocatePool(BufferSize
);
916 for (IterCount
= 0; ; IterCount
++) {
917 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
918 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
920 if (BufferSize
<= LastBufferSize
) {
921 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
922 BufferSize
= LastBufferSize
* 2;
925 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
928 Buffer
= ReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
929 LastBufferSize
= BufferSize
;
931 if (EFI_ERROR(Status
)) {
936 // check for end of listing
937 if (BufferSize
== 0) { // end of directory listing
942 // entry is ready to be returned
943 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
946 if (FilterMode
== 1) { // only return directories
947 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
949 } else if (FilterMode
== 2) { // only return files
950 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
952 } else // no filter or unknown filter -> return everything
959 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
961 if (RelativePath
== NULL
) {
962 DirIter
->LastStatus
= EFI_SUCCESS
;
963 DirIter
->DirHandle
= BaseDir
;
964 DirIter
->CloseDirHandle
= FALSE
;
966 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
967 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
969 DirIter
->LastFileInfo
= NULL
;
972 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
973 OUT EFI_FILE_INFO
**DirEntry
)
975 BOOLEAN KeepGoing
= TRUE
;
979 if (DirIter
->LastFileInfo
!= NULL
) {
980 FreePool(DirIter
->LastFileInfo
);
981 DirIter
->LastFileInfo
= NULL
;
984 if (EFI_ERROR(DirIter
->LastStatus
))
985 return FALSE
; // stop iteration
988 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
989 if (EFI_ERROR(DirIter
->LastStatus
))
991 if (DirIter
->LastFileInfo
== NULL
) // end of listing
993 if (FilePattern
!= NULL
) {
994 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
997 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
998 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1001 // else continue loop
1004 } while (KeepGoing
);
1006 *DirEntry
= DirIter
->LastFileInfo
;
1010 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1012 if (DirIter
->LastFileInfo
!= NULL
) {
1013 FreePool(DirIter
->LastFileInfo
);
1014 DirIter
->LastFileInfo
= NULL
;
1016 if (DirIter
->CloseDirHandle
)
1017 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1018 return DirIter
->LastStatus
;
1022 // file name manipulation
1025 // Returns the filename portion (minus path name) of the
1027 CHAR16
* Basename(IN CHAR16
*Path
)
1035 for (i
= StrLen(Path
); i
> 0; i
--) {
1036 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1037 FileName
= Path
+ i
;
1046 // Replaces a filename extension of ".efi" with the specified string
1047 // (Extension). If the input Path doesn't end in ".efi", Extension
1048 // is added to the existing filename.
1049 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1053 PathLen
= StrLen(Path
);
1054 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1055 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1056 Path
[PathLen
- 4] = 0;
1058 StrCat(Path
, Extension
);
1059 } // VOID ReplaceEfiExtension()
1062 // memory string search
1065 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1071 BufferLength
-= SearchStringLength
;
1072 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1073 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1074 return (INTN
)Offset
;
1080 // Performs a case-insensitive search of BigStr for SmallStr.
1081 // Returns TRUE if found, FALSE if not.
1082 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1083 CHAR16
*SmallCopy
, *BigCopy
;
1084 BOOLEAN Found
= FALSE
;
1085 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1087 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1088 SmallCopy
= StrDuplicate(SmallStr
);
1089 BigCopy
= StrDuplicate(BigStr
);
1092 SmallLen
= StrLen(SmallCopy
);
1093 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1094 while ((!Found
) && (StartPoint
< NumCompares
)) {
1095 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1097 FreePool(SmallCopy
);
1102 } // BOOLEAN StriSubCmp()
1104 // Merges two strings, creating a new one and returning a pointer to it.
1105 // If AddChar != 0, the specified character is placed between the two original
1106 // strings (unless the first string is NULL). The original input string
1107 // *First is de-allocated and replaced by the new merged string.
1108 // This is similar to StrCat, but safer and more flexible because
1109 // MergeStrings allocates memory that's the correct size for the
1110 // new merged string, so it can take a NULL *First and it cleans
1111 // up the old memory. It should *NOT* be used with a constant
1112 // *First, though....
1113 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1114 UINTN Length1
= 0, Length2
= 0;
1118 Length1
= StrLen(*First
);
1120 Length2
= StrLen(Second
);
1121 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1122 if (NewString
!= NULL
) {
1123 NewString
[0] = L
'\0';
1124 if (*First
!= NULL
) {
1125 StrCat(NewString
, *First
);
1127 NewString
[Length1
] = AddChar
;
1128 NewString
[Length1
+ 1] = 0;
1130 } // if (*First != NULL)
1132 StrCat(NewString
, Second
);
1136 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1138 } // static CHAR16* MergeStrings()
1140 // Takes an input pathname (*Path) and returns the part of the filename from
1141 // the final dot onwards, converted to lowercase. If the filename includes
1142 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1143 // The calling function is responsible for freeing the memory associated with
1144 // the return value.
1145 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1147 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1150 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1153 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1154 if (Path
[i
] == L
'.')
1156 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1162 MergeStrings(&Extension
, &Path
[i
], 0);
1167 } // CHAR16 *FindExtension
1169 // Takes an input pathname (*Path) and locates the final directory component
1170 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1171 // function returns the string 'foo'.
1172 // Assumes the pathname is separated with backslashes.
1173 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1174 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1175 CHAR16
*Found
= NULL
;
1177 PathLength
= StrLen(Path
);
1178 // Find start & end of target element
1179 for (i
= 0; i
< PathLength
; i
++) {
1180 if (Path
[i
] == '\\') {
1181 StartOfElement
= EndOfElement
;
1185 // Extract the target element
1186 if (EndOfElement
> 0) {
1187 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1191 if (EndOfElement
>= StartOfElement
) {
1192 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1193 Found
= StrDuplicate(&Path
[StartOfElement
]);
1195 Found
[CopyLength
] = 0;
1196 } // if (EndOfElement >= StartOfElement)
1197 } // if (EndOfElement > 0)
1199 } // CHAR16 *FindLastDirName
1201 // Returns the directory portion of a pathname. For instance,
1202 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1203 // string 'EFI\foo'.
1204 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1205 UINTN i
, LastBackslash
= 0;
1208 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1209 if (FullPath
[i
] == '\\')
1212 PathOnly
= StrDuplicate(FullPath
);
1213 PathOnly
[LastBackslash
] = 0;
1217 // Returns all the digits in the input string, including intervening
1218 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1219 // this function returns "3.3.4-7". If InString contains no digits,
1220 // the return value is NULL.
1221 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1222 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1223 CHAR16
*Found
= NULL
;
1225 InLength
= StartOfElement
= StrLen(InString
);
1226 // Find start & end of target element
1227 for (i
= 0; i
< InLength
; i
++) {
1228 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1229 if (StartOfElement
> i
)
1231 if (EndOfElement
< i
)
1235 // Extract the target element
1236 if (EndOfElement
> 0) {
1237 if (EndOfElement
>= StartOfElement
) {
1238 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1239 Found
= StrDuplicate(&InString
[StartOfElement
]);
1241 Found
[CopyLength
] = 0;
1242 } // if (EndOfElement >= StartOfElement)
1243 } // if (EndOfElement > 0)
1245 } // CHAR16 *FindNumbers()
1247 // Find the #Index element (numbered from 0) in a comma-delimited string
1249 // Returns the found element, or NULL if Index is out of range or InString
1250 // is NULL. Note that the calling function is responsible for freeing the
1251 // memory associated with the returned string pointer.
1252 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1253 UINTN StartPos
= 0, CurPos
= 0;
1254 BOOLEAN Found
= FALSE
;
1255 CHAR16
*FoundString
= NULL
;
1257 if (InString
!= NULL
) {
1258 // After while() loop, StartPos marks start of item #Index
1259 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1260 if (InString
[CurPos
] == L
',') {
1262 StartPos
= CurPos
+ 1;
1266 // After while() loop, CurPos is one past the end of the element
1267 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1268 if (InString
[CurPos
] == L
',')
1274 FoundString
= StrDuplicate(&InString
[StartPos
]);
1275 if (FoundString
!= NULL
)
1276 FoundString
[CurPos
- StartPos
] = 0;
1278 return (FoundString
);
1279 } // CHAR16 *FindCommaDelimited()
1282 static EFI_GUID AppleRemovableMediaGuid
= APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID
;
1284 // Eject all removable media.
1285 // Returns TRUE if any media were ejected, FALSE otherwise.
1286 BOOLEAN
EjectMedia(VOID
) {
1288 UINTN HandleIndex
, HandleCount
= 0, Ejected
= 0;
1289 EFI_HANDLE
*Handles
, Handle
;
1290 APPLE_REMOVABLE_MEDIA_PROTOCOL
*Ejectable
;
1292 Status
= LibLocateHandle(ByProtocol
, &AppleRemovableMediaGuid
, NULL
, &HandleCount
, &Handles
);
1293 if (EFI_ERROR(Status
) || HandleCount
== 0)
1294 return (FALSE
); // probably not an Apple system
1296 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1297 Handle
= Handles
[HandleIndex
];
1298 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &AppleRemovableMediaGuid
, (VOID
**) &Ejectable
);
1299 if (EFI_ERROR(Status
))
1301 Status
= refit_call1_wrapper(Ejectable
->Eject
, Ejectable
);
1302 if (!EFI_ERROR(Status
))
1306 return (Ejected
> 0);
1307 } // VOID EjectMedia()