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