]> code.delx.au - refind/blob - refind/lib.c
4989076e88bad395a9a4efaf8d4886eac82c390d
[refind] / refind / lib.c
1 /*
2 * refind/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-2013 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 "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
51 //#include "../include/UsbMass.h"
52
53 #ifdef __MAKEWITH_GNUEFI
54 #define EfiReallocatePool ReallocatePool
55 #else
56 #define LibLocateHandle gBS->LocateHandleBuffer
57 #define DevicePathProtocol gEfiDevicePathProtocolGuid
58 #define BlockIoProtocol gEfiBlockIoProtocolGuid
59 #define LibFileSystemInfo EfiLibFileSystemInfo
60 #define LibOpenRoot EfiLibOpenRoot
61 EFI_DEVICE_PATH EndDevicePath[] = {
62 {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
63 };
64
65 //#define EndDevicePath DevicePath
66 #endif
67
68 // "Magic" signatures for various filesystems
69 #define FAT_MAGIC 0xAA55
70 #define EXT2_SUPER_MAGIC 0xEF53
71 #define HFSPLUS_MAGIC1 0x2B48
72 #define HFSPLUS_MAGIC2 0x5848
73 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
74 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
75 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
76 #define BTRFS_SIGNATURE "_BHRfS_M"
77
78 // variables
79
80 EFI_HANDLE SelfImageHandle;
81 EFI_LOADED_IMAGE *SelfLoadedImage;
82 EFI_FILE *SelfRootDir;
83 EFI_FILE *SelfDir;
84 CHAR16 *SelfDirPath;
85
86 REFIT_VOLUME *SelfVolume = NULL;
87 REFIT_VOLUME **Volumes = NULL;
88 UINTN VolumesCount = 0;
89
90 // Maximum size for disk sectors
91 #define SECTOR_SIZE 4096
92
93 // Number of bytes to read from a partition to determine its filesystem type
94 // and identify its boot loader, and hence probable BIOS-mode OS installation
95 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
96
97
98 // functions
99
100 static EFI_STATUS FinishInitRefitLib(VOID);
101
102 static VOID UninitVolumes(VOID);
103
104 //
105 // self recognition stuff
106 //
107
108 // Converts forward slashes to backslashes, removes duplicate slashes, and
109 // removes slashes from both the start and end of the pathname.
110 // Necessary because some (buggy?) EFI implementations produce "\/" strings
111 // in pathnames, because some user inputs can produce duplicate directory
112 // separators, and because we want consistent start and end slashes for
113 // directory comparisons. A special case: If the PathName refers to root,
114 // return "/", since some firmware implementations flake out if this
115 // isn't present.
116 VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
117 CHAR16 *NewName;
118 UINTN i, Length, FinalChar = 0;
119 BOOLEAN LastWasSlash = FALSE;
120
121 Length = StrLen(PathName);
122 NewName = AllocateZeroPool(sizeof(CHAR16) * (Length + 2));
123 if (NewName != NULL) {
124 for (i = 0; i < StrLen(PathName); i++) {
125 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
126 if ((!LastWasSlash) && (FinalChar != 0))
127 NewName[FinalChar++] = L'\\';
128 LastWasSlash = TRUE;
129 } else {
130 NewName[FinalChar++] = PathName[i];
131 LastWasSlash = FALSE;
132 } // if/else
133 } // for
134 NewName[FinalChar] = 0;
135 if ((FinalChar > 0) && (NewName[FinalChar - 1] == L'\\'))
136 NewName[--FinalChar] = 0;
137 if (FinalChar == 0) {
138 NewName[0] = L'\\';
139 NewName[1] = 0;
140 }
141 // Copy the transformed name back....
142 StrCpy(PathName, NewName);
143 FreePool(NewName);
144 } // if allocation OK
145 } // CleanUpPathNameSlashes()
146
147 // Splits an EFI device path into device and filename components. For instance, if InString is
148 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
149 // this function will truncate that input to
150 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
151 // and return bzImage-3.5.1.efi as its return value.
152 // It does this by searching for the last ")" character in InString, copying everything
153 // after that string (after some cleanup) as the return value, and truncating the original
154 // input value.
155 // If InString contains no ")" character, this function leaves the original input string
156 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
157 static CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
158 INTN i;
159 CHAR16 *FileName = NULL;
160 BOOLEAN Found = FALSE;
161
162 if (InString != NULL) {
163 i = StrLen(InString) - 1;
164 while ((i >= 0) && (!Found)) {
165 if (InString[i] == L')') {
166 Found = TRUE;
167 FileName = StrDuplicate(&InString[i + 1]);
168 CleanUpPathNameSlashes(FileName);
169 InString[i + 1] = '\0';
170 } // if
171 i--;
172 } // while
173 if (FileName == NULL)
174 FileName = StrDuplicate(InString);
175 } // if
176 return FileName;
177 } // static CHAR16* SplitDeviceString()
178
179 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
180 {
181 EFI_STATUS Status;
182 CHAR16 *DevicePathAsString, *Temp;
183
184 SelfImageHandle = ImageHandle;
185 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
186 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
187 return EFI_LOAD_ERROR;
188
189 // find the current directory
190 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
191 CleanUpPathNameSlashes(DevicePathAsString);
192 MyFreePool(SelfDirPath);
193 Temp = FindPath(DevicePathAsString);
194 SelfDirPath = SplitDeviceString(Temp);
195 MyFreePool(DevicePathAsString);
196 MyFreePool(Temp);
197
198 return FinishInitRefitLib();
199 }
200
201 // called before running external programs to close open file handles
202 VOID UninitRefitLib(VOID)
203 {
204 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
205 // See the comment on it there.
206 if(SelfRootDir == SelfVolume->RootDir)
207 SelfRootDir=0;
208
209 UninitVolumes();
210
211 if (SelfDir != NULL) {
212 refit_call1_wrapper(SelfDir->Close, SelfDir);
213 SelfDir = NULL;
214 }
215
216 if (SelfRootDir != NULL) {
217 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
218 SelfRootDir = NULL;
219 }
220 }
221
222 // called after running external programs to re-open file handles
223 EFI_STATUS ReinitRefitLib(VOID)
224 {
225 ReinitVolumes();
226
227 if ((ST->Hdr.Revision >> 16) == 1) {
228 // Below two lines were in rEFIt, but seem to cause system crashes or
229 // reboots when launching OSes after returning from programs on most
230 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
231 // installation volume" (see the next function) when returning from
232 // programs when these two lines are removed, and it often crashes
233 // when returning from a program or when launching a second program
234 // with these lines removed. Therefore, the preceding if() statement
235 // executes these lines only on EFIs with a major version number of 1
236 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
237 // of hardware on which to test is limited, though, so this may be the
238 // wrong test, or there may be a better way to fix this problem.
239 // TODO: Figure out cause of above weirdness and fix it more
240 // reliably!
241 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
242 SelfRootDir = SelfVolume->RootDir;
243 } // if
244
245 return FinishInitRefitLib();
246 }
247
248 static EFI_STATUS FinishInitRefitLib(VOID)
249 {
250 EFI_STATUS Status;
251
252 if (SelfRootDir == NULL) {
253 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
254 if (SelfRootDir == NULL) {
255 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
256 return EFI_LOAD_ERROR;
257 }
258 }
259
260 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
261 if (CheckFatalError(Status, L"while opening our installation directory"))
262 return EFI_LOAD_ERROR;
263
264 return EFI_SUCCESS;
265 }
266
267 //
268 // list functions
269 //
270
271 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
272 {
273 UINTN AllocateCount;
274
275 *ElementCount = InitialElementCount;
276 if (*ElementCount > 0) {
277 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
278 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
279 } else {
280 *ListPtr = NULL;
281 }
282 }
283
284 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
285 {
286 UINTN AllocateCount;
287
288 if ((*ElementCount & 7) == 0) {
289 AllocateCount = *ElementCount + 8;
290 if (*ElementCount == 0)
291 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
292 else
293 *ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
294 }
295 (*ListPtr)[*ElementCount] = NewElement;
296 (*ElementCount)++;
297 } /* VOID AddListElement() */
298
299 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
300 {
301 UINTN i;
302
303 if ((*ElementCount > 0) && (**ListPtr != NULL)) {
304 for (i = 0; i < *ElementCount; i++) {
305 // TODO: call a user-provided routine for each element here
306 MyFreePool((*ListPtr)[i]);
307 }
308 MyFreePool(*ListPtr);
309 }
310 } // VOID FreeList()
311
312 //
313 // firmware device path discovery
314 //
315
316 static UINT8 LegacyLoaderMediaPathData[] = {
317 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
318 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
319 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
320 };
321 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
322
323 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
324 {
325 EFI_STATUS Status;
326 UINTN HandleCount = 0;
327 UINTN HandleIndex, HardcodedIndex;
328 EFI_HANDLE *Handles;
329 EFI_HANDLE Handle;
330 UINTN PathCount = 0;
331 UINTN PathIndex;
332 EFI_LOADED_IMAGE *LoadedImage;
333 EFI_DEVICE_PATH *DevicePath;
334 BOOLEAN Seen;
335
336 MaxPaths--; // leave space for the terminating NULL pointer
337
338 // get all LoadedImage handles
339 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL, &HandleCount, &Handles);
340 if (CheckError(Status, L"while listing LoadedImage handles")) {
341 if (HardcodedPathList) {
342 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
343 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
344 }
345 PathList[PathCount] = NULL;
346 return;
347 }
348 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
349 Handle = Handles[HandleIndex];
350
351 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
352 if (EFI_ERROR(Status))
353 continue; // This can only happen if the firmware scewed up, ignore it.
354
355 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
356 if (EFI_ERROR(Status))
357 continue; // This happens, ignore it.
358
359 // Only grab memory range nodes
360 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
361 continue;
362
363 // Check if we have this device path in the list already
364 // WARNING: This assumes the first node in the device path is unique!
365 Seen = FALSE;
366 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
367 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
368 continue;
369 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
370 Seen = TRUE;
371 break;
372 }
373 }
374 if (Seen)
375 continue;
376
377 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
378 }
379 MyFreePool(Handles);
380
381 if (HardcodedPathList) {
382 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
383 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
384 }
385 PathList[PathCount] = NULL;
386 }
387
388 //
389 // volume functions
390 //
391
392 // Return a pointer to a string containing a filesystem type name. If the
393 // filesystem type is unknown, a blank (but non-null) string is returned.
394 // The returned variable is a constant that should NOT be freed.
395 static CHAR16 *FSTypeName(IN UINT32 TypeCode) {
396 CHAR16 *retval = NULL;
397
398 switch (TypeCode) {
399 case FS_TYPE_FAT:
400 retval = L" FAT";
401 break;
402 case FS_TYPE_HFSPLUS:
403 retval = L" HFS+";
404 break;
405 case FS_TYPE_EXT2:
406 retval = L" ext2";
407 break;
408 case FS_TYPE_EXT3:
409 retval = L" ext3";
410 break;
411 case FS_TYPE_EXT4:
412 retval = L" ext4";
413 break;
414 case FS_TYPE_REISERFS:
415 retval = L" ReiserFS";
416 break;
417 case FS_TYPE_BTRFS:
418 retval = L" Btrfs";
419 break;
420 case FS_TYPE_ISO9660:
421 retval = L" ISO-9660";
422 break;
423 default:
424 retval = L"";
425 break;
426 } // switch
427 return retval;
428 } // CHAR16 *FSTypeName()
429
430 // Identify the filesystem type, if possible. Expects a Buffer containing
431 // the first few (normally 4096) bytes of the filesystem, and outputs a
432 // code representing the identified filesystem type.
433 static UINT32 IdentifyFilesystemType(IN UINT8 *Buffer, IN UINTN BufferSize) {
434 UINT32 FoundType = FS_TYPE_UNKNOWN;
435 UINT32 *Ext2Incompat, *Ext2Compat;
436 UINT16 *Magic16;
437 char *MagicString;
438
439 if (Buffer != NULL) {
440
441 if (BufferSize >= 512) {
442 Magic16 = (UINT16*) (Buffer + 510);
443 if (*Magic16 == FAT_MAGIC)
444 return FS_TYPE_FAT;
445 } // search for FAT magic
446
447 if (BufferSize >= (1024 + 100)) {
448 Magic16 = (UINT16*) (Buffer + 1024 + 56);
449 if (*Magic16 == EXT2_SUPER_MAGIC) { // ext2/3/4
450 Ext2Compat = (UINT32*) (Buffer + 1024 + 92);
451 Ext2Incompat = (UINT32*) (Buffer + 1024 + 96);
452 if ((*Ext2Incompat & 0x0040) || (*Ext2Incompat & 0x0200)) { // check for extents or flex_bg
453 return FS_TYPE_EXT4;
454 } else if (*Ext2Compat & 0x0004) { // check for journal
455 return FS_TYPE_EXT3;
456 } else { // none of these features; presume it's ext2...
457 return FS_TYPE_EXT2;
458 }
459 }
460 } // search for ext2/3/4 magic
461
462 if (BufferSize >= (65536 + 62)) {
463 MagicString = (char*) (Buffer + 65536 + 52);
464 if ((CompareMem(MagicString, REISERFS_SUPER_MAGIC_STRING, 8) == 0) ||
465 (CompareMem(MagicString, REISER2FS_SUPER_MAGIC_STRING, 9) == 0) ||
466 (CompareMem(MagicString, REISER2FS_JR_SUPER_MAGIC_STRING, 9) == 0)) {
467 return FS_TYPE_REISERFS;
468 } // if
469 } // search for ReiserFS magic
470
471 if (BufferSize >= (65536 + 64 + 8)) {
472 MagicString = (char*) (Buffer + 65536 + 64);
473 if (CompareMem(MagicString, BTRFS_SIGNATURE, 8) == 0)
474 return FS_TYPE_BTRFS;
475 } // search for Btrfs magic
476
477 if (BufferSize >= (1024 + 2)) {
478 Magic16 = (UINT16*) (Buffer + 1024);
479 if ((*Magic16 == HFSPLUS_MAGIC1) || (*Magic16 == HFSPLUS_MAGIC2)) {
480 return FS_TYPE_HFSPLUS;
481 }
482 } // search for HFS+ magic
483 } // if (Buffer != NULL)
484
485 return FoundType;
486 } // UINT32 IdentifyFilesystemType()
487
488 static VOID ScanVolumeBootcode(REFIT_VOLUME *Volume, BOOLEAN *Bootable)
489 {
490 EFI_STATUS Status;
491 UINT8 Buffer[SAMPLE_SIZE];
492 UINTN i;
493 MBR_PARTITION_INFO *MbrTable;
494 BOOLEAN MbrTableFound;
495
496 Volume->HasBootCode = FALSE;
497 Volume->OSIconName = NULL;
498 Volume->OSName = NULL;
499 *Bootable = FALSE;
500
501 if (Volume->BlockIO == NULL)
502 return;
503 if (Volume->BlockIO->Media->BlockSize > SAMPLE_SIZE)
504 return; // our buffer is too small...
505
506 // look at the boot sector (this is used for both hard disks and El Torito images!)
507 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
508 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
509 Volume->BlockIOOffset, SAMPLE_SIZE, Buffer);
510 if (!EFI_ERROR(Status)) {
511
512 Volume->FSType = IdentifyFilesystemType(Buffer, SAMPLE_SIZE);
513 if ((*((UINT16 *)(Buffer + 510)) == 0xaa55 && Buffer[0] != 0) && (FindMem(Buffer, 512, "EXFAT", 5) == -1)) {
514 *Bootable = TRUE;
515 Volume->HasBootCode = TRUE;
516 }
517
518 // detect specific boot codes
519 if (CompareMem(Buffer + 2, "LILO", 4) == 0 ||
520 CompareMem(Buffer + 6, "LILO", 4) == 0 ||
521 CompareMem(Buffer + 3, "SYSLINUX", 8) == 0 ||
522 FindMem(Buffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
523 Volume->HasBootCode = TRUE;
524 Volume->OSIconName = L"linux";
525 Volume->OSName = L"Linux";
526
527 } else if (FindMem(Buffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
528 Volume->HasBootCode = TRUE;
529 Volume->OSIconName = L"grub,linux";
530 Volume->OSName = L"Linux";
531
532 // // Below doesn't produce a bootable entry, so commented out for the moment....
533 // // GRUB in BIOS boot partition:
534 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
535 // Volume->HasBootCode = TRUE;
536 // Volume->OSIconName = L"grub,linux";
537 // Volume->OSName = L"Linux";
538 // Volume->VolName = L"BIOS Boot Partition";
539 // *Bootable = TRUE;
540
541 } else if ((*((UINT32 *)(Buffer + 502)) == 0 &&
542 *((UINT32 *)(Buffer + 506)) == 50000 &&
543 *((UINT16 *)(Buffer + 510)) == 0xaa55) ||
544 FindMem(Buffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
545 Volume->HasBootCode = TRUE;
546 Volume->OSIconName = L"freebsd";
547 Volume->OSName = L"FreeBSD";
548
549 } else if (FindMem(Buffer, 512, "!Loading", 8) >= 0 ||
550 FindMem(Buffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
551 Volume->HasBootCode = TRUE;
552 Volume->OSIconName = L"openbsd";
553 Volume->OSName = L"OpenBSD";
554
555 } else if (FindMem(Buffer, 512, "Not a bootxx image", 18) >= 0 ||
556 *((UINT32 *)(Buffer + 1028)) == 0x7886b6d1) {
557 Volume->HasBootCode = TRUE;
558 Volume->OSIconName = L"netbsd";
559 Volume->OSName = L"NetBSD";
560
561 } else if (FindMem(Buffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
562 Volume->HasBootCode = TRUE;
563 Volume->OSIconName = L"win";
564 Volume->OSName = L"Windows";
565
566 } else if (FindMem(Buffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
567 Volume->HasBootCode = TRUE;
568 Volume->OSIconName = L"winvista,win";
569 Volume->OSName = L"Windows";
570
571 } else if (FindMem(Buffer, 512, "CPUBOOT SYS", 11) >= 0 ||
572 FindMem(Buffer, 512, "KERNEL SYS", 11) >= 0) {
573 Volume->HasBootCode = TRUE;
574 Volume->OSIconName = L"freedos";
575 Volume->OSName = L"FreeDOS";
576
577 } else if (FindMem(Buffer, 512, "OS2LDR", 6) >= 0 ||
578 FindMem(Buffer, 512, "OS2BOOT", 7) >= 0) {
579 Volume->HasBootCode = TRUE;
580 Volume->OSIconName = L"ecomstation";
581 Volume->OSName = L"eComStation";
582
583 } else if (FindMem(Buffer, 512, "Be Boot Loader", 14) >= 0) {
584 Volume->HasBootCode = TRUE;
585 Volume->OSIconName = L"beos";
586 Volume->OSName = L"BeOS";
587
588 } else if (FindMem(Buffer, 512, "yT Boot Loader", 14) >= 0) {
589 Volume->HasBootCode = TRUE;
590 Volume->OSIconName = L"zeta,beos";
591 Volume->OSName = L"ZETA";
592
593 } else if (FindMem(Buffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
594 FindMem(Buffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
595 Volume->HasBootCode = TRUE;
596 Volume->OSIconName = L"haiku,beos";
597 Volume->OSName = L"Haiku";
598
599 }
600
601 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
602 // need to fix AddLegacyEntry in main.c.
603
604 #if REFIT_DEBUG > 0
605 Print(L" Result of bootcode detection: %s %s (%s)\n",
606 Volume->HasBootCode ? L"bootable" : L"non-bootable",
607 Volume->OSName, Volume->OSIconName);
608 #endif
609
610 // dummy FAT boot sector (created by OS X's newfs_msdos)
611 if (FindMem(Buffer, 512, "Non-system disk", 15) >= 0)
612 Volume->HasBootCode = FALSE;
613
614 // dummy FAT boot sector (created by Linux's mkdosfs)
615 if (FindMem(Buffer, 512, "This is not a bootable disk", 27) >= 0)
616 Volume->HasBootCode = FALSE;
617
618 // dummy FAT boot sector (created by Windows)
619 if (FindMem(Buffer, 512, "Press any key to restart", 24) >= 0)
620 Volume->HasBootCode = FALSE;
621
622 // check for MBR partition table
623 if (*((UINT16 *)(Buffer + 510)) == 0xaa55) {
624 MbrTableFound = FALSE;
625 MbrTable = (MBR_PARTITION_INFO *)(Buffer + 446);
626 for (i = 0; i < 4; i++)
627 if (MbrTable[i].StartLBA && MbrTable[i].Size)
628 MbrTableFound = TRUE;
629 for (i = 0; i < 4; i++)
630 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
631 MbrTableFound = FALSE;
632 if (MbrTableFound) {
633 Volume->MbrPartitionTable = AllocatePool(4 * 16);
634 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
635 }
636 }
637
638 } else {
639 #if REFIT_DEBUG > 0
640 CheckError(Status, L"while reading boot sector");
641 #endif
642 }
643 } /* VOID ScanVolumeBootcode() */
644
645 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
646 VOID SetVolumeBadgeIcon(REFIT_VOLUME *Volume)
647 {
648 if (Volume->VolBadgeImage == NULL) {
649 Volume->VolBadgeImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeBadge", 128);
650 }
651
652 if (Volume->VolBadgeImage == NULL) {
653 switch (Volume->DiskKind) {
654 case DISK_KIND_INTERNAL:
655 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
656 break;
657 case DISK_KIND_EXTERNAL:
658 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
659 break;
660 case DISK_KIND_OPTICAL:
661 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
662 break;
663 } // switch()
664 }
665 } // VOID SetVolumeBadgeIcon()
666
667 // Return a string representing the input size in IEEE-1541 units.
668 // The calling function is responsible for freeing the allocated memory.
669 static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
670 UINT64 SizeInIeee;
671 UINTN Index = 0, NumPrefixes;
672 CHAR16 *Units, *Prefixes = L" KMGTPEZ";
673 CHAR16 *TheValue;
674
675 TheValue = AllocateZeroPool(sizeof(CHAR16) * 256);
676 if (TheValue != NULL) {
677 NumPrefixes = StrLen(Prefixes);
678 SizeInIeee = SizeInBytes;
679 while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
680 Index++;
681 SizeInIeee /= 1024;
682 } // while
683 if (Prefixes[Index] == ' ') {
684 Units = StrDuplicate(L"-byte");
685 } else {
686 Units = StrDuplicate(L" iB");
687 Units[1] = Prefixes[Index];
688 } // if/else
689 SPrint(TheValue, 255, L"%ld%s", SizeInIeee, Units);
690 } // if
691 return TheValue;
692 } // CHAR16 *SizeInSIUnits()
693
694 // Return a name for the volume. Ideally this should be the label for the
695 // filesystem it contains, but this function falls back to describing the
696 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
697 // this information can be extracted.
698 // The calling function is responsible for freeing the memory allocated
699 // for the name string.
700 static CHAR16 *GetVolumeName(IN REFIT_VOLUME *Volume) {
701 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
702 CHAR16 *FoundName = NULL;
703 CHAR16 *SISize, *TypeName;
704
705 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
706 if (FileSystemInfoPtr != NULL) { // we have filesystem information (size, label)....
707 if ((FileSystemInfoPtr->VolumeLabel != NULL) && (StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
708 FoundName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
709 }
710
711 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
712 // this so that we can build a new name that includes the size....
713 if ((FoundName != NULL) && (StrCmp(FoundName, L"HFS+ volume") == 0) && (Volume->FSType == FS_TYPE_HFSPLUS)) {
714 MyFreePool(FoundName);
715 FoundName = NULL;
716 } // if rEFInd HFS+ driver suspected
717
718 if (FoundName == NULL) { // filesystem has no name, so use fs type and size
719 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
720 if (FoundName != NULL) {
721 SISize = SizeInIEEEUnits(FileSystemInfoPtr->VolumeSize);
722 SPrint(FoundName, 255, L"%s%s volume", SISize, FSTypeName(Volume->FSType));
723 MyFreePool(SISize);
724 } // if allocated memory OK
725 } // if (FoundName == NULL)
726
727 FreePool(FileSystemInfoPtr);
728
729 } else { // fs driver not returning info; fall back on our own information....
730 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
731 if (FoundName != NULL) {
732 TypeName = FSTypeName(Volume->FSType); // NOTE: Don't free TypeName; function returns constant
733 if (StrLen(TypeName) > 0)
734 SPrint(FoundName, 255, L"%s volume", FSTypeName(Volume->FSType));
735 else
736 SPrint(FoundName, 255, L"unknown volume");
737 } // if allocated memory OK
738 } // if
739
740 // TODO: Above could be improved/extended, in case filesystem name is not found,
741 // such as:
742 // - use partition label
743 // - use or add disk/partition number (e.g., "(hd0,2)")
744
745 // Desperate fallback name....
746 if (FoundName == NULL) {
747 FoundName = StrDuplicate(L"unknown volume");
748 }
749 return FoundName;
750 } // static CHAR16 *GetVolumeName()
751
752 VOID ScanVolume(REFIT_VOLUME *Volume)
753 {
754 EFI_STATUS Status;
755 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
756 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
757 EFI_HANDLE WholeDiskHandle;
758 UINTN PartialLength;
759 BOOLEAN Bootable;
760
761 // get device path
762 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
763 #if REFIT_DEBUG > 0
764 if (Volume->DevicePath != NULL) {
765 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
766 #if REFIT_DEBUG >= 2
767 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
768 #endif
769 }
770 #endif
771
772 Volume->DiskKind = DISK_KIND_INTERNAL; // default
773
774 // get block i/o
775 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
776 if (EFI_ERROR(Status)) {
777 Volume->BlockIO = NULL;
778 Print(L"Warning: Can't get BlockIO protocol.\n");
779 } else {
780 if (Volume->BlockIO->Media->BlockSize == 2048)
781 Volume->DiskKind = DISK_KIND_OPTICAL;
782 }
783
784 // scan for bootcode and MBR table
785 Bootable = FALSE;
786 ScanVolumeBootcode(Volume, &Bootable);
787
788 // detect device type
789 DevicePath = Volume->DevicePath;
790 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
791 NextDevicePath = NextDevicePathNode(DevicePath);
792
793 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
794 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
795 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
796 DevicePathSubType(DevicePath) == MSG_1394_DP ||
797 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
798 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
799 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
800 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
801 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
802 Bootable = TRUE;
803 }
804
805 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
806 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
807 // TODO: also check for Boot Camp GUID
808 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
809 }
810
811 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
812 // make a device path for the whole device
813 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
814 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
815 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
816 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
817
818 // get the handle for that path
819 RemainingDevicePath = DiskDevicePath;
820 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
821 FreePool(DiskDevicePath);
822
823 if (!EFI_ERROR(Status)) {
824 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
825
826 // get the device path for later
827 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
828 if (!EFI_ERROR(Status)) {
829 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
830 }
831
832 // look at the BlockIO protocol
833 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
834 if (!EFI_ERROR(Status)) {
835
836 // check the media block size
837 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
838 Volume->DiskKind = DISK_KIND_OPTICAL;
839
840 } else {
841 Volume->WholeDiskBlockIO = NULL;
842 //CheckError(Status, L"from HandleProtocol");
843 }
844 } //else
845 // CheckError(Status, L"from LocateDevicePath");
846 }
847
848 DevicePath = NextDevicePath;
849 } // while
850
851 if (!Bootable) {
852 #if REFIT_DEBUG > 0
853 if (Volume->HasBootCode)
854 Print(L" Volume considered non-bootable, but boot code is present\n");
855 #endif
856 Volume->HasBootCode = FALSE;
857 }
858
859 // open the root directory of the volume
860 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
861
862 // Set volume icon based on .VolumeBadge icon or disk kind
863 SetVolumeBadgeIcon(Volume);
864
865 if (Volume->RootDir == NULL) {
866 Volume->IsReadable = FALSE;
867 return;
868 } else {
869 Volume->IsReadable = TRUE;
870 }
871
872 Volume->VolName = GetVolumeName(Volume);
873
874 // get custom volume icons if present
875 if (!Volume->VolIconImage)
876 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", 128);
877 } // ScanVolume()
878
879 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
880 {
881 EFI_STATUS Status;
882 REFIT_VOLUME *Volume;
883 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
884 UINTN i;
885 UINTN LogicalPartitionIndex = 4;
886 UINT8 SectorBuffer[512];
887 BOOLEAN Bootable;
888 MBR_PARTITION_INFO *EMbrTable;
889
890 ExtBase = MbrEntry->StartLBA;
891
892 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
893 // read current EMBR
894 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
895 WholeDiskVolume->BlockIO,
896 WholeDiskVolume->BlockIO->Media->MediaId,
897 ExtCurrent, 512, SectorBuffer);
898 if (EFI_ERROR(Status))
899 break;
900 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
901 break;
902 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
903
904 // scan logical partitions in this EMBR
905 NextExtCurrent = 0;
906 for (i = 0; i < 4; i++) {
907 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
908 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
909 break;
910 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
911 // set next ExtCurrent
912 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
913 break;
914 } else {
915
916 // found a logical partition
917 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
918 Volume->DiskKind = WholeDiskVolume->DiskKind;
919 Volume->IsMbrPartition = TRUE;
920 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
921 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
922 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
923 Volume->BlockIO = WholeDiskVolume->BlockIO;
924 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
925 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
926
927 Bootable = FALSE;
928 ScanVolumeBootcode(Volume, &Bootable);
929 if (!Bootable)
930 Volume->HasBootCode = FALSE;
931
932 SetVolumeBadgeIcon(Volume);
933
934 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
935
936 }
937 }
938 }
939 } /* VOID ScanExtendedPartition() */
940
941 VOID ScanVolumes(VOID)
942 {
943 EFI_STATUS Status;
944 EFI_HANDLE *Handles;
945 REFIT_VOLUME *Volume, *WholeDiskVolume;
946 MBR_PARTITION_INFO *MbrTable;
947 UINTN HandleCount = 0;
948 UINTN HandleIndex;
949 UINTN VolumeIndex, VolumeIndex2;
950 UINTN PartitionIndex;
951 UINTN SectorSum, i, VolNumber = 0;
952 UINT8 *SectorBuffer1, *SectorBuffer2;
953
954 MyFreePool(Volumes);
955 Volumes = NULL;
956 VolumesCount = 0;
957
958 // get all filesystem handles
959 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
960 // was: &FileSystemProtocol
961 if (Status == EFI_NOT_FOUND) {
962 return; // no filesystems. strange, but true...
963 }
964 if (CheckError(Status, L"while listing all file systems"))
965 return;
966
967 // first pass: collect information about all handles
968 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
969 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
970 Volume->DeviceHandle = Handles[HandleIndex];
971 ScanVolume(Volume);
972 if (Volume->IsReadable)
973 Volume->VolNumber = VolNumber++;
974 else
975 Volume->VolNumber = VOL_UNREADABLE;
976
977 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
978
979 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
980 SelfVolume = Volume;
981 }
982 MyFreePool(Handles);
983
984 if (SelfVolume == NULL)
985 Print(L"WARNING: SelfVolume not found");
986
987 // second pass: relate partitions and whole disk devices
988 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
989 Volume = Volumes[VolumeIndex];
990 // check MBR partition table for extended partitions
991 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
992 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
993 Volume->MbrPartitionTable != NULL) {
994 MbrTable = Volume->MbrPartitionTable;
995 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
996 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
997 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
998 }
999 }
1000 }
1001
1002 // search for corresponding whole disk volume entry
1003 WholeDiskVolume = NULL;
1004 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1005 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1006 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1007 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1008 Volumes[VolumeIndex2]->BlockIOOffset == 0)
1009 WholeDiskVolume = Volumes[VolumeIndex2];
1010 }
1011 }
1012
1013 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1014 // check if this volume is one of the partitions in the table
1015 MbrTable = WholeDiskVolume->MbrPartitionTable;
1016 SectorBuffer1 = AllocatePool(512);
1017 SectorBuffer2 = AllocatePool(512);
1018 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1019 // check size
1020 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1021 continue;
1022
1023 // compare boot sector read through offset vs. directly
1024 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1025 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1026 Volume->BlockIOOffset, 512, SectorBuffer1);
1027 if (EFI_ERROR(Status))
1028 break;
1029 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1030 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1031 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1032 if (EFI_ERROR(Status))
1033 break;
1034 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1035 continue;
1036 SectorSum = 0;
1037 for (i = 0; i < 512; i++)
1038 SectorSum += SectorBuffer1[i];
1039 if (SectorSum < 1000)
1040 continue;
1041
1042 // TODO: mark entry as non-bootable if it is an extended partition
1043
1044 // now we're reasonably sure the association is correct...
1045 Volume->IsMbrPartition = TRUE;
1046 Volume->MbrPartitionIndex = PartitionIndex;
1047 if (Volume->VolName == NULL) {
1048 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1049 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1050 }
1051 break;
1052 }
1053
1054 MyFreePool(SectorBuffer1);
1055 MyFreePool(SectorBuffer2);
1056 }
1057
1058 } // for
1059 } /* VOID ScanVolumes() */
1060
1061 static VOID UninitVolumes(VOID)
1062 {
1063 REFIT_VOLUME *Volume;
1064 UINTN VolumeIndex;
1065
1066 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1067 Volume = Volumes[VolumeIndex];
1068
1069 if (Volume->RootDir != NULL) {
1070 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
1071 Volume->RootDir = NULL;
1072 }
1073
1074 Volume->DeviceHandle = NULL;
1075 Volume->BlockIO = NULL;
1076 Volume->WholeDiskBlockIO = NULL;
1077 }
1078 }
1079
1080 VOID ReinitVolumes(VOID)
1081 {
1082 EFI_STATUS Status;
1083 REFIT_VOLUME *Volume;
1084 UINTN VolumeIndex;
1085 EFI_DEVICE_PATH *RemainingDevicePath;
1086 EFI_HANDLE DeviceHandle, WholeDiskHandle;
1087
1088 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1089 Volume = Volumes[VolumeIndex];
1090
1091 if (Volume->DevicePath != NULL) {
1092 // get the handle for that path
1093 RemainingDevicePath = Volume->DevicePath;
1094 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
1095
1096 if (!EFI_ERROR(Status)) {
1097 Volume->DeviceHandle = DeviceHandle;
1098
1099 // get the root directory
1100 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1101
1102 } else
1103 CheckError(Status, L"from LocateDevicePath");
1104 }
1105
1106 if (Volume->WholeDiskDevicePath != NULL) {
1107 // get the handle for that path
1108 RemainingDevicePath = Volume->WholeDiskDevicePath;
1109 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
1110
1111 if (!EFI_ERROR(Status)) {
1112 // get the BlockIO protocol
1113 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
1114 if (EFI_ERROR(Status)) {
1115 Volume->WholeDiskBlockIO = NULL;
1116 CheckError(Status, L"from HandleProtocol");
1117 }
1118 } else
1119 CheckError(Status, L"from LocateDevicePath");
1120 }
1121 }
1122 }
1123
1124 //
1125 // file and dir functions
1126 //
1127
1128 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1129 {
1130 EFI_STATUS Status;
1131 EFI_FILE_HANDLE TestFile;
1132
1133 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1134 if (Status == EFI_SUCCESS) {
1135 refit_call1_wrapper(TestFile->Close, TestFile);
1136 return TRUE;
1137 }
1138 return FALSE;
1139 }
1140
1141 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1142 {
1143 EFI_STATUS Status;
1144 VOID *Buffer;
1145 UINTN LastBufferSize, BufferSize;
1146 INTN IterCount;
1147
1148 for (;;) {
1149
1150 // free pointer from last call
1151 if (*DirEntry != NULL) {
1152 FreePool(*DirEntry);
1153 *DirEntry = NULL;
1154 }
1155
1156 // read next directory entry
1157 LastBufferSize = BufferSize = 256;
1158 Buffer = AllocatePool(BufferSize);
1159 for (IterCount = 0; ; IterCount++) {
1160 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1161 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1162 break;
1163 if (BufferSize <= LastBufferSize) {
1164 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1165 BufferSize = LastBufferSize * 2;
1166 #if REFIT_DEBUG > 0
1167 } else {
1168 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1169 #endif
1170 }
1171 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1172 LastBufferSize = BufferSize;
1173 }
1174 if (EFI_ERROR(Status)) {
1175 MyFreePool(Buffer);
1176 Buffer = NULL;
1177 break;
1178 }
1179
1180 // check for end of listing
1181 if (BufferSize == 0) { // end of directory listing
1182 MyFreePool(Buffer);
1183 Buffer = NULL;
1184 break;
1185 }
1186
1187 // entry is ready to be returned
1188 *DirEntry = (EFI_FILE_INFO *)Buffer;
1189
1190 // filter results
1191 if (FilterMode == 1) { // only return directories
1192 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1193 break;
1194 } else if (FilterMode == 2) { // only return files
1195 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1196 break;
1197 } else // no filter or unknown filter -> return everything
1198 break;
1199
1200 }
1201 return Status;
1202 }
1203
1204 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1205 {
1206 if (RelativePath == NULL) {
1207 DirIter->LastStatus = EFI_SUCCESS;
1208 DirIter->DirHandle = BaseDir;
1209 DirIter->CloseDirHandle = FALSE;
1210 } else {
1211 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1212 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1213 }
1214 DirIter->LastFileInfo = NULL;
1215 }
1216
1217 #ifndef __MAKEWITH_GNUEFI
1218 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1219
1220 static EFI_STATUS
1221 InitializeUnicodeCollationProtocol (VOID)
1222 {
1223 EFI_STATUS Status;
1224
1225 if (mUnicodeCollation != NULL) {
1226 return EFI_SUCCESS;
1227 }
1228
1229 //
1230 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1231 // instances first and then select one which support English language.
1232 // Current implementation just pick the first instance.
1233 //
1234 Status = gBS->LocateProtocol (
1235 &gEfiUnicodeCollation2ProtocolGuid,
1236 NULL,
1237 (VOID **) &mUnicodeCollation
1238 );
1239 if (EFI_ERROR(Status)) {
1240 Status = gBS->LocateProtocol (
1241 &gEfiUnicodeCollationProtocolGuid,
1242 NULL,
1243 (VOID **) &mUnicodeCollation
1244 );
1245
1246 }
1247 return Status;
1248 }
1249
1250 static BOOLEAN
1251 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1252 {
1253 if (!mUnicodeCollation) {
1254 InitializeUnicodeCollationProtocol();
1255 }
1256 if (mUnicodeCollation)
1257 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1258 return FALSE; // Shouldn't happen
1259 }
1260
1261 static VOID StrLwr (IN OUT CHAR16 *Str) {
1262 if (!mUnicodeCollation) {
1263 InitializeUnicodeCollationProtocol();
1264 }
1265 if (mUnicodeCollation)
1266 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1267 }
1268
1269 #endif
1270
1271 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1272 OUT EFI_FILE_INFO **DirEntry)
1273 {
1274 BOOLEAN KeepGoing = TRUE;
1275 UINTN i;
1276 CHAR16 *OnePattern;
1277
1278 if (DirIter->LastFileInfo != NULL) {
1279 FreePool(DirIter->LastFileInfo);
1280 DirIter->LastFileInfo = NULL;
1281 }
1282
1283 if (EFI_ERROR(DirIter->LastStatus))
1284 return FALSE; // stop iteration
1285
1286 do {
1287 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1288 if (EFI_ERROR(DirIter->LastStatus))
1289 return FALSE;
1290 if (DirIter->LastFileInfo == NULL) // end of listing
1291 return FALSE;
1292 if (FilePattern != NULL) {
1293 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1294 KeepGoing = FALSE;
1295 i = 0;
1296 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1297 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1298 KeepGoing = FALSE;
1299 } // while
1300 // else continue loop
1301 } else
1302 break;
1303 } while (KeepGoing && FilePattern);
1304
1305 *DirEntry = DirIter->LastFileInfo;
1306 return TRUE;
1307 }
1308
1309 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1310 {
1311 if (DirIter->LastFileInfo != NULL) {
1312 FreePool(DirIter->LastFileInfo);
1313 DirIter->LastFileInfo = NULL;
1314 }
1315 if (DirIter->CloseDirHandle)
1316 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1317 return DirIter->LastStatus;
1318 }
1319
1320 //
1321 // file name manipulation
1322 //
1323
1324 // Returns the filename portion (minus path name) of the
1325 // specified file
1326 CHAR16 * Basename(IN CHAR16 *Path)
1327 {
1328 CHAR16 *FileName;
1329 UINTN i;
1330
1331 FileName = Path;
1332
1333 if (Path != NULL) {
1334 for (i = StrLen(Path); i > 0; i--) {
1335 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1336 FileName = Path + i;
1337 break;
1338 }
1339 }
1340 }
1341
1342 return FileName;
1343 }
1344
1345 // Remove the .efi extension from FileName -- for instance, if FileName is
1346 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1347 // returns a copy of the original input.
1348 CHAR16 * StripEfiExtension(CHAR16 *FileName) {
1349 UINTN Length;
1350 CHAR16 *Copy = NULL;
1351
1352 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1353 Length = StrLen(Copy);
1354 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1355 if ((Length >= 4) && ((StriCmp(&Copy[Length - 4], L".efi") == 0) || (StriCmp(&Copy[Length - 4], L".EFI") == 0))) {
1356 Copy[Length - 4] = 0;
1357 } // if
1358 } // if
1359 return Copy;
1360 } // CHAR16 * StripExtension()
1361
1362 //
1363 // memory string search
1364 //
1365
1366 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1367 {
1368 UINT8 *BufferPtr;
1369 UINTN Offset;
1370
1371 BufferPtr = Buffer;
1372 BufferLength -= SearchStringLength;
1373 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1374 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1375 return (INTN)Offset;
1376 }
1377
1378 return -1;
1379 }
1380
1381 // Performs a case-insensitive search of BigStr for SmallStr.
1382 // Returns TRUE if found, FALSE if not.
1383 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1384 CHAR16 *SmallCopy, *BigCopy;
1385 BOOLEAN Found = FALSE;
1386 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1387
1388 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1389 SmallCopy = StrDuplicate(SmallStr);
1390 BigCopy = StrDuplicate(BigStr);
1391 StrLwr(SmallCopy);
1392 StrLwr(BigCopy);
1393 SmallLen = StrLen(SmallCopy);
1394 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1395 while ((!Found) && (StartPoint < NumCompares)) {
1396 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1397 } // while
1398 MyFreePool(SmallCopy);
1399 MyFreePool(BigCopy);
1400 } // if
1401
1402 return (Found);
1403 } // BOOLEAN StriSubCmp()
1404
1405 // Merges two strings, creating a new one and returning a pointer to it.
1406 // If AddChar != 0, the specified character is placed between the two original
1407 // strings (unless the first string is NULL or empty). The original input
1408 // string *First is de-allocated and replaced by the new merged string.
1409 // This is similar to StrCat, but safer and more flexible because
1410 // MergeStrings allocates memory that's the correct size for the
1411 // new merged string, so it can take a NULL *First and it cleans
1412 // up the old memory. It should *NOT* be used with a constant
1413 // *First, though....
1414 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1415 UINTN Length1 = 0, Length2 = 0;
1416 CHAR16* NewString;
1417
1418 if (*First != NULL)
1419 Length1 = StrLen(*First);
1420 if (Second != NULL)
1421 Length2 = StrLen(Second);
1422 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1423 if (NewString != NULL) {
1424 if ((*First != NULL) && (StrLen(*First) == 0)) {
1425 MyFreePool(*First);
1426 *First = NULL;
1427 }
1428 NewString[0] = L'\0';
1429 if (*First != NULL) {
1430 StrCat(NewString, *First);
1431 if (AddChar) {
1432 NewString[Length1] = AddChar;
1433 NewString[Length1 + 1] = '\0';
1434 } // if (AddChar)
1435 } // if (*First != NULL)
1436 if (Second != NULL)
1437 StrCat(NewString, Second);
1438 MyFreePool(*First);
1439 *First = NewString;
1440 } else {
1441 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1442 } // if/else
1443 } // static CHAR16* MergeStrings()
1444
1445 // Takes an input pathname (*Path) and returns the part of the filename from
1446 // the final dot onwards, converted to lowercase. If the filename includes
1447 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1448 // The calling function is responsible for freeing the memory associated with
1449 // the return value.
1450 CHAR16 *FindExtension(IN CHAR16 *Path) {
1451 CHAR16 *Extension;
1452 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1453 INTN i;
1454
1455 Extension = AllocateZeroPool(sizeof(CHAR16));
1456 if (Path) {
1457 i = StrLen(Path);
1458 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1459 if (Path[i] == L'.')
1460 Found = TRUE;
1461 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1462 FoundSlash = TRUE;
1463 if (!Found)
1464 i--;
1465 } // while
1466 if (Found) {
1467 MergeStrings(&Extension, &Path[i], 0);
1468 StrLwr(Extension);
1469 } // if (Found)
1470 } // if
1471 return (Extension);
1472 } // CHAR16 *FindExtension
1473
1474 // Takes an input pathname (*Path) and locates the final directory component
1475 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1476 // function returns the string 'foo'.
1477 // Assumes the pathname is separated with backslashes.
1478 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1479 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1480 CHAR16 *Found = NULL;
1481
1482 if (Path == NULL)
1483 return NULL;
1484
1485 PathLength = StrLen(Path);
1486 // Find start & end of target element
1487 for (i = 0; i < PathLength; i++) {
1488 if (Path[i] == '\\') {
1489 StartOfElement = EndOfElement;
1490 EndOfElement = i;
1491 } // if
1492 } // for
1493 // Extract the target element
1494 if (EndOfElement > 0) {
1495 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1496 StartOfElement++;
1497 } // while
1498 EndOfElement--;
1499 if (EndOfElement >= StartOfElement) {
1500 CopyLength = EndOfElement - StartOfElement + 1;
1501 Found = StrDuplicate(&Path[StartOfElement]);
1502 if (Found != NULL)
1503 Found[CopyLength] = 0;
1504 } // if (EndOfElement >= StartOfElement)
1505 } // if (EndOfElement > 0)
1506 return (Found);
1507 } // CHAR16 *FindLastDirName
1508
1509 // Returns the directory portion of a pathname. For instance,
1510 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1511 // string 'EFI\foo'. The calling function is responsible for
1512 // freeing the returned string's memory.
1513 CHAR16 *FindPath(IN CHAR16* FullPath) {
1514 UINTN i, LastBackslash = 0;
1515 CHAR16 *PathOnly = NULL;
1516
1517 if (FullPath != NULL) {
1518 for (i = 0; i < StrLen(FullPath); i++) {
1519 if (FullPath[i] == '\\')
1520 LastBackslash = i;
1521 } // for
1522 PathOnly = StrDuplicate(FullPath);
1523 PathOnly[LastBackslash] = 0;
1524 } // if
1525 return (PathOnly);
1526 }
1527
1528 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1529 // DeviceVolume, and returns that and the filename (*loader).
1530 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1531 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1532 UINTN i = 0;
1533 BOOLEAN Found = FALSE;
1534
1535 MyFreePool(*loader);
1536 MyFreePool(*DeviceVolume);
1537 *DeviceVolume = NULL;
1538 DeviceString = DevicePathToStr(loadpath);
1539 *loader = SplitDeviceString(DeviceString);
1540
1541 while ((i < VolumesCount) && (!Found)) {
1542 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1543 Temp = SplitDeviceString(VolumeDeviceString);
1544 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1545 Found = TRUE;
1546 *DeviceVolume = Volumes[i];
1547 }
1548 MyFreePool(Temp);
1549 MyFreePool(VolumeDeviceString);
1550 i++;
1551 } // while
1552
1553 MyFreePool(DeviceString);
1554 } // VOID FindVolumeAndFilename()
1555
1556 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1557 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1558 // the filename component in the original *Path variable and the split-off
1559 // volume component in the *VolName variable.
1560 // Returns TRUE if both components are found, FALSE otherwise.
1561 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1562 UINTN i = 0, Length;
1563 CHAR16 *Filename;
1564
1565 if (*Path == NULL)
1566 return FALSE;
1567
1568 if (*VolName != NULL) {
1569 MyFreePool(*VolName);
1570 *VolName = NULL;
1571 }
1572
1573 Length = StrLen(*Path);
1574 while ((i < Length) && ((*Path)[i] != L':')) {
1575 i++;
1576 } // while
1577
1578 if (i < Length) {
1579 Filename = StrDuplicate((*Path) + i + 1);
1580 (*Path)[i] = 0;
1581 *VolName = *Path;
1582 *Path = Filename;
1583 return TRUE;
1584 } else {
1585 return FALSE;
1586 }
1587 } // BOOLEAN SplitVolumeAndFilename()
1588
1589 // Returns all the digits in the input string, including intervening
1590 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1591 // this function returns "3.3.4-7". If InString contains no digits,
1592 // the return value is NULL.
1593 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1594 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1595 CHAR16 *Found = NULL;
1596
1597 if (InString == NULL)
1598 return NULL;
1599
1600 InLength = StartOfElement = StrLen(InString);
1601 // Find start & end of target element
1602 for (i = 0; i < InLength; i++) {
1603 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1604 if (StartOfElement > i)
1605 StartOfElement = i;
1606 if (EndOfElement < i)
1607 EndOfElement = i;
1608 } // if
1609 } // for
1610 // Extract the target element
1611 if (EndOfElement > 0) {
1612 if (EndOfElement >= StartOfElement) {
1613 CopyLength = EndOfElement - StartOfElement + 1;
1614 Found = StrDuplicate(&InString[StartOfElement]);
1615 if (Found != NULL)
1616 Found[CopyLength] = 0;
1617 } // if (EndOfElement >= StartOfElement)
1618 } // if (EndOfElement > 0)
1619 return (Found);
1620 } // CHAR16 *FindNumbers()
1621
1622 // Find the #Index element (numbered from 0) in a comma-delimited string
1623 // of elements.
1624 // Returns the found element, or NULL if Index is out of range or InString
1625 // is NULL. Note that the calling function is responsible for freeing the
1626 // memory associated with the returned string pointer.
1627 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1628 UINTN StartPos = 0, CurPos = 0;
1629 BOOLEAN Found = FALSE;
1630 CHAR16 *FoundString = NULL;
1631
1632 if (InString != NULL) {
1633 // After while() loop, StartPos marks start of item #Index
1634 while ((Index > 0) && (CurPos < StrLen(InString))) {
1635 if (InString[CurPos] == L',') {
1636 Index--;
1637 StartPos = CurPos + 1;
1638 } // if
1639 CurPos++;
1640 } // while
1641 // After while() loop, CurPos is one past the end of the element
1642 while ((CurPos < StrLen(InString)) && (!Found)) {
1643 if (InString[CurPos] == L',')
1644 Found = TRUE;
1645 else
1646 CurPos++;
1647 } // while
1648 if (Index == 0)
1649 FoundString = StrDuplicate(&InString[StartPos]);
1650 if (FoundString != NULL)
1651 FoundString[CurPos - StartPos] = 0;
1652 } // if
1653 return (FoundString);
1654 } // CHAR16 *FindCommaDelimited()
1655
1656 // Returns TRUE if SmallString is an element in the comma-delimited List,
1657 // FALSE otherwise. Performs comparison case-insensitively (except on
1658 // buggy EFIs with case-sensitive StriCmp() functions).
1659 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1660 UINTN i = 0;
1661 BOOLEAN Found = FALSE;
1662 CHAR16 *OneElement;
1663
1664 if (SmallString && List) {
1665 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1666 if (StriCmp(OneElement, SmallString) == 0)
1667 Found = TRUE;
1668 } // while
1669 } // if
1670 return Found;
1671 } // BOOLEAN IsIn()
1672
1673 // Implement FreePool the way it should have been done to begin with, so that
1674 // it doesn't throw an ASSERT message if fed a NULL pointer....
1675 VOID MyFreePool(IN VOID *Pointer) {
1676 if (Pointer != NULL)
1677 FreePool(Pointer);
1678 }
1679
1680 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1681
1682 // Eject all removable media.
1683 // Returns TRUE if any media were ejected, FALSE otherwise.
1684 BOOLEAN EjectMedia(VOID) {
1685 EFI_STATUS Status;
1686 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1687 EFI_HANDLE *Handles, Handle;
1688 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1689
1690 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1691 if (EFI_ERROR(Status) || HandleCount == 0)
1692 return (FALSE); // probably not an Apple system
1693
1694 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1695 Handle = Handles[HandleIndex];
1696 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1697 if (EFI_ERROR(Status))
1698 continue;
1699 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1700 if (!EFI_ERROR(Status))
1701 Ejected++;
1702 }
1703 MyFreePool(Handles);
1704 return (Ejected > 0);
1705 } // VOID EjectMedia()
1706
1707
1708 // Return the GUID as a string, suitable for display to the user. Note that the calling
1709 // function is responsible for freeing the allocated memory.
1710 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1711 CHAR16 *TheString;
1712
1713 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1714 if (TheString != 0) {
1715 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1716 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1717 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1718 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1719 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1720 }
1721 return TheString;
1722 } // GuidAsString(EFI_GUID *GuidData)