]> code.delx.au - refind/blob - refind/lib.c
Improved BIOS-bootable detection code
[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 // GRUB in BIOS boot partition:
370 } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
371 Volume->HasBootCode = TRUE;
372 Volume->OSIconName = L"grub,linux";
373 Volume->OSName = L"Linux";
374 Volume->VolName = L"BIOS Boot Partition";
375 *Bootable = TRUE;
376
377 } else if ((*((UINT32 *)(SectorBuffer + 502)) == 0 &&
378 *((UINT32 *)(SectorBuffer + 506)) == 50000 &&
379 *((UINT16 *)(SectorBuffer + 510)) == 0xaa55) ||
380 FindMem(SectorBuffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
381 Volume->HasBootCode = TRUE;
382 Volume->OSIconName = L"freebsd";
383 Volume->OSName = L"FreeBSD";
384
385 } else if (FindMem(SectorBuffer, 512, "!Loading", 8) >= 0 ||
386 FindMem(SectorBuffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
387 Volume->HasBootCode = TRUE;
388 Volume->OSIconName = L"openbsd";
389 Volume->OSName = L"OpenBSD";
390
391 } else if (FindMem(SectorBuffer, 512, "Not a bootxx image", 18) >= 0 ||
392 *((UINT32 *)(SectorBuffer + 1028)) == 0x7886b6d1) {
393 Volume->HasBootCode = TRUE;
394 Volume->OSIconName = L"netbsd";
395 Volume->OSName = L"NetBSD";
396
397 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
398 Volume->HasBootCode = TRUE;
399 Volume->OSIconName = L"win";
400 Volume->OSName = L"Windows";
401
402 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
403 Volume->HasBootCode = TRUE;
404 Volume->OSIconName = L"winvista,win";
405 Volume->OSName = L"Windows";
406
407 } else if (FindMem(SectorBuffer, 512, "CPUBOOT SYS", 11) >= 0 ||
408 FindMem(SectorBuffer, 512, "KERNEL SYS", 11) >= 0) {
409 Volume->HasBootCode = TRUE;
410 Volume->OSIconName = L"freedos";
411 Volume->OSName = L"FreeDOS";
412
413 } else if (FindMem(SectorBuffer, 512, "OS2LDR", 6) >= 0 ||
414 FindMem(SectorBuffer, 512, "OS2BOOT", 7) >= 0) {
415 Volume->HasBootCode = TRUE;
416 Volume->OSIconName = L"ecomstation";
417 Volume->OSName = L"eComStation";
418
419 } else if (FindMem(SectorBuffer, 512, "Be Boot Loader", 14) >= 0) {
420 Volume->HasBootCode = TRUE;
421 Volume->OSIconName = L"beos";
422 Volume->OSName = L"BeOS";
423
424 } else if (FindMem(SectorBuffer, 512, "yT Boot Loader", 14) >= 0) {
425 Volume->HasBootCode = TRUE;
426 Volume->OSIconName = L"zeta,beos";
427 Volume->OSName = L"ZETA";
428
429 } else if (FindMem(SectorBuffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
430 FindMem(SectorBuffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
431 Volume->HasBootCode = TRUE;
432 Volume->OSIconName = L"haiku,beos";
433 Volume->OSName = L"Haiku";
434
435 }
436
437 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
438 // need to fix AddLegacyEntry in main.c.
439
440 #if REFIT_DEBUG > 0
441 Print(L" Result of bootcode detection: %s %s (%s)\n",
442 Volume->HasBootCode ? L"bootable" : L"non-bootable",
443 Volume->OSName, Volume->OSIconName);
444 #endif
445
446 // dummy FAT boot sector (created by OS X's newfs_msdos)
447 if (FindMem(SectorBuffer, 512, "Non-system disk", 15) >= 0)
448 Volume->HasBootCode = FALSE;
449
450 // dummy FAT boot sector (created by Linux's mkdosfs)
451 if (FindMem(SectorBuffer, 512, "This is not a bootable disk", 27) >= 0)
452 Volume->HasBootCode = FALSE;
453
454 // dummy FAT boot sector (created by Windows)
455 if (FindMem(SectorBuffer, 512, "Press any key to restart", 24) >= 0)
456 Volume->HasBootCode = FALSE;
457
458 // check for MBR partition table
459 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55) {
460 MbrTableFound = FALSE;
461 MbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
462 for (i = 0; i < 4; i++)
463 if (MbrTable[i].StartLBA && MbrTable[i].Size)
464 MbrTableFound = TRUE;
465 for (i = 0; i < 4; i++)
466 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
467 MbrTableFound = FALSE;
468 if (MbrTableFound) {
469 Volume->MbrPartitionTable = AllocatePool(4 * 16);
470 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
471 }
472 }
473
474 } else {
475 #if REFIT_DEBUG > 0
476 CheckError(Status, L"while reading boot sector");
477 #endif
478 }
479 }
480
481 // default volume badge icon based on disk kind
482 static VOID ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME *Volume)
483 {
484 switch (Volume->DiskKind) {
485 case DISK_KIND_INTERNAL:
486 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
487 break;
488 case DISK_KIND_EXTERNAL:
489 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
490 break;
491 case DISK_KIND_OPTICAL:
492 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
493 break;
494 } // switch()
495 }
496
497 static VOID ScanVolume(IN OUT REFIT_VOLUME *Volume)
498 {
499 EFI_STATUS Status;
500 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
501 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
502 EFI_HANDLE WholeDiskHandle;
503 UINTN PartialLength;
504 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
505 BOOLEAN Bootable;
506
507 // get device path
508 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
509 #if REFIT_DEBUG > 0
510 if (Volume->DevicePath != NULL) {
511 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
512 #if REFIT_DEBUG >= 2
513 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
514 #endif
515 }
516 #endif
517
518 Volume->DiskKind = DISK_KIND_INTERNAL; // default
519
520 // get block i/o
521 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
522 if (EFI_ERROR(Status)) {
523 Volume->BlockIO = NULL;
524 Print(L"Warning: Can't get BlockIO protocol.\n");
525 } else {
526 if (Volume->BlockIO->Media->BlockSize == 2048)
527 Volume->DiskKind = DISK_KIND_OPTICAL;
528 }
529
530 // scan for bootcode and MBR table
531 Bootable = FALSE;
532 ScanVolumeBootcode(Volume, &Bootable);
533
534 // detect device type
535 DevicePath = Volume->DevicePath;
536 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
537 NextDevicePath = NextDevicePathNode(DevicePath);
538
539 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
540 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
541 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
542 DevicePathSubType(DevicePath) == MSG_1394_DP ||
543 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
544 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
545 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
546 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
547 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
548 Bootable = TRUE;
549 }
550
551 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
552 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
553 // TODO: also check for Boot Camp GUID
554 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
555 }
556
557 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
558 // make a device path for the whole device
559 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
560 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
561 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
562 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
563
564 // get the handle for that path
565 RemainingDevicePath = DiskDevicePath;
566 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
567 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
568 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
569 FreePool(DiskDevicePath);
570
571 if (!EFI_ERROR(Status)) {
572 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
573
574 // get the device path for later
575 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
576 if (!EFI_ERROR(Status)) {
577 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
578 }
579
580 // look at the BlockIO protocol
581 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
582 if (!EFI_ERROR(Status)) {
583
584 // check the media block size
585 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
586 Volume->DiskKind = DISK_KIND_OPTICAL;
587
588 } else {
589 Volume->WholeDiskBlockIO = NULL;
590 //CheckError(Status, L"from HandleProtocol");
591 }
592 } //else
593 // CheckError(Status, L"from LocateDevicePath");
594 }
595
596 DevicePath = NextDevicePath;
597 } // while
598
599 if (!Bootable) {
600 #if REFIT_DEBUG > 0
601 if (Volume->HasBootCode)
602 Print(L" Volume considered non-bootable, but boot code is present\n");
603 #endif
604 Volume->HasBootCode = FALSE;
605 }
606
607 // default volume icon based on disk kind
608 ScanVolumeDefaultIcon(Volume);
609
610 // open the root directory of the volume
611 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
612 if (Volume->RootDir == NULL) {
613 Volume->IsReadable = FALSE;
614 return;
615 } else {
616 Volume->IsReadable = TRUE;
617 }
618
619 // get volume name
620 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
621 if (FileSystemInfoPtr != NULL) {
622 Volume->VolName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
623 FreePool(FileSystemInfoPtr);
624 }
625
626 if (Volume->VolName == NULL) {
627 Volume->VolName = StrDuplicate(L"Unknown");
628 }
629 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
630 // - name from bytes 3 to 10 of the boot sector
631 // - partition number
632 // - name derived from file system type or partition type
633
634 // get custom volume icon if present
635 if (FileExists(Volume->RootDir, VOLUME_BADGE_NAME))
636 Volume->VolBadgeImage = LoadIcns(Volume->RootDir, VOLUME_BADGE_NAME, 32);
637 if (FileExists(Volume->RootDir, VOLUME_ICON_NAME)) {
638 Volume->VolIconImage = LoadIcns(Volume->RootDir, VOLUME_ICON_NAME, 128);
639 }
640 }
641
642 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
643 {
644 EFI_STATUS Status;
645 REFIT_VOLUME *Volume;
646 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
647 UINTN i;
648 UINTN LogicalPartitionIndex = 4;
649 UINT8 SectorBuffer[512];
650 BOOLEAN Bootable;
651 MBR_PARTITION_INFO *EMbrTable;
652
653 ExtBase = MbrEntry->StartLBA;
654
655 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
656 // read current EMBR
657 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
658 WholeDiskVolume->BlockIO,
659 WholeDiskVolume->BlockIO->Media->MediaId,
660 ExtCurrent, 512, SectorBuffer);
661 if (EFI_ERROR(Status))
662 break;
663 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
664 break;
665 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
666
667 // scan logical partitions in this EMBR
668 NextExtCurrent = 0;
669 for (i = 0; i < 4; i++) {
670 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
671 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
672 break;
673 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
674 // set next ExtCurrent
675 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
676 break;
677 } else {
678
679 // found a logical partition
680 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
681 Volume->DiskKind = WholeDiskVolume->DiskKind;
682 Volume->IsMbrPartition = TRUE;
683 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
684 Volume->VolName = PoolPrint(L"Partition %d", Volume->MbrPartitionIndex + 1);
685 Volume->BlockIO = WholeDiskVolume->BlockIO;
686 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
687 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
688
689 Bootable = FALSE;
690 ScanVolumeBootcode(Volume, &Bootable);
691 if (!Bootable)
692 Volume->HasBootCode = FALSE;
693
694 ScanVolumeDefaultIcon(Volume);
695
696 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
697
698 }
699 }
700 }
701 }
702
703 VOID ScanVolumes(VOID)
704 {
705 EFI_STATUS Status;
706 UINTN HandleCount = 0;
707 UINTN HandleIndex;
708 EFI_HANDLE *Handles;
709 REFIT_VOLUME *Volume, *WholeDiskVolume;
710 UINTN VolumeIndex, VolumeIndex2;
711 MBR_PARTITION_INFO *MbrTable;
712 UINTN PartitionIndex;
713 UINT8 *SectorBuffer1, *SectorBuffer2;
714 UINTN SectorSum, i;
715
716 FreePool(Volumes);
717 Volumes = NULL;
718 VolumesCount = 0;
719
720 // get all filesystem handles
721 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
722 // was: &FileSystemProtocol
723 if (Status == EFI_NOT_FOUND)
724 return; // no filesystems. strange, but true...
725 if (CheckError(Status, L"while listing all file systems"))
726 return;
727
728 // first pass: collect information about all handles
729 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
730 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
731 Volume->DeviceHandle = Handles[HandleIndex];
732 ScanVolume(Volume);
733
734 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
735
736 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
737 SelfVolume = Volume;
738 }
739 FreePool(Handles);
740
741 if (SelfVolume == NULL)
742 Print(L"WARNING: SelfVolume not found");
743
744 // second pass: relate partitions and whole disk devices
745 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
746 Volume = Volumes[VolumeIndex];
747 // check MBR partition table for extended partitions
748 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
749 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
750 Volume->MbrPartitionTable != NULL) {
751 MbrTable = Volume->MbrPartitionTable;
752 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
753 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
754 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
755 }
756 }
757 }
758
759 // search for corresponding whole disk volume entry
760 WholeDiskVolume = NULL;
761 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
762 Volume->BlockIO != Volume->WholeDiskBlockIO) {
763 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
764 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
765 Volumes[VolumeIndex2]->BlockIOOffset == 0)
766 WholeDiskVolume = Volumes[VolumeIndex2];
767 }
768 }
769
770 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
771 // check if this volume is one of the partitions in the table
772 MbrTable = WholeDiskVolume->MbrPartitionTable;
773 SectorBuffer1 = AllocatePool(512);
774 SectorBuffer2 = AllocatePool(512);
775 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
776 // check size
777 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
778 continue;
779
780 // compare boot sector read through offset vs. directly
781 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
782 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
783 Volume->BlockIOOffset, 512, SectorBuffer1);
784 if (EFI_ERROR(Status))
785 break;
786 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
787 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
788 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
789 if (EFI_ERROR(Status))
790 break;
791 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
792 continue;
793 SectorSum = 0;
794 for (i = 0; i < 512; i++)
795 SectorSum += SectorBuffer1[i];
796 if (SectorSum < 1000)
797 continue;
798
799 // TODO: mark entry as non-bootable if it is an extended partition
800
801 // now we're reasonably sure the association is correct...
802 Volume->IsMbrPartition = TRUE;
803 Volume->MbrPartitionIndex = PartitionIndex;
804 if (Volume->VolName == NULL)
805 Volume->VolName = PoolPrint(L"Partition %d", PartitionIndex + 1);
806 break;
807 }
808
809 FreePool(SectorBuffer1);
810 FreePool(SectorBuffer2);
811 }
812
813 }
814 } /* VOID ScanVolumes() */
815
816 static VOID UninitVolumes(VOID)
817 {
818 REFIT_VOLUME *Volume;
819 UINTN VolumeIndex;
820
821 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
822 Volume = Volumes[VolumeIndex];
823
824 if (Volume->RootDir != NULL) {
825 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
826 Volume->RootDir = NULL;
827 }
828
829 Volume->DeviceHandle = NULL;
830 Volume->BlockIO = NULL;
831 Volume->WholeDiskBlockIO = NULL;
832 }
833 }
834
835 VOID ReinitVolumes(VOID)
836 {
837 EFI_STATUS Status;
838 REFIT_VOLUME *Volume;
839 UINTN VolumeIndex;
840 EFI_DEVICE_PATH *RemainingDevicePath;
841 EFI_HANDLE DeviceHandle, WholeDiskHandle;
842
843 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
844 Volume = Volumes[VolumeIndex];
845
846 if (Volume->DevicePath != NULL) {
847 // get the handle for that path
848 RemainingDevicePath = Volume->DevicePath;
849 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
850
851 if (!EFI_ERROR(Status)) {
852 Volume->DeviceHandle = DeviceHandle;
853
854 // get the root directory
855 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
856
857 } else
858 CheckError(Status, L"from LocateDevicePath");
859 }
860
861 if (Volume->WholeDiskDevicePath != NULL) {
862 // get the handle for that path
863 RemainingDevicePath = Volume->WholeDiskDevicePath;
864 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
865
866 if (!EFI_ERROR(Status)) {
867 // get the BlockIO protocol
868 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
869 if (EFI_ERROR(Status)) {
870 Volume->WholeDiskBlockIO = NULL;
871 CheckError(Status, L"from HandleProtocol");
872 }
873 } else
874 CheckError(Status, L"from LocateDevicePath");
875 }
876 }
877 }
878
879 //
880 // file and dir functions
881 //
882
883 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
884 {
885 EFI_STATUS Status;
886 EFI_FILE_HANDLE TestFile;
887
888 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
889 if (Status == EFI_SUCCESS) {
890 refit_call1_wrapper(TestFile->Close, TestFile);
891 return TRUE;
892 }
893 return FALSE;
894 }
895
896 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
897 {
898 EFI_STATUS Status;
899 VOID *Buffer;
900 UINTN LastBufferSize, BufferSize;
901 INTN IterCount;
902
903 for (;;) {
904
905 // free pointer from last call
906 if (*DirEntry != NULL) {
907 FreePool(*DirEntry);
908 *DirEntry = NULL;
909 }
910
911 // read next directory entry
912 LastBufferSize = BufferSize = 256;
913 Buffer = AllocatePool(BufferSize);
914 for (IterCount = 0; ; IterCount++) {
915 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
916 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
917 break;
918 if (BufferSize <= LastBufferSize) {
919 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
920 BufferSize = LastBufferSize * 2;
921 #if REFIT_DEBUG > 0
922 } else {
923 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
924 #endif
925 }
926 Buffer = ReallocatePool(Buffer, LastBufferSize, BufferSize);
927 LastBufferSize = BufferSize;
928 }
929 if (EFI_ERROR(Status)) {
930 FreePool(Buffer);
931 break;
932 }
933
934 // check for end of listing
935 if (BufferSize == 0) { // end of directory listing
936 FreePool(Buffer);
937 break;
938 }
939
940 // entry is ready to be returned
941 *DirEntry = (EFI_FILE_INFO *)Buffer;
942
943 // filter results
944 if (FilterMode == 1) { // only return directories
945 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
946 break;
947 } else if (FilterMode == 2) { // only return files
948 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
949 break;
950 } else // no filter or unknown filter -> return everything
951 break;
952
953 }
954 return Status;
955 }
956
957 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
958 {
959 if (RelativePath == NULL) {
960 DirIter->LastStatus = EFI_SUCCESS;
961 DirIter->DirHandle = BaseDir;
962 DirIter->CloseDirHandle = FALSE;
963 } else {
964 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
965 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
966 }
967 DirIter->LastFileInfo = NULL;
968 }
969
970 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
971 OUT EFI_FILE_INFO **DirEntry)
972 {
973 BOOLEAN KeepGoing = TRUE;
974 UINTN i;
975 CHAR16 *OnePattern;
976
977 if (DirIter->LastFileInfo != NULL) {
978 FreePool(DirIter->LastFileInfo);
979 DirIter->LastFileInfo = NULL;
980 }
981
982 if (EFI_ERROR(DirIter->LastStatus))
983 return FALSE; // stop iteration
984
985 do {
986 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
987 if (EFI_ERROR(DirIter->LastStatus))
988 return FALSE;
989 if (DirIter->LastFileInfo == NULL) // end of listing
990 return FALSE;
991 if (FilePattern != NULL) {
992 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
993 KeepGoing = FALSE;
994 i = 0;
995 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
996 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
997 KeepGoing = FALSE;
998 } // while
999 // else continue loop
1000 } else
1001 break;
1002 } while (KeepGoing);
1003
1004 *DirEntry = DirIter->LastFileInfo;
1005 return TRUE;
1006 }
1007
1008 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1009 {
1010 if (DirIter->LastFileInfo != NULL) {
1011 FreePool(DirIter->LastFileInfo);
1012 DirIter->LastFileInfo = NULL;
1013 }
1014 if (DirIter->CloseDirHandle)
1015 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1016 return DirIter->LastStatus;
1017 }
1018
1019 //
1020 // file name manipulation
1021 //
1022
1023 // Returns the filename portion (minus path name) of the
1024 // specified file
1025 CHAR16 * Basename(IN CHAR16 *Path)
1026 {
1027 CHAR16 *FileName;
1028 UINTN i;
1029
1030 FileName = Path;
1031
1032 if (Path != NULL) {
1033 for (i = StrLen(Path); i > 0; i--) {
1034 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1035 FileName = Path + i;
1036 break;
1037 }
1038 }
1039 }
1040
1041 return FileName;
1042 }
1043
1044 // Replaces a filename extension of ".efi" with the specified string
1045 // (Extension). If the input Path doesn't end in ".efi", Extension
1046 // is added to the existing filename.
1047 VOID ReplaceEfiExtension(IN OUT CHAR16 *Path, IN CHAR16 *Extension)
1048 {
1049 UINTN PathLen;
1050
1051 PathLen = StrLen(Path);
1052 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1053 if ((PathLen >= 4) && ((StriCmp(&Path[PathLen - 4], L".efi") == 0) || (StriCmp(&Path[PathLen - 4], L".EFI") == 0))) {
1054 Path[PathLen - 4] = 0;
1055 } // if
1056 StrCat(Path, Extension);
1057 } // VOID ReplaceEfiExtension()
1058
1059 //
1060 // memory string search
1061 //
1062
1063 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1064 {
1065 UINT8 *BufferPtr;
1066 UINTN Offset;
1067
1068 BufferPtr = Buffer;
1069 BufferLength -= SearchStringLength;
1070 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1071 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1072 return (INTN)Offset;
1073 }
1074
1075 return -1;
1076 }
1077
1078 // Performs a case-insensitive search of BigStr for SmallStr.
1079 // Returns TRUE if found, FALSE if not.
1080 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1081 CHAR16 *SmallCopy, *BigCopy;
1082 BOOLEAN Found = FALSE;
1083 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1084
1085 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1086 SmallCopy = StrDuplicate(SmallStr);
1087 BigCopy = StrDuplicate(BigStr);
1088 StrLwr(SmallCopy);
1089 StrLwr(BigCopy);
1090 SmallLen = StrLen(SmallCopy);
1091 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1092 while ((!Found) && (StartPoint < NumCompares)) {
1093 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1094 } // while
1095 FreePool(SmallCopy);
1096 FreePool(BigCopy);
1097 } // if
1098
1099 return (Found);
1100 } // BOOLEAN StriSubCmp()
1101
1102 // Merges two strings, creating a new one and returning a pointer to it.
1103 // If AddChar != 0, the specified character is placed between the two original
1104 // strings (unless the first string is NULL). The original input string
1105 // *First is de-allocated and replaced by the new merged string.
1106 // This is similar to StrCat, but safer and more flexible because
1107 // MergeStrings allocates memory that's the correct size for the
1108 // new merged string, so it can take a NULL *First and it cleans
1109 // up the old memory. It should *NOT* be used with a constant
1110 // *First, though....
1111 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1112 UINTN Length1 = 0, Length2 = 0;
1113 CHAR16* NewString;
1114
1115 if (*First != NULL)
1116 Length1 = StrLen(*First);
1117 if (Second != NULL)
1118 Length2 = StrLen(Second);
1119 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1120 if (NewString != NULL) {
1121 NewString[0] = L'\0';
1122 if (*First != NULL) {
1123 StrCat(NewString, *First);
1124 if (AddChar) {
1125 NewString[Length1] = AddChar;
1126 NewString[Length1 + 1] = 0;
1127 } // if (AddChar)
1128 } // if (*First != NULL)
1129 if (Second != NULL)
1130 StrCat(NewString, Second);
1131 FreePool(*First);
1132 *First = NewString;
1133 } else {
1134 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1135 } // if/else
1136 } // static CHAR16* MergeStrings()
1137
1138 // Takes an input pathname (*Path) and returns the part of the filename from
1139 // the final dot onwards, converted to lowercase. If the filename includes
1140 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1141 // The calling function is responsible for freeing the memory associated with
1142 // the return value.
1143 CHAR16 *FindExtension(IN CHAR16 *Path) {
1144 CHAR16 *Extension;
1145 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1146 UINTN i;
1147
1148 Extension = AllocateZeroPool(sizeof(CHAR16));
1149 if (Path) {
1150 i = StrLen(Path);
1151 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1152 if (Path[i] == L'.')
1153 Found = TRUE;
1154 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1155 FoundSlash = TRUE;
1156 if (!Found)
1157 i--;
1158 } // while
1159 if (Found) {
1160 MergeStrings(&Extension, &Path[i], 0);
1161 StrLwr(Extension);
1162 } // if (Found)
1163 } // if
1164 return (Extension);
1165 } // CHAR16 *FindExtension
1166
1167 // Takes an input pathname (*Path) and locates the final directory component
1168 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1169 // function returns the string 'foo'.
1170 // Assumes the pathname is separated with backslashes.
1171 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1172 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1173 CHAR16 *Found = NULL;
1174
1175 PathLength = StrLen(Path);
1176 // Find start & end of target element
1177 for (i = 0; i < PathLength; i++) {
1178 if (Path[i] == '\\') {
1179 StartOfElement = EndOfElement;
1180 EndOfElement = i;
1181 } // if
1182 } // for
1183 // Extract the target element
1184 if (EndOfElement > 0) {
1185 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1186 StartOfElement++;
1187 } // while
1188 EndOfElement--;
1189 if (EndOfElement >= StartOfElement) {
1190 CopyLength = EndOfElement - StartOfElement + 1;
1191 Found = StrDuplicate(&Path[StartOfElement]);
1192 if (Found != NULL)
1193 Found[CopyLength] = 0;
1194 } // if (EndOfElement >= StartOfElement)
1195 } // if (EndOfElement > 0)
1196 return (Found);
1197 } // CHAR16 *FindLastDirName
1198
1199 // Returns the directory portion of a pathname. For instance,
1200 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1201 // string 'EFI\foo'.
1202 CHAR16 *FindPath(IN CHAR16* FullPath) {
1203 UINTN i, LastBackslash = 0;
1204 CHAR16 *PathOnly;
1205
1206 for (i = 0; i < StrLen(FullPath); i++) {
1207 if (FullPath[i] == '\\')
1208 LastBackslash = i;
1209 } // for
1210 PathOnly = StrDuplicate(FullPath);
1211 PathOnly[LastBackslash] = 0;
1212 return (PathOnly);
1213 }
1214
1215 // Returns all the digits in the input string, including intervening
1216 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1217 // this function returns "3.3.4-7". If InString contains no digits,
1218 // the return value is NULL.
1219 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1220 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1221 CHAR16 *Found = NULL;
1222
1223 InLength = StartOfElement = StrLen(InString);
1224 // Find start & end of target element
1225 for (i = 0; i < InLength; i++) {
1226 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1227 if (StartOfElement > i)
1228 StartOfElement = i;
1229 if (EndOfElement < i)
1230 EndOfElement = i;
1231 } // if
1232 } // for
1233 // Extract the target element
1234 if (EndOfElement > 0) {
1235 if (EndOfElement >= StartOfElement) {
1236 CopyLength = EndOfElement - StartOfElement + 1;
1237 Found = StrDuplicate(&InString[StartOfElement]);
1238 if (Found != NULL)
1239 Found[CopyLength] = 0;
1240 } // if (EndOfElement >= StartOfElement)
1241 } // if (EndOfElement > 0)
1242 return (Found);
1243 } // CHAR16 *FindNumbers()
1244
1245 // Find the #Index element (numbered from 0) in a comma-delimited string
1246 // of elements.
1247 // Returns the found element, or NULL if Index is out of range or InString
1248 // is NULL. Note that the calling function is responsible for freeing the
1249 // memory associated with the returned string pointer.
1250 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1251 UINTN StartPos = 0, CurPos = 0;
1252 BOOLEAN Found = FALSE;
1253 CHAR16 *FoundString = NULL;
1254
1255 if (InString != NULL) {
1256 // After while() loop, StartPos marks start of item #Index
1257 while ((Index > 0) && (CurPos < StrLen(InString))) {
1258 if (InString[CurPos] == L',') {
1259 Index--;
1260 StartPos = CurPos + 1;
1261 } // if
1262 CurPos++;
1263 } // while
1264 // After while() loop, CurPos is one past the end of the element
1265 while ((CurPos < StrLen(InString)) && (!Found)) {
1266 if (InString[CurPos] == L',')
1267 Found = TRUE;
1268 else
1269 CurPos++;
1270 } // while
1271 if (Index == 0)
1272 FoundString = StrDuplicate(&InString[StartPos]);
1273 if (FoundString != NULL)
1274 FoundString[CurPos - StartPos] = 0;
1275 } // if
1276 return (FoundString);
1277 } // CHAR16 *FindCommaDelimited()