]> code.delx.au - refind/blob - refind/lib.c
Fixed an icon display bug & very minor incorrect error message bug.
[refind] / refind / lib.c
1 /*
2 * refit/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
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
18 * distribution.
19 *
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.
23 *
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.
35 */
36 /*
37 * Modifications copyright (c) 2012 Roderick W. Smith
38 *
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.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "refit_call_wrapper.h"
50
51 // variables
52
53 EFI_HANDLE SelfImageHandle;
54 EFI_LOADED_IMAGE *SelfLoadedImage;
55 EFI_FILE *SelfRootDir;
56 EFI_FILE *SelfDir;
57 CHAR16 *SelfDirPath;
58
59 REFIT_VOLUME *SelfVolume = NULL;
60 REFIT_VOLUME **Volumes = NULL;
61 UINTN VolumesCount = 0;
62
63 // Maximum size for disk sectors
64 #define SECTOR_SIZE 4096
65
66 // functions
67
68 static EFI_STATUS FinishInitRefitLib(VOID);
69
70 static VOID UninitVolumes(VOID);
71
72 //
73 // self recognition stuff
74 //
75
76 // Converts forward slashes to backslashes and removes duplicate slashes.
77 // Necessary because some (buggy?) EFI implementations produce "\/" strings
78 // in pathnames.
79 static VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
80 CHAR16 *NewName;
81 UINTN i, j = 0;
82 BOOLEAN LastWasSlash = FALSE;
83
84 NewName = AllocateZeroPool(sizeof(CHAR16) * (StrLen(PathName) + 1));
85 if (NewName != NULL) {
86 for (i = 0; i < StrLen(PathName); i++) {
87 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
88 if (!LastWasSlash)
89 NewName[j++] = L'\\';
90 LastWasSlash = TRUE;
91 } else {
92 NewName[j++] = PathName[i];
93 LastWasSlash = FALSE;
94 } // if/else
95 } // for
96 NewName[j] = 0;
97 // Copy the transformed name back....
98 StrCpy(PathName, NewName);
99 FreePool(NewName);
100 } // if allocation OK
101 } // CleanUpPathNameSlashes()
102
103 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
104 {
105 EFI_STATUS Status;
106 CHAR16 *DevicePathAsString;
107 UINTN i;
108
109 SelfImageHandle = ImageHandle;
110 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
111 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
112 return EFI_LOAD_ERROR;
113
114 // find the current directory
115 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
116 CleanUpPathNameSlashes(DevicePathAsString);
117 if (DevicePathAsString != NULL) {
118 for (i = StrLen(DevicePathAsString); (i > 0) && (DevicePathAsString[i] != '\\'); i--) ;
119 DevicePathAsString[i] = 0;
120 } else
121 DevicePathAsString[0] = 0;
122 SelfDirPath = StrDuplicate(DevicePathAsString);
123 FreePool(DevicePathAsString);
124
125 return FinishInitRefitLib();
126 }
127
128 // called before running external programs to close open file handles
129 VOID UninitRefitLib(VOID)
130 {
131 UninitVolumes();
132
133 if (SelfDir != NULL) {
134 refit_call1_wrapper(SelfDir->Close, SelfDir);
135 SelfDir = NULL;
136 }
137
138 if (SelfRootDir != NULL) {
139 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
140 SelfRootDir = NULL;
141 }
142 }
143
144 // called after running external programs to re-open file handles
145 EFI_STATUS ReinitRefitLib(VOID)
146 {
147 ReinitVolumes();
148
149 // Below two lines were in rEFIt, but seem to cause problems on
150 // most systems. OTOH, my Mac Mini produces (apparently harmless)
151 // errors about "(re)opening our installation volume" (see the
152 // next function) when returning from programs when these two lines
153 // are removed. On the gripping hand, the Mac SOMETIMES crashes
154 // when launching a second program even with these lines removed.
155 // TODO: Figure out cause of above weirdness and fix it more
156 // reliably!
157 /* if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
158 SelfRootDir = SelfVolume->RootDir; */
159
160 return FinishInitRefitLib();
161 }
162
163 static EFI_STATUS FinishInitRefitLib(VOID)
164 {
165 EFI_STATUS Status;
166
167 if (SelfRootDir == NULL) {
168 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
169 if (SelfRootDir == NULL) {
170 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
171 return EFI_LOAD_ERROR;
172 }
173 }
174
175 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
176 if (CheckFatalError(Status, L"while opening our installation directory"))
177 return EFI_LOAD_ERROR;
178
179 return EFI_SUCCESS;
180 }
181
182 //
183 // list functions
184 //
185
186 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
187 {
188 UINTN AllocateCount;
189
190 *ElementCount = InitialElementCount;
191 if (*ElementCount > 0) {
192 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
193 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
194 } else {
195 *ListPtr = NULL;
196 }
197 }
198
199 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
200 {
201 UINTN AllocateCount;
202
203 if ((*ElementCount & 7) == 0) {
204 AllocateCount = *ElementCount + 8;
205 if (*ElementCount == 0)
206 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
207 else
208 *ListPtr = ReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
209 }
210 (*ListPtr)[*ElementCount] = NewElement;
211 (*ElementCount)++;
212 } /* VOID AddListElement() */
213
214 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
215 {
216 UINTN i;
217
218 if (*ElementCount > 0) {
219 for (i = 0; i < *ElementCount; i++) {
220 // TODO: call a user-provided routine for each element here
221 FreePool((*ListPtr)[i]);
222 }
223 FreePool(*ListPtr);
224 }
225 }
226
227 //
228 // firmware device path discovery
229 //
230
231 static UINT8 LegacyLoaderMediaPathData[] = {
232 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
233 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
234 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
235 };
236 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
237
238 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
239 {
240 EFI_STATUS Status;
241 UINTN HandleCount = 0;
242 UINTN HandleIndex, HardcodedIndex;
243 EFI_HANDLE *Handles;
244 EFI_HANDLE Handle;
245 UINTN PathCount = 0;
246 UINTN PathIndex;
247 EFI_LOADED_IMAGE *LoadedImage;
248 EFI_DEVICE_PATH *DevicePath;
249 BOOLEAN Seen;
250
251 MaxPaths--; // leave space for the terminating NULL pointer
252
253 // get all LoadedImage handles
254 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL,
255 &HandleCount, &Handles);
256 if (CheckError(Status, L"while listing LoadedImage handles")) {
257 if (HardcodedPathList) {
258 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
259 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
260 }
261 PathList[PathCount] = NULL;
262 return;
263 }
264 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
265 Handle = Handles[HandleIndex];
266
267 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
268 if (EFI_ERROR(Status))
269 continue; // This can only happen if the firmware scewed up, ignore it.
270
271 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
272 if (EFI_ERROR(Status))
273 continue; // This happens, ignore it.
274
275 // Only grab memory range nodes
276 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
277 continue;
278
279 // Check if we have this device path in the list already
280 // WARNING: This assumes the first node in the device path is unique!
281 Seen = FALSE;
282 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
283 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
284 continue;
285 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
286 Seen = TRUE;
287 break;
288 }
289 }
290 if (Seen)
291 continue;
292
293 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
294 }
295 FreePool(Handles);
296
297 if (HardcodedPathList) {
298 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
299 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
300 }
301 PathList[PathCount] = NULL;
302 }
303
304 //
305 // volume functions
306 //
307
308 static VOID ScanVolumeBootcode(IN OUT REFIT_VOLUME *Volume, OUT BOOLEAN *Bootable)
309 {
310 EFI_STATUS Status;
311 UINT8 SectorBuffer[SECTOR_SIZE];
312 UINTN i;
313 MBR_PARTITION_INFO *MbrTable;
314 BOOLEAN MbrTableFound;
315
316 Volume->HasBootCode = FALSE;
317 Volume->OSIconName = NULL;
318 Volume->OSName = NULL;
319 *Bootable = FALSE;
320
321 if (Volume->BlockIO == NULL)
322 return;
323 if (Volume->BlockIO->Media->BlockSize > SECTOR_SIZE)
324 return; // our buffer is too small...
325
326 // look at the boot sector (this is used for both hard disks and El Torito images!)
327 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
328 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
329 Volume->BlockIOOffset, SECTOR_SIZE, SectorBuffer);
330 if (!EFI_ERROR(Status)) {
331
332 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55 && SectorBuffer[0] != 0) {
333 *Bootable = TRUE;
334 Volume->HasBootCode = TRUE;
335 }
336
337 // detect specific boot codes
338 if (CompareMem(SectorBuffer + 2, "LILO", 4) == 0 ||
339 CompareMem(SectorBuffer + 6, "LILO", 4) == 0 ||
340 CompareMem(SectorBuffer + 3, "SYSLINUX", 8) == 0 ||
341 FindMem(SectorBuffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
342 Volume->HasBootCode = TRUE;
343 Volume->OSIconName = L"linux";
344 Volume->OSName = L"Linux";
345
346 } else if (FindMem(SectorBuffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
347 Volume->HasBootCode = TRUE;
348 Volume->OSIconName = L"grub,linux";
349 Volume->OSName = L"Linux";
350
351 } else if ((*((UINT32 *)(SectorBuffer + 502)) == 0 &&
352 *((UINT32 *)(SectorBuffer + 506)) == 50000 &&
353 *((UINT16 *)(SectorBuffer + 510)) == 0xaa55) ||
354 FindMem(SectorBuffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
355 Volume->HasBootCode = TRUE;
356 Volume->OSIconName = L"freebsd";
357 Volume->OSName = L"FreeBSD";
358
359 } else if (FindMem(SectorBuffer, 512, "!Loading", 8) >= 0 ||
360 FindMem(SectorBuffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
361 Volume->HasBootCode = TRUE;
362 Volume->OSIconName = L"openbsd";
363 Volume->OSName = L"OpenBSD";
364
365 } else if (FindMem(SectorBuffer, 512, "Not a bootxx image", 18) >= 0 ||
366 *((UINT32 *)(SectorBuffer + 1028)) == 0x7886b6d1) {
367 Volume->HasBootCode = TRUE;
368 Volume->OSIconName = L"netbsd";
369 Volume->OSName = L"NetBSD";
370
371 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
372 Volume->HasBootCode = TRUE;
373 Volume->OSIconName = L"win";
374 Volume->OSName = L"Windows";
375
376 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
377 Volume->HasBootCode = TRUE;
378 Volume->OSIconName = L"winvista,win";
379 Volume->OSName = L"Windows";
380
381 } else if (FindMem(SectorBuffer, 512, "CPUBOOT SYS", 11) >= 0 ||
382 FindMem(SectorBuffer, 512, "KERNEL SYS", 11) >= 0) {
383 Volume->HasBootCode = TRUE;
384 Volume->OSIconName = L"freedos";
385 Volume->OSName = L"FreeDOS";
386
387 } else if (FindMem(SectorBuffer, 512, "OS2LDR", 6) >= 0 ||
388 FindMem(SectorBuffer, 512, "OS2BOOT", 7) >= 0) {
389 Volume->HasBootCode = TRUE;
390 Volume->OSIconName = L"ecomstation";
391 Volume->OSName = L"eComStation";
392
393 } else if (FindMem(SectorBuffer, 512, "Be Boot Loader", 14) >= 0) {
394 Volume->HasBootCode = TRUE;
395 Volume->OSIconName = L"beos";
396 Volume->OSName = L"BeOS";
397
398 } else if (FindMem(SectorBuffer, 512, "yT Boot Loader", 14) >= 0) {
399 Volume->HasBootCode = TRUE;
400 Volume->OSIconName = L"zeta,beos";
401 Volume->OSName = L"ZETA";
402
403 } else if (FindMem(SectorBuffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
404 FindMem(SectorBuffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
405 Volume->HasBootCode = TRUE;
406 Volume->OSIconName = L"haiku,beos";
407 Volume->OSName = L"Haiku";
408
409 }
410
411 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
412 // need to fix AddLegacyEntry in main.c.
413
414 #if REFIT_DEBUG > 0
415 Print(L" Result of bootcode detection: %s %s (%s)\n",
416 Volume->HasBootCode ? L"bootable" : L"non-bootable",
417 Volume->OSName, Volume->OSIconName);
418 #endif
419
420 if (FindMem(SectorBuffer, 512, "Non-system disk", 15) >= 0) // dummy FAT boot sector
421 Volume->HasBootCode = FALSE;
422
423 // check for MBR partition table
424 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55) {
425 MbrTableFound = FALSE;
426 MbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
427 for (i = 0; i < 4; i++)
428 if (MbrTable[i].StartLBA && MbrTable[i].Size)
429 MbrTableFound = TRUE;
430 for (i = 0; i < 4; i++)
431 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
432 MbrTableFound = FALSE;
433 if (MbrTableFound) {
434 Volume->MbrPartitionTable = AllocatePool(4 * 16);
435 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
436 }
437 }
438
439 } else {
440 #if REFIT_DEBUG > 0
441 CheckError(Status, L"while reading boot sector");
442 #endif
443 }
444 }
445
446 // default volume icon based on disk kind
447 static VOID ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME *Volume)
448 {
449 switch (Volume->DiskKind) {
450 case DISK_KIND_INTERNAL:
451 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
452 break;
453 case DISK_KIND_EXTERNAL:
454 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
455 break;
456 case DISK_KIND_OPTICAL:
457 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
458 break;
459 } // switch()
460 }
461
462 static VOID ScanVolume(IN OUT REFIT_VOLUME *Volume)
463 {
464 EFI_STATUS Status;
465 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
466 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
467 EFI_HANDLE WholeDiskHandle;
468 UINTN PartialLength;
469 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
470 BOOLEAN Bootable;
471
472 // get device path
473 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
474 #if REFIT_DEBUG > 0
475 if (Volume->DevicePath != NULL) {
476 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
477 #if REFIT_DEBUG >= 2
478 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
479 #endif
480 }
481 #endif
482
483 Volume->DiskKind = DISK_KIND_INTERNAL; // default
484
485 // get block i/o
486 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
487 if (EFI_ERROR(Status)) {
488 Volume->BlockIO = NULL;
489 Print(L"Warning: Can't get BlockIO protocol.\n");
490 } else {
491 if (Volume->BlockIO->Media->BlockSize == 2048)
492 Volume->DiskKind = DISK_KIND_OPTICAL;
493 }
494
495 // scan for bootcode and MBR table
496 Bootable = FALSE;
497 ScanVolumeBootcode(Volume, &Bootable);
498
499 // detect device type
500 DevicePath = Volume->DevicePath;
501 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
502 NextDevicePath = NextDevicePathNode(DevicePath);
503
504 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
505 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
506 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
507 DevicePathSubType(DevicePath) == MSG_1394_DP ||
508 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
509 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
510 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
511 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
512 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
513 Bootable = TRUE;
514 }
515
516 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
517 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
518 // TODO: also check for Boot Camp GUID
519 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
520 }
521
522 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
523 // make a device path for the whole device
524 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
525 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
526 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
527 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
528
529 // get the handle for that path
530 RemainingDevicePath = DiskDevicePath;
531 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
532 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
533 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
534 FreePool(DiskDevicePath);
535
536 if (!EFI_ERROR(Status)) {
537 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
538
539 // get the device path for later
540 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
541 if (!EFI_ERROR(Status)) {
542 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
543 }
544
545 // look at the BlockIO protocol
546 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
547 if (!EFI_ERROR(Status)) {
548
549 // check the media block size
550 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
551 Volume->DiskKind = DISK_KIND_OPTICAL;
552
553 } else {
554 Volume->WholeDiskBlockIO = NULL;
555 //CheckError(Status, L"from HandleProtocol");
556 }
557 } //else
558 // CheckError(Status, L"from LocateDevicePath");
559 }
560
561 DevicePath = NextDevicePath;
562 } // while
563
564 if (!Bootable) {
565 #if REFIT_DEBUG > 0
566 if (Volume->HasBootCode)
567 Print(L" Volume considered non-bootable, but boot code is present\n");
568 #endif
569 Volume->HasBootCode = FALSE;
570 }
571
572 // default volume icon based on disk kind
573 ScanVolumeDefaultIcon(Volume);
574
575 // open the root directory of the volume
576 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
577 if (Volume->RootDir == NULL) {
578 return;
579 }
580
581 // get volume name
582 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
583 if (FileSystemInfoPtr != NULL) {
584 Volume->VolName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
585 FreePool(FileSystemInfoPtr);
586 }
587
588 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
589 // - name from bytes 3 to 10 of the boot sector
590 // - partition number
591 // - name derived from file system type or partition type
592
593 // get custom volume icon if present
594 if (FileExists(Volume->RootDir, L".VolumeIcon.icns"))
595 Volume->VolBadgeImage = LoadIcns(Volume->RootDir, L".VolumeIcon.icns", 32);
596 }
597
598 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
599 {
600 EFI_STATUS Status;
601 REFIT_VOLUME *Volume;
602 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
603 UINTN i;
604 UINTN LogicalPartitionIndex = 4;
605 UINT8 SectorBuffer[512];
606 BOOLEAN Bootable;
607 MBR_PARTITION_INFO *EMbrTable;
608
609 ExtBase = MbrEntry->StartLBA;
610
611 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
612 // read current EMBR
613 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
614 WholeDiskVolume->BlockIO,
615 WholeDiskVolume->BlockIO->Media->MediaId,
616 ExtCurrent, 512, SectorBuffer);
617 if (EFI_ERROR(Status))
618 break;
619 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
620 break;
621 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
622
623 // scan logical partitions in this EMBR
624 NextExtCurrent = 0;
625 for (i = 0; i < 4; i++) {
626 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
627 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
628 break;
629 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
630 // set next ExtCurrent
631 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
632 break;
633 } else {
634
635 // found a logical partition
636 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
637 Volume->DiskKind = WholeDiskVolume->DiskKind;
638 Volume->IsMbrPartition = TRUE;
639 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
640 Volume->VolName = PoolPrint(L"Partition %d", Volume->MbrPartitionIndex + 1);
641 Volume->BlockIO = WholeDiskVolume->BlockIO;
642 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
643 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
644
645 Bootable = FALSE;
646 ScanVolumeBootcode(Volume, &Bootable);
647 if (!Bootable)
648 Volume->HasBootCode = FALSE;
649
650 ScanVolumeDefaultIcon(Volume);
651
652 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
653
654 }
655 }
656 }
657 }
658
659 VOID ScanVolumes(VOID)
660 {
661 EFI_STATUS Status;
662 UINTN HandleCount = 0;
663 UINTN HandleIndex;
664 EFI_HANDLE *Handles;
665 REFIT_VOLUME *Volume, *WholeDiskVolume;
666 UINTN VolumeIndex, VolumeIndex2;
667 MBR_PARTITION_INFO *MbrTable;
668 UINTN PartitionIndex;
669 UINT8 *SectorBuffer1, *SectorBuffer2;
670 UINTN SectorSum, i;
671
672 FreePool(Volumes);
673 Volumes = NULL;
674 VolumesCount = 0;
675
676 // get all filesystem handles
677 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
678 // was: &FileSystemProtocol
679 if (Status == EFI_NOT_FOUND)
680 return; // no filesystems. strange, but true...
681 if (CheckError(Status, L"while listing all file systems"))
682 return;
683
684 // first pass: collect information about all handles
685 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
686 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
687 Volume->DeviceHandle = Handles[HandleIndex];
688 ScanVolume(Volume);
689
690 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
691
692 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
693 SelfVolume = Volume;
694 }
695 FreePool(Handles);
696
697 if (SelfVolume == NULL)
698 Print(L"WARNING: SelfVolume not found");
699
700 // second pass: relate partitions and whole disk devices
701 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
702 Volume = Volumes[VolumeIndex];
703 // check MBR partition table for extended partitions
704 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
705 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
706 Volume->MbrPartitionTable != NULL) {
707 MbrTable = Volume->MbrPartitionTable;
708 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
709 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
710 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
711 }
712 }
713 }
714
715 // search for corresponding whole disk volume entry
716 WholeDiskVolume = NULL;
717 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
718 Volume->BlockIO != Volume->WholeDiskBlockIO) {
719 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
720 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
721 Volumes[VolumeIndex2]->BlockIOOffset == 0)
722 WholeDiskVolume = Volumes[VolumeIndex2];
723 }
724 }
725
726 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
727 // check if this volume is one of the partitions in the table
728 MbrTable = WholeDiskVolume->MbrPartitionTable;
729 SectorBuffer1 = AllocatePool(512);
730 SectorBuffer2 = AllocatePool(512);
731 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
732 // check size
733 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
734 continue;
735
736 // compare boot sector read through offset vs. directly
737 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
738 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
739 Volume->BlockIOOffset, 512, SectorBuffer1);
740 if (EFI_ERROR(Status))
741 break;
742 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
743 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
744 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
745 if (EFI_ERROR(Status))
746 break;
747 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
748 continue;
749 SectorSum = 0;
750 for (i = 0; i < 512; i++)
751 SectorSum += SectorBuffer1[i];
752 if (SectorSum < 1000)
753 continue;
754
755 // TODO: mark entry as non-bootable if it is an extended partition
756
757 // now we're reasonably sure the association is correct...
758 Volume->IsMbrPartition = TRUE;
759 Volume->MbrPartitionIndex = PartitionIndex;
760 if (Volume->VolName == NULL)
761 Volume->VolName = PoolPrint(L"Partition %d", PartitionIndex + 1);
762 break;
763 }
764
765 FreePool(SectorBuffer1);
766 FreePool(SectorBuffer2);
767 }
768
769 }
770 } /* VOID ScanVolumes() */
771
772 static VOID UninitVolumes(VOID)
773 {
774 REFIT_VOLUME *Volume;
775 UINTN VolumeIndex;
776
777 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
778 Volume = Volumes[VolumeIndex];
779
780 if (Volume->RootDir != NULL) {
781 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
782 Volume->RootDir = NULL;
783 }
784
785 Volume->DeviceHandle = NULL;
786 Volume->BlockIO = NULL;
787 Volume->WholeDiskBlockIO = NULL;
788 }
789 }
790
791 VOID ReinitVolumes(VOID)
792 {
793 EFI_STATUS Status;
794 REFIT_VOLUME *Volume;
795 UINTN VolumeIndex;
796 EFI_DEVICE_PATH *RemainingDevicePath;
797 EFI_HANDLE DeviceHandle, WholeDiskHandle;
798
799 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
800 Volume = Volumes[VolumeIndex];
801
802 if (Volume->DevicePath != NULL) {
803 // get the handle for that path
804 RemainingDevicePath = Volume->DevicePath;
805 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
806
807 if (!EFI_ERROR(Status)) {
808 Volume->DeviceHandle = DeviceHandle;
809
810 // get the root directory
811 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
812
813 } else
814 CheckError(Status, L"from LocateDevicePath");
815 }
816
817 if (Volume->WholeDiskDevicePath != NULL) {
818 // get the handle for that path
819 RemainingDevicePath = Volume->WholeDiskDevicePath;
820 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
821
822 if (!EFI_ERROR(Status)) {
823 // get the BlockIO protocol
824 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
825 if (EFI_ERROR(Status)) {
826 Volume->WholeDiskBlockIO = NULL;
827 CheckError(Status, L"from HandleProtocol");
828 }
829 } else
830 CheckError(Status, L"from LocateDevicePath");
831 }
832 }
833 }
834
835 //
836 // file and dir functions
837 //
838
839 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
840 {
841 EFI_STATUS Status;
842 EFI_FILE_HANDLE TestFile;
843
844 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
845 if (Status == EFI_SUCCESS) {
846 refit_call1_wrapper(TestFile->Close, TestFile);
847 return TRUE;
848 }
849 return FALSE;
850 }
851
852 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
853 {
854 EFI_STATUS Status;
855 VOID *Buffer;
856 UINTN LastBufferSize, BufferSize;
857 INTN IterCount;
858
859 for (;;) {
860
861 // free pointer from last call
862 if (*DirEntry != NULL) {
863 FreePool(*DirEntry);
864 *DirEntry = NULL;
865 }
866
867 // read next directory entry
868 LastBufferSize = BufferSize = 256;
869 Buffer = AllocatePool(BufferSize);
870 for (IterCount = 0; ; IterCount++) {
871 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
872 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
873 break;
874 if (BufferSize <= LastBufferSize) {
875 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
876 BufferSize = LastBufferSize * 2;
877 #if REFIT_DEBUG > 0
878 } else {
879 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
880 #endif
881 }
882 Buffer = ReallocatePool(Buffer, LastBufferSize, BufferSize);
883 LastBufferSize = BufferSize;
884 }
885 if (EFI_ERROR(Status)) {
886 FreePool(Buffer);
887 break;
888 }
889
890 // check for end of listing
891 if (BufferSize == 0) { // end of directory listing
892 FreePool(Buffer);
893 break;
894 }
895
896 // entry is ready to be returned
897 *DirEntry = (EFI_FILE_INFO *)Buffer;
898
899 // filter results
900 if (FilterMode == 1) { // only return directories
901 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
902 break;
903 } else if (FilterMode == 2) { // only return files
904 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
905 break;
906 } else // no filter or unknown filter -> return everything
907 break;
908
909 }
910 return Status;
911 }
912
913 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
914 {
915 if (RelativePath == NULL) {
916 DirIter->LastStatus = EFI_SUCCESS;
917 DirIter->DirHandle = BaseDir;
918 DirIter->CloseDirHandle = FALSE;
919 } else {
920 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
921 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
922 }
923 DirIter->LastFileInfo = NULL;
924 }
925
926 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
927 OUT EFI_FILE_INFO **DirEntry)
928 {
929 if (DirIter->LastFileInfo != NULL) {
930 FreePool(DirIter->LastFileInfo);
931 DirIter->LastFileInfo = NULL;
932 }
933
934 if (EFI_ERROR(DirIter->LastStatus))
935 return FALSE; // stop iteration
936
937 for (;;) {
938 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
939 if (EFI_ERROR(DirIter->LastStatus))
940 return FALSE;
941 if (DirIter->LastFileInfo == NULL) // end of listing
942 return FALSE;
943 if (FilePattern != NULL) {
944 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
945 break;
946 if (MetaiMatch(DirIter->LastFileInfo->FileName, FilePattern))
947 break;
948 // else continue loop
949 } else
950 break;
951 }
952
953 *DirEntry = DirIter->LastFileInfo;
954 return TRUE;
955 }
956
957 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
958 {
959 if (DirIter->LastFileInfo != NULL) {
960 FreePool(DirIter->LastFileInfo);
961 DirIter->LastFileInfo = NULL;
962 }
963 if (DirIter->CloseDirHandle)
964 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
965 return DirIter->LastStatus;
966 }
967
968 //
969 // file name manipulation
970 //
971
972 // Returns the filename portion (minus path name) of the
973 // specified file
974 CHAR16 * Basename(IN CHAR16 *Path)
975 {
976 CHAR16 *FileName;
977 UINTN i;
978
979 FileName = Path;
980
981 if (Path != NULL) {
982 for (i = StrLen(Path); i > 0; i--) {
983 if (Path[i-1] == '\\' || Path[i-1] == '/') {
984 FileName = Path + i;
985 break;
986 }
987 }
988 }
989
990 return FileName;
991 }
992
993 VOID ReplaceExtension(IN OUT CHAR16 *Path, IN CHAR16 *Extension)
994 {
995 UINTN i;
996
997 for (i = StrLen(Path); i >= 0; i--) {
998 if (Path[i] == '.') {
999 Path[i] = 0;
1000 break;
1001 }
1002 if (Path[i] == '\\' || Path[i] == '/')
1003 break;
1004 }
1005 StrCat(Path, Extension);
1006 }
1007
1008 //
1009 // memory string search
1010 //
1011
1012 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1013 {
1014 UINT8 *BufferPtr;
1015 UINTN Offset;
1016
1017 BufferPtr = Buffer;
1018 BufferLength -= SearchStringLength;
1019 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1020 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1021 return (INTN)Offset;
1022 }
1023
1024 return -1;
1025 }
1026
1027 // Performs a case-insensitive search of BigStr for SmallStr.
1028 // Returns TRUE if found, FALSE if not.
1029 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1030 CHAR16 *SmallCopy, *BigCopy;
1031 BOOLEAN Found = FALSE;
1032 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1033
1034 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1035 SmallCopy = StrDuplicate(SmallStr);
1036 BigCopy = StrDuplicate(BigStr);
1037 StrLwr(SmallCopy);
1038 StrLwr(BigCopy);
1039 SmallLen = StrLen(SmallCopy);
1040 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1041 while ((!Found) && (StartPoint < NumCompares)) {
1042 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1043 } // while
1044 FreePool(SmallCopy);
1045 FreePool(BigCopy);
1046 } // if
1047
1048 return (Found);
1049 } // BOOLEAN StriSubCmp()
1050
1051 // Merges two strings, creating a new one and returning a pointer to it.
1052 // If AddChar != 0, the specified character is placed between the two original
1053 // strings (unless the first string is NULL). The original input string
1054 // *First is de-allocated and replaced by the new merged string.
1055 // This is similar to StrCat, but safer and more flexible because
1056 // MergeStrings allocates memory that's the correct size for the
1057 // new merged string, so it can take a NULL *First and it cleans
1058 // up the old memory. It should *NOT* be used with a constant
1059 // *First, though....
1060 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1061 UINTN Length1 = 0, Length2 = 0;
1062 CHAR16* NewString;
1063
1064 if (*First != NULL)
1065 Length1 = StrLen(*First);
1066 if (Second != NULL)
1067 Length2 = StrLen(Second);
1068 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1069 NewString[0] = 0;
1070 if (NewString != NULL) {
1071 if (*First != NULL) {
1072 StrCat(NewString, *First);
1073 if (AddChar) {
1074 NewString[Length1] = AddChar;
1075 NewString[Length1 + 1] = 0;
1076 } // if (AddChar)
1077 } // if (*First != NULL)
1078 if (First != NULL)
1079 StrCat(NewString, Second);
1080 FreePool(*First);
1081 *First = NewString;
1082 } else {
1083 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1084 } // if/else
1085 } // static CHAR16* MergeStrings()
1086
1087 // Takes an input pathname (*Path) and locates the final directory component
1088 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1089 // function returns the string 'foo'.
1090 // Assumes the pathname is separated with backslashes.
1091 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1092 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1093 CHAR16 *Found = NULL;
1094
1095 PathLength = StrLen(Path);
1096 // Find start & end of target element
1097 for (i = 0; i < PathLength; i++) {
1098 if (Path[i] == '\\') {
1099 StartOfElement = EndOfElement;
1100 EndOfElement = i;
1101 } // if
1102 } // for
1103 // Extract the target element
1104 if (EndOfElement > 0) {
1105 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1106 StartOfElement++;
1107 } // while
1108 EndOfElement--;
1109 if (EndOfElement >= StartOfElement) {
1110 CopyLength = EndOfElement - StartOfElement + 1;
1111 Found = StrDuplicate(&Path[StartOfElement]);
1112 if (Found != NULL)
1113 Found[CopyLength] = 0;
1114 } // if (EndOfElement >= StartOfElement)
1115 } // if (EndOfElement > 0)
1116 return (Found);
1117 } // CHAR16 *FindLastDirName
1118
1119 // Returns the directory portion of a pathname. For instance,
1120 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1121 // string 'EFI\foo'.
1122 CHAR16 *FindPath(IN CHAR16* FullPath) {
1123 UINTN i, LastBackslash = 0;
1124 CHAR16 *PathOnly;
1125
1126 for (i = 0; i < StrLen(FullPath); i++) {
1127 if (FullPath[i] == '\\')
1128 LastBackslash = i;
1129 } // for
1130 PathOnly = StrDuplicate(FullPath);
1131 PathOnly[LastBackslash] = 0;
1132 return (PathOnly);
1133 }
1134
1135 // Returns all the digits in the input string, including intervening
1136 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1137 // this function returns "3.3.4-7". If InString contains no digits,
1138 // the return value is NULL.
1139 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1140 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1141 CHAR16 *Found = NULL;
1142
1143 InLength = StartOfElement = StrLen(InString);
1144 // Find start & end of target element
1145 for (i = 0; i < InLength; i++) {
1146 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1147 if (StartOfElement > i)
1148 StartOfElement = i;
1149 if (EndOfElement < i)
1150 EndOfElement = i;
1151 } // if
1152 } // for
1153 // Extract the target element
1154 if (EndOfElement > 0) {
1155 if (EndOfElement >= StartOfElement) {
1156 CopyLength = EndOfElement - StartOfElement + 1;
1157 Found = StrDuplicate(&InString[StartOfElement]);
1158 if (Found != NULL)
1159 Found[CopyLength] = 0;
1160 } // if (EndOfElement >= StartOfElement)
1161 } // if (EndOfElement > 0)
1162 return (Found);
1163 } // CHAR16 *FindNumbers()
1164
1165 // Find the #Index element (numbered from 0) in a comma-delimited string
1166 // of elements.
1167 // Returns the found element, or NULL if Index is out of range of InString
1168 // is NULL.
1169 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1170 UINTN StartPos = 0, CurPos = 0;
1171 BOOLEAN Found = FALSE;
1172 CHAR16 *FoundString = NULL;
1173
1174 if (InString != NULL) {
1175 // After while() loop, StartPos marks start of item #Index
1176 while ((Index > 0) && (CurPos < StrLen(InString))) {
1177 if (InString[CurPos] == L',') {
1178 Index--;
1179 StartPos = CurPos + 1;
1180 } // if
1181 CurPos++;
1182 } // while
1183 // After while() loop, CurPos is one past the end of the element
1184 while ((CurPos < StrLen(InString)) && (!Found)) {
1185 if (InString[CurPos] == L',')
1186 Found = TRUE;
1187 else
1188 CurPos++;
1189 } // while
1190 } // if
1191 if (Index == 0)
1192 FoundString = StrDuplicate(&InString[StartPos]);
1193 if (FoundString != NULL)
1194 FoundString[CurPos - StartPos] = 0;
1195 return (FoundString);
1196 } // CHAR16 *FindCommaDelimited()