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