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