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