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