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"
53 EFI_HANDLE SelfImageHandle
;
54 EFI_LOADED_IMAGE
*SelfLoadedImage
;
55 EFI_FILE
*SelfRootDir
;
59 REFIT_VOLUME
*SelfVolume
= NULL
;
60 REFIT_VOLUME
**Volumes
= NULL
;
61 UINTN VolumesCount
= 0;
63 // Maximum size for disk sectors
64 #define SECTOR_SIZE 4096
66 // Default names for volume badges (mini-icon to define disk type) and icons
67 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
68 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
72 static EFI_STATUS
FinishInitRefitLib(VOID
);
74 static VOID
UninitVolumes(VOID
);
77 // self recognition stuff
80 // Converts forward slashes to backslashes, removes duplicate slashes, and
81 // removes slashes from both the start and end of the pathname.
82 // Necessary because some (buggy?) EFI implementations produce "\/" strings
83 // in pathnames, because some user inputs can produce duplicate directory
84 // separators, and because we want consistent start and end slashes for
85 // directory comparisons. A special case: If the PathName refers to root,
86 // return "/", since some firmware implementations flake out if this
88 VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
90 UINTN i
, FinalChar
= 0;
91 BOOLEAN LastWasSlash
= FALSE
;
93 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 2));
94 if (NewName
!= NULL
) {
95 for (i
= 0; i
< StrLen(PathName
); i
++) {
96 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
97 if ((!LastWasSlash
) && (FinalChar
!= 0))
98 NewName
[FinalChar
++] = L
'\\';
101 NewName
[FinalChar
++] = PathName
[i
];
102 LastWasSlash
= FALSE
;
105 NewName
[FinalChar
] = 0;
106 if ((FinalChar
> 0) && (NewName
[FinalChar
- 1] == L
'\\'))
107 NewName
[--FinalChar
] = 0;
108 if (FinalChar
== 0) {
112 // Copy the transformed name back....
113 StrCpy(PathName
, NewName
);
115 } // if allocation OK
116 } // CleanUpPathNameSlashes()
118 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
121 CHAR16
*DevicePathAsString
;
123 SelfImageHandle
= ImageHandle
;
124 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
125 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
126 return EFI_LOAD_ERROR
;
128 // find the current directory
129 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
130 CleanUpPathNameSlashes(DevicePathAsString
);
131 if (SelfDirPath
!= NULL
)
132 FreePool(SelfDirPath
);
133 SelfDirPath
= FindPath(DevicePathAsString
);
134 FreePool(DevicePathAsString
);
136 return FinishInitRefitLib();
139 // called before running external programs to close open file handles
140 VOID
UninitRefitLib(VOID
)
144 if (SelfDir
!= NULL
) {
145 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
149 if (SelfRootDir
!= NULL
) {
150 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
155 // called after running external programs to re-open file handles
156 EFI_STATUS
ReinitRefitLib(VOID
)
160 if ((ST
->Hdr
.Revision
>> 16) == 1) {
161 // Below two lines were in rEFIt, but seem to cause system crashes or
162 // reboots when launching OSes after returning from programs on most
163 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
164 // installation volume" (see the next function) when returning from
165 // programs when these two lines are removed, and it often crashes
166 // when returning from a program or when launching a second program
167 // with these lines removed. Therefore, the preceding if() statement
168 // executes these lines only on EFIs with a major version number of 1
169 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
170 // of hardware on which to test is limited, though, so this may be the
171 // wrong test, or there may be a better way to fix this problem.
172 // TODO: Figure out cause of above weirdness and fix it more
174 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
175 SelfRootDir
= SelfVolume
->RootDir
;
178 return FinishInitRefitLib();
181 static EFI_STATUS
FinishInitRefitLib(VOID
)
185 if (SelfRootDir
== NULL
) {
186 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
187 if (SelfRootDir
== NULL
) {
188 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
189 return EFI_LOAD_ERROR
;
193 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
194 if (CheckFatalError(Status
, L
"while opening our installation directory"))
195 return EFI_LOAD_ERROR
;
204 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
208 *ElementCount
= InitialElementCount
;
209 if (*ElementCount
> 0) {
210 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
211 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
217 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
221 if ((*ElementCount
& 7) == 0) {
222 AllocateCount
= *ElementCount
+ 8;
223 if (*ElementCount
== 0)
224 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
226 *ListPtr
= ReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
228 (*ListPtr
)[*ElementCount
] = NewElement
;
230 } /* VOID AddListElement() */
232 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
236 if (*ElementCount
> 0) {
237 for (i
= 0; i
< *ElementCount
; i
++) {
238 // TODO: call a user-provided routine for each element here
239 FreePool((*ListPtr
)[i
]);
246 // firmware device path discovery
249 static UINT8 LegacyLoaderMediaPathData
[] = {
250 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
251 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
252 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
254 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
256 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
259 UINTN HandleCount
= 0;
260 UINTN HandleIndex
, HardcodedIndex
;
265 EFI_LOADED_IMAGE
*LoadedImage
;
266 EFI_DEVICE_PATH
*DevicePath
;
269 MaxPaths
--; // leave space for the terminating NULL pointer
271 // get all LoadedImage handles
272 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
,
273 &HandleCount
, &Handles
);
274 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
275 if (HardcodedPathList
) {
276 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
277 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
279 PathList
[PathCount
] = NULL
;
282 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
283 Handle
= Handles
[HandleIndex
];
285 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
286 if (EFI_ERROR(Status
))
287 continue; // This can only happen if the firmware scewed up, ignore it.
289 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
290 if (EFI_ERROR(Status
))
291 continue; // This happens, ignore it.
293 // Only grab memory range nodes
294 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
297 // Check if we have this device path in the list already
298 // WARNING: This assumes the first node in the device path is unique!
300 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
301 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
303 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
311 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
315 if (HardcodedPathList
) {
316 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
317 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
319 PathList
[PathCount
] = NULL
;
326 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
329 UINT8 SectorBuffer
[SECTOR_SIZE
];
331 MBR_PARTITION_INFO
*MbrTable
;
332 BOOLEAN MbrTableFound
;
334 Volume
->HasBootCode
= FALSE
;
335 Volume
->OSIconName
= NULL
;
336 Volume
->OSName
= NULL
;
339 if (Volume
->BlockIO
== NULL
)
341 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
342 return; // our buffer is too small...
344 // look at the boot sector (this is used for both hard disks and El Torito images!)
345 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
346 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
347 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
348 if (!EFI_ERROR(Status
)) {
350 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
352 Volume
->HasBootCode
= TRUE
;
355 // detect specific boot codes
356 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
357 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
358 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
359 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
360 Volume
->HasBootCode
= TRUE
;
361 Volume
->OSIconName
= L
"linux";
362 Volume
->OSName
= L
"Linux";
364 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
365 Volume
->HasBootCode
= TRUE
;
366 Volume
->OSIconName
= L
"grub,linux";
367 Volume
->OSName
= L
"Linux";
369 // // Below doesn't produce a bootable entry, so commented out for the moment....
370 // // GRUB in BIOS boot partition:
371 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
372 // Volume->HasBootCode = TRUE;
373 // Volume->OSIconName = L"grub,linux";
374 // Volume->OSName = L"Linux";
375 // Volume->VolName = L"BIOS Boot Partition";
378 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
379 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
380 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
381 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
382 Volume
->HasBootCode
= TRUE
;
383 Volume
->OSIconName
= L
"freebsd";
384 Volume
->OSName
= L
"FreeBSD";
386 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
387 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
388 Volume
->HasBootCode
= TRUE
;
389 Volume
->OSIconName
= L
"openbsd";
390 Volume
->OSName
= L
"OpenBSD";
392 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
393 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
394 Volume
->HasBootCode
= TRUE
;
395 Volume
->OSIconName
= L
"netbsd";
396 Volume
->OSName
= L
"NetBSD";
398 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
399 Volume
->HasBootCode
= TRUE
;
400 Volume
->OSIconName
= L
"win";
401 Volume
->OSName
= L
"Windows";
403 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
404 Volume
->HasBootCode
= TRUE
;
405 Volume
->OSIconName
= L
"winvista,win";
406 Volume
->OSName
= L
"Windows";
408 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
409 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
410 Volume
->HasBootCode
= TRUE
;
411 Volume
->OSIconName
= L
"freedos";
412 Volume
->OSName
= L
"FreeDOS";
414 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
415 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
416 Volume
->HasBootCode
= TRUE
;
417 Volume
->OSIconName
= L
"ecomstation";
418 Volume
->OSName
= L
"eComStation";
420 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
421 Volume
->HasBootCode
= TRUE
;
422 Volume
->OSIconName
= L
"beos";
423 Volume
->OSName
= L
"BeOS";
425 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
426 Volume
->HasBootCode
= TRUE
;
427 Volume
->OSIconName
= L
"zeta,beos";
428 Volume
->OSName
= L
"ZETA";
430 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
431 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
432 Volume
->HasBootCode
= TRUE
;
433 Volume
->OSIconName
= L
"haiku,beos";
434 Volume
->OSName
= L
"Haiku";
438 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
439 // need to fix AddLegacyEntry in main.c.
442 Print(L
" Result of bootcode detection: %s %s (%s)\n",
443 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
444 Volume
->OSName
, Volume
->OSIconName
);
447 // dummy FAT boot sector (created by OS X's newfs_msdos)
448 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0)
449 Volume
->HasBootCode
= FALSE
;
451 // dummy FAT boot sector (created by Linux's mkdosfs)
452 if (FindMem(SectorBuffer
, 512, "This is not a bootable disk", 27) >= 0)
453 Volume
->HasBootCode
= FALSE
;
455 // dummy FAT boot sector (created by Windows)
456 if (FindMem(SectorBuffer
, 512, "Press any key to restart", 24) >= 0)
457 Volume
->HasBootCode
= FALSE
;
459 // check for MBR partition table
460 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
461 MbrTableFound
= FALSE
;
462 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
463 for (i
= 0; i
< 4; i
++)
464 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
465 MbrTableFound
= TRUE
;
466 for (i
= 0; i
< 4; i
++)
467 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
468 MbrTableFound
= FALSE
;
470 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
471 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
477 CheckError(Status
, L
"while reading boot sector");
482 // default volume badge icon based on disk kind
483 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
485 switch (Volume
->DiskKind
) {
486 case DISK_KIND_INTERNAL
:
487 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
489 case DISK_KIND_EXTERNAL
:
490 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
492 case DISK_KIND_OPTICAL
:
493 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
498 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
501 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
502 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
503 EFI_HANDLE WholeDiskHandle
;
505 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
509 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
511 if (Volume
->DevicePath
!= NULL
) {
512 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
514 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
519 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
522 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
523 if (EFI_ERROR(Status
)) {
524 Volume
->BlockIO
= NULL
;
525 Print(L
"Warning: Can't get BlockIO protocol.\n");
527 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
528 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
531 // scan for bootcode and MBR table
533 ScanVolumeBootcode(Volume
, &Bootable
);
535 // detect device type
536 DevicePath
= Volume
->DevicePath
;
537 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
538 NextDevicePath
= NextDevicePathNode(DevicePath
);
540 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
541 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
542 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
543 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
544 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
545 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
546 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
547 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
548 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
552 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
553 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
554 // TODO: also check for Boot Camp GUID
555 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
558 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
559 // make a device path for the whole device
560 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
561 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
562 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
563 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
565 // get the handle for that path
566 RemainingDevicePath
= DiskDevicePath
;
567 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
568 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
569 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
570 FreePool(DiskDevicePath
);
572 if (!EFI_ERROR(Status
)) {
573 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
575 // get the device path for later
576 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
577 if (!EFI_ERROR(Status
)) {
578 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
581 // look at the BlockIO protocol
582 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
583 if (!EFI_ERROR(Status
)) {
585 // check the media block size
586 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
587 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
590 Volume
->WholeDiskBlockIO
= NULL
;
591 //CheckError(Status, L"from HandleProtocol");
594 // CheckError(Status, L"from LocateDevicePath");
597 DevicePath
= NextDevicePath
;
602 if (Volume
->HasBootCode
)
603 Print(L
" Volume considered non-bootable, but boot code is present\n");
605 Volume
->HasBootCode
= FALSE
;
608 // default volume icon based on disk kind
609 ScanVolumeDefaultIcon(Volume
);
611 // open the root directory of the volume
612 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
613 if (Volume
->RootDir
== NULL
) {
614 Volume
->IsReadable
= FALSE
;
617 Volume
->IsReadable
= TRUE
;
621 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
622 if (FileSystemInfoPtr
!= NULL
) {
623 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
624 FreePool(FileSystemInfoPtr
);
627 if (Volume
->VolName
== NULL
) {
628 Volume
->VolName
= StrDuplicate(L
"Unknown");
630 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
631 // - name from bytes 3 to 10 of the boot sector
632 // - partition number
633 // - name derived from file system type or partition type
635 // get custom volume icon if present
636 if (FileExists(Volume
->RootDir
, VOLUME_BADGE_NAME
))
637 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, VOLUME_BADGE_NAME
, 32);
638 if (FileExists(Volume
->RootDir
, VOLUME_ICON_NAME
)) {
639 Volume
->VolIconImage
= LoadIcns(Volume
->RootDir
, VOLUME_ICON_NAME
, 128);
643 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
646 REFIT_VOLUME
*Volume
;
647 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
649 UINTN LogicalPartitionIndex
= 4;
650 UINT8 SectorBuffer
[512];
652 MBR_PARTITION_INFO
*EMbrTable
;
654 ExtBase
= MbrEntry
->StartLBA
;
656 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
658 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
659 WholeDiskVolume
->BlockIO
,
660 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
661 ExtCurrent
, 512, SectorBuffer
);
662 if (EFI_ERROR(Status
))
664 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
666 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
668 // scan logical partitions in this EMBR
670 for (i
= 0; i
< 4; i
++) {
671 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
672 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
674 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
675 // set next ExtCurrent
676 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
680 // found a logical partition
681 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
682 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
683 Volume
->IsMbrPartition
= TRUE
;
684 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
685 Volume
->VolName
= PoolPrint(L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
686 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
687 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
688 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
691 ScanVolumeBootcode(Volume
, &Bootable
);
693 Volume
->HasBootCode
= FALSE
;
695 ScanVolumeDefaultIcon(Volume
);
697 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
704 VOID
ScanVolumes(VOID
)
707 UINTN HandleCount
= 0;
710 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
711 UINTN VolumeIndex
, VolumeIndex2
;
712 MBR_PARTITION_INFO
*MbrTable
;
713 UINTN PartitionIndex
;
714 UINT8
*SectorBuffer1
, *SectorBuffer2
;
721 // get all filesystem handles
722 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
723 // was: &FileSystemProtocol
724 if (Status
== EFI_NOT_FOUND
)
725 return; // no filesystems. strange, but true...
726 if (CheckError(Status
, L
"while listing all file systems"))
729 // first pass: collect information about all handles
730 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
731 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
732 Volume
->DeviceHandle
= Handles
[HandleIndex
];
735 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
737 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
742 if (SelfVolume
== NULL
)
743 Print(L
"WARNING: SelfVolume not found");
745 // second pass: relate partitions and whole disk devices
746 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
747 Volume
= Volumes
[VolumeIndex
];
748 // check MBR partition table for extended partitions
749 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
750 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
751 Volume
->MbrPartitionTable
!= NULL
) {
752 MbrTable
= Volume
->MbrPartitionTable
;
753 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
754 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
755 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
760 // search for corresponding whole disk volume entry
761 WholeDiskVolume
= NULL
;
762 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
763 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
764 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
765 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
766 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
767 WholeDiskVolume
= Volumes
[VolumeIndex2
];
771 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
772 // check if this volume is one of the partitions in the table
773 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
774 SectorBuffer1
= AllocatePool(512);
775 SectorBuffer2
= AllocatePool(512);
776 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
778 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
781 // compare boot sector read through offset vs. directly
782 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
783 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
784 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
785 if (EFI_ERROR(Status
))
787 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
788 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
789 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
790 if (EFI_ERROR(Status
))
792 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
795 for (i
= 0; i
< 512; i
++)
796 SectorSum
+= SectorBuffer1
[i
];
797 if (SectorSum
< 1000)
800 // TODO: mark entry as non-bootable if it is an extended partition
802 // now we're reasonably sure the association is correct...
803 Volume
->IsMbrPartition
= TRUE
;
804 Volume
->MbrPartitionIndex
= PartitionIndex
;
805 if (Volume
->VolName
== NULL
)
806 Volume
->VolName
= PoolPrint(L
"Partition %d", PartitionIndex
+ 1);
810 FreePool(SectorBuffer1
);
811 FreePool(SectorBuffer2
);
815 } /* VOID ScanVolumes() */
817 static VOID
UninitVolumes(VOID
)
819 REFIT_VOLUME
*Volume
;
822 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
823 Volume
= Volumes
[VolumeIndex
];
825 if (Volume
->RootDir
!= NULL
) {
826 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
827 Volume
->RootDir
= NULL
;
830 Volume
->DeviceHandle
= NULL
;
831 Volume
->BlockIO
= NULL
;
832 Volume
->WholeDiskBlockIO
= NULL
;
836 VOID
ReinitVolumes(VOID
)
839 REFIT_VOLUME
*Volume
;
841 EFI_DEVICE_PATH
*RemainingDevicePath
;
842 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
844 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
845 Volume
= Volumes
[VolumeIndex
];
847 if (Volume
->DevicePath
!= NULL
) {
848 // get the handle for that path
849 RemainingDevicePath
= Volume
->DevicePath
;
850 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
852 if (!EFI_ERROR(Status
)) {
853 Volume
->DeviceHandle
= DeviceHandle
;
855 // get the root directory
856 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
859 CheckError(Status
, L
"from LocateDevicePath");
862 if (Volume
->WholeDiskDevicePath
!= NULL
) {
863 // get the handle for that path
864 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
865 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
867 if (!EFI_ERROR(Status
)) {
868 // get the BlockIO protocol
869 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
870 if (EFI_ERROR(Status
)) {
871 Volume
->WholeDiskBlockIO
= NULL
;
872 CheckError(Status
, L
"from HandleProtocol");
875 CheckError(Status
, L
"from LocateDevicePath");
881 // file and dir functions
884 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
887 EFI_FILE_HANDLE TestFile
;
889 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
890 if (Status
== EFI_SUCCESS
) {
891 refit_call1_wrapper(TestFile
->Close
, TestFile
);
897 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
901 UINTN LastBufferSize
, BufferSize
;
906 // free pointer from last call
907 if (*DirEntry
!= NULL
) {
912 // read next directory entry
913 LastBufferSize
= BufferSize
= 256;
914 Buffer
= AllocatePool(BufferSize
);
915 for (IterCount
= 0; ; IterCount
++) {
916 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
917 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
919 if (BufferSize
<= LastBufferSize
) {
920 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
921 BufferSize
= LastBufferSize
* 2;
924 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
927 Buffer
= ReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
928 LastBufferSize
= BufferSize
;
930 if (EFI_ERROR(Status
)) {
935 // check for end of listing
936 if (BufferSize
== 0) { // end of directory listing
941 // entry is ready to be returned
942 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
945 if (FilterMode
== 1) { // only return directories
946 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
948 } else if (FilterMode
== 2) { // only return files
949 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
951 } else // no filter or unknown filter -> return everything
958 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
960 if (RelativePath
== NULL
) {
961 DirIter
->LastStatus
= EFI_SUCCESS
;
962 DirIter
->DirHandle
= BaseDir
;
963 DirIter
->CloseDirHandle
= FALSE
;
965 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
966 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
968 DirIter
->LastFileInfo
= NULL
;
971 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
972 OUT EFI_FILE_INFO
**DirEntry
)
974 BOOLEAN KeepGoing
= TRUE
;
978 if (DirIter
->LastFileInfo
!= NULL
) {
979 FreePool(DirIter
->LastFileInfo
);
980 DirIter
->LastFileInfo
= NULL
;
983 if (EFI_ERROR(DirIter
->LastStatus
))
984 return FALSE
; // stop iteration
987 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
988 if (EFI_ERROR(DirIter
->LastStatus
))
990 if (DirIter
->LastFileInfo
== NULL
) // end of listing
992 if (FilePattern
!= NULL
) {
993 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
996 while (KeepGoing
&& (OnePattern
= FindCommaDelimited(FilePattern
, i
++)) != NULL
) {
997 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, OnePattern
))
1000 // else continue loop
1003 } while (KeepGoing
);
1005 *DirEntry
= DirIter
->LastFileInfo
;
1009 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
1011 if (DirIter
->LastFileInfo
!= NULL
) {
1012 FreePool(DirIter
->LastFileInfo
);
1013 DirIter
->LastFileInfo
= NULL
;
1015 if (DirIter
->CloseDirHandle
)
1016 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
1017 return DirIter
->LastStatus
;
1021 // file name manipulation
1024 // Returns the filename portion (minus path name) of the
1026 CHAR16
* Basename(IN CHAR16
*Path
)
1034 for (i
= StrLen(Path
); i
> 0; i
--) {
1035 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
1036 FileName
= Path
+ i
;
1045 // Replaces a filename extension of ".efi" with the specified string
1046 // (Extension). If the input Path doesn't end in ".efi", Extension
1047 // is added to the existing filename.
1048 VOID
ReplaceEfiExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
1052 PathLen
= StrLen(Path
);
1053 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1054 if ((PathLen
>= 4) && ((StriCmp(&Path
[PathLen
- 4], L
".efi") == 0) || (StriCmp(&Path
[PathLen
- 4], L
".EFI") == 0))) {
1055 Path
[PathLen
- 4] = 0;
1057 StrCat(Path
, Extension
);
1058 } // VOID ReplaceEfiExtension()
1061 // memory string search
1064 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1070 BufferLength
-= SearchStringLength
;
1071 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1072 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1073 return (INTN
)Offset
;
1079 // Performs a case-insensitive search of BigStr for SmallStr.
1080 // Returns TRUE if found, FALSE if not.
1081 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1082 CHAR16
*SmallCopy
, *BigCopy
;
1083 BOOLEAN Found
= FALSE
;
1084 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1086 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1087 SmallCopy
= StrDuplicate(SmallStr
);
1088 BigCopy
= StrDuplicate(BigStr
);
1091 SmallLen
= StrLen(SmallCopy
);
1092 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1093 while ((!Found
) && (StartPoint
< NumCompares
)) {
1094 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1096 FreePool(SmallCopy
);
1101 } // BOOLEAN StriSubCmp()
1103 // Merges two strings, creating a new one and returning a pointer to it.
1104 // If AddChar != 0, the specified character is placed between the two original
1105 // strings (unless the first string is NULL). The original input string
1106 // *First is de-allocated and replaced by the new merged string.
1107 // This is similar to StrCat, but safer and more flexible because
1108 // MergeStrings allocates memory that's the correct size for the
1109 // new merged string, so it can take a NULL *First and it cleans
1110 // up the old memory. It should *NOT* be used with a constant
1111 // *First, though....
1112 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1113 UINTN Length1
= 0, Length2
= 0;
1117 Length1
= StrLen(*First
);
1119 Length2
= StrLen(Second
);
1120 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1121 if (NewString
!= NULL
) {
1122 NewString
[0] = L
'\0';
1123 if (*First
!= NULL
) {
1124 StrCat(NewString
, *First
);
1126 NewString
[Length1
] = AddChar
;
1127 NewString
[Length1
+ 1] = 0;
1129 } // if (*First != NULL)
1131 StrCat(NewString
, Second
);
1135 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1137 } // static CHAR16* MergeStrings()
1139 // Takes an input pathname (*Path) and returns the part of the filename from
1140 // the final dot onwards, converted to lowercase. If the filename includes
1141 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1142 // The calling function is responsible for freeing the memory associated with
1143 // the return value.
1144 CHAR16
*FindExtension(IN CHAR16
*Path
) {
1146 BOOLEAN Found
= FALSE
, FoundSlash
= FALSE
;
1149 Extension
= AllocateZeroPool(sizeof(CHAR16
));
1152 while ((!Found
) && (!FoundSlash
) && (i
>= 0)) {
1153 if (Path
[i
] == L
'.')
1155 else if ((Path
[i
] == L
'/') || (Path
[i
] == L
'\\'))
1161 MergeStrings(&Extension
, &Path
[i
], 0);
1166 } // CHAR16 *FindExtension
1168 // Takes an input pathname (*Path) and locates the final directory component
1169 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1170 // function returns the string 'foo'.
1171 // Assumes the pathname is separated with backslashes.
1172 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1173 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1174 CHAR16
*Found
= NULL
;
1176 PathLength
= StrLen(Path
);
1177 // Find start & end of target element
1178 for (i
= 0; i
< PathLength
; i
++) {
1179 if (Path
[i
] == '\\') {
1180 StartOfElement
= EndOfElement
;
1184 // Extract the target element
1185 if (EndOfElement
> 0) {
1186 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1190 if (EndOfElement
>= StartOfElement
) {
1191 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1192 Found
= StrDuplicate(&Path
[StartOfElement
]);
1194 Found
[CopyLength
] = 0;
1195 } // if (EndOfElement >= StartOfElement)
1196 } // if (EndOfElement > 0)
1198 } // CHAR16 *FindLastDirName
1200 // Returns the directory portion of a pathname. For instance,
1201 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1202 // string 'EFI\foo'.
1203 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1204 UINTN i
, LastBackslash
= 0;
1207 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1208 if (FullPath
[i
] == '\\')
1211 PathOnly
= StrDuplicate(FullPath
);
1212 PathOnly
[LastBackslash
] = 0;
1216 // Returns all the digits in the input string, including intervening
1217 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1218 // this function returns "3.3.4-7". If InString contains no digits,
1219 // the return value is NULL.
1220 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1221 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1222 CHAR16
*Found
= NULL
;
1224 InLength
= StartOfElement
= StrLen(InString
);
1225 // Find start & end of target element
1226 for (i
= 0; i
< InLength
; i
++) {
1227 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1228 if (StartOfElement
> i
)
1230 if (EndOfElement
< i
)
1234 // Extract the target element
1235 if (EndOfElement
> 0) {
1236 if (EndOfElement
>= StartOfElement
) {
1237 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1238 Found
= StrDuplicate(&InString
[StartOfElement
]);
1240 Found
[CopyLength
] = 0;
1241 } // if (EndOfElement >= StartOfElement)
1242 } // if (EndOfElement > 0)
1244 } // CHAR16 *FindNumbers()
1246 // Find the #Index element (numbered from 0) in a comma-delimited string
1248 // Returns the found element, or NULL if Index is out of range or InString
1249 // is NULL. Note that the calling function is responsible for freeing the
1250 // memory associated with the returned string pointer.
1251 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1252 UINTN StartPos
= 0, CurPos
= 0;
1253 BOOLEAN Found
= FALSE
;
1254 CHAR16
*FoundString
= NULL
;
1256 if (InString
!= NULL
) {
1257 // After while() loop, StartPos marks start of item #Index
1258 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1259 if (InString
[CurPos
] == L
',') {
1261 StartPos
= CurPos
+ 1;
1265 // After while() loop, CurPos is one past the end of the element
1266 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1267 if (InString
[CurPos
] == L
',')
1273 FoundString
= StrDuplicate(&InString
[StartPos
]);
1274 if (FoundString
!= NULL
)
1275 FoundString
[CurPos
- StartPos
] = 0;
1277 return (FoundString
);
1278 } // CHAR16 *FindCommaDelimited()