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