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