]> code.delx.au - refind/blob - refind/lib.c
New FreeBSD GPT BIOS-mode boot loader detection code. Also,
[refind] / refind / lib.c
1 /*
2 * refind/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012-2015 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), a copy of which must be distributed
41 * with this source code or binaries made from it.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
51 #include "gpt.h"
52 #include "config.h"
53
54 #ifdef __MAKEWITH_GNUEFI
55 #define EfiReallocatePool ReallocatePool
56 #else
57 #define LibLocateHandle gBS->LocateHandleBuffer
58 #define DevicePathProtocol gEfiDevicePathProtocolGuid
59 #define BlockIoProtocol gEfiBlockIoProtocolGuid
60 #define LibFileSystemInfo EfiLibFileSystemInfo
61 #define LibOpenRoot EfiLibOpenRoot
62 EFI_DEVICE_PATH EndDevicePath[] = {
63 {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
64 };
65
66 //#define EndDevicePath DevicePath
67 #endif
68
69 // "Magic" signatures for various filesystems
70 #define FAT_MAGIC 0xAA55
71 #define EXT2_SUPER_MAGIC 0xEF53
72 #define HFSPLUS_MAGIC1 0x2B48
73 #define HFSPLUS_MAGIC2 0x5848
74 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
75 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
76 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
77 #define BTRFS_SIGNATURE "_BHRfS_M"
78 #define NTFS_SIGNATURE "NTFS "
79
80 // variables
81
82 EFI_HANDLE SelfImageHandle;
83 EFI_LOADED_IMAGE *SelfLoadedImage;
84 EFI_FILE *SelfRootDir;
85 EFI_FILE *SelfDir;
86 CHAR16 *SelfDirPath;
87
88 REFIT_VOLUME *SelfVolume = NULL;
89 REFIT_VOLUME **Volumes = NULL;
90 UINTN VolumesCount = 0;
91 extern GPT_DATA *gPartitions;
92
93 // Maximum size for disk sectors
94 #define SECTOR_SIZE 4096
95
96 // Number of bytes to read from a partition to determine its filesystem type
97 // and identify its boot loader, and hence probable BIOS-mode OS installation
98 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
99
100
101 // functions
102
103 static EFI_STATUS FinishInitRefitLib(VOID);
104
105 static VOID UninitVolumes(VOID);
106
107 //
108 // self recognition stuff
109 //
110
111 // Converts forward slashes to backslashes, removes duplicate slashes, and
112 // removes slashes from both the start and end of the pathname.
113 // Necessary because some (buggy?) EFI implementations produce "\/" strings
114 // in pathnames, because some user inputs can produce duplicate directory
115 // separators, and because we want consistent start and end slashes for
116 // directory comparisons. A special case: If the PathName refers to root,
117 // return "/", since some firmware implementations flake out if this
118 // isn't present.
119 VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
120 CHAR16 *NewName;
121 UINTN i, Length, FinalChar = 0;
122 BOOLEAN LastWasSlash = FALSE;
123
124 Length = StrLen(PathName);
125 NewName = AllocateZeroPool(sizeof(CHAR16) * (Length + 2));
126 if (NewName != NULL) {
127 for (i = 0; i < StrLen(PathName); i++) {
128 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
129 if ((!LastWasSlash) && (FinalChar != 0))
130 NewName[FinalChar++] = L'\\';
131 LastWasSlash = TRUE;
132 } else {
133 NewName[FinalChar++] = PathName[i];
134 LastWasSlash = FALSE;
135 } // if/else
136 } // for
137 NewName[FinalChar] = 0;
138 if ((FinalChar > 0) && (NewName[FinalChar - 1] == L'\\'))
139 NewName[--FinalChar] = 0;
140 if (FinalChar == 0) {
141 NewName[0] = L'\\';
142 NewName[1] = 0;
143 }
144 // Copy the transformed name back....
145 StrCpy(PathName, NewName);
146 FreePool(NewName);
147 } // if allocation OK
148 } // CleanUpPathNameSlashes()
149
150 // Splits an EFI device path into device and filename components. For instance, if InString is
151 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
152 // this function will truncate that input to
153 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
154 // and return bzImage-3.5.1.efi as its return value.
155 // It does this by searching for the last ")" character in InString, copying everything
156 // after that string (after some cleanup) as the return value, and truncating the original
157 // input value.
158 // If InString contains no ")" character, this function leaves the original input string
159 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
160 static CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
161 INTN i;
162 CHAR16 *FileName = NULL;
163 BOOLEAN Found = FALSE;
164
165 if (InString != NULL) {
166 i = StrLen(InString) - 1;
167 while ((i >= 0) && (!Found)) {
168 if (InString[i] == L')') {
169 Found = TRUE;
170 FileName = StrDuplicate(&InString[i + 1]);
171 CleanUpPathNameSlashes(FileName);
172 InString[i + 1] = '\0';
173 } // if
174 i--;
175 } // while
176 if (FileName == NULL)
177 FileName = StrDuplicate(InString);
178 } // if
179 return FileName;
180 } // static CHAR16* SplitDeviceString()
181
182 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
183 {
184 EFI_STATUS Status;
185 CHAR16 *DevicePathAsString, *Temp;
186
187 SelfImageHandle = ImageHandle;
188 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
189 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
190 return EFI_LOAD_ERROR;
191
192 // find the current directory
193 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
194 CleanUpPathNameSlashes(DevicePathAsString);
195 MyFreePool(SelfDirPath);
196 Temp = FindPath(DevicePathAsString);
197 SelfDirPath = SplitDeviceString(Temp);
198 MyFreePool(DevicePathAsString);
199 MyFreePool(Temp);
200
201 return FinishInitRefitLib();
202 }
203
204 // called before running external programs to close open file handles
205 VOID UninitRefitLib(VOID)
206 {
207 // This piece of code was made to correspond to weirdness in ReinitRefitLib().
208 // See the comment on it there.
209 if(SelfRootDir == SelfVolume->RootDir)
210 SelfRootDir=0;
211
212 UninitVolumes();
213
214 if (SelfDir != NULL) {
215 refit_call1_wrapper(SelfDir->Close, SelfDir);
216 SelfDir = NULL;
217 }
218
219 if (SelfRootDir != NULL) {
220 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
221 SelfRootDir = NULL;
222 }
223 }
224
225 // called after running external programs to re-open file handles
226 EFI_STATUS ReinitRefitLib(VOID)
227 {
228 ReinitVolumes();
229
230 if ((ST->Hdr.Revision >> 16) == 1) {
231 // Below two lines were in rEFIt, but seem to cause system crashes or
232 // reboots when launching OSes after returning from programs on most
233 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
234 // installation volume" (see the next function) when returning from
235 // programs when these two lines are removed, and it often crashes
236 // when returning from a program or when launching a second program
237 // with these lines removed. Therefore, the preceding if() statement
238 // executes these lines only on EFIs with a major version number of 1
239 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
240 // of hardware on which to test is limited, though, so this may be the
241 // wrong test, or there may be a better way to fix this problem.
242 // TODO: Figure out cause of above weirdness and fix it more
243 // reliably!
244 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
245 SelfRootDir = SelfVolume->RootDir;
246 } // if
247
248 return FinishInitRefitLib();
249 }
250
251 static EFI_STATUS FinishInitRefitLib(VOID)
252 {
253 EFI_STATUS Status;
254
255 if (SelfRootDir == NULL) {
256 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
257 if (SelfRootDir == NULL) {
258 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
259 return EFI_LOAD_ERROR;
260 }
261 }
262
263 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
264 if (CheckFatalError(Status, L"while opening our installation directory"))
265 return EFI_LOAD_ERROR;
266
267 return EFI_SUCCESS;
268 }
269
270 //
271 // EFI variable read and write functions
272 //
273
274 // From gummiboot: Retrieve a raw EFI variable.
275 // Returns EFI status
276 EFI_STATUS EfivarGetRaw(EFI_GUID *vendor, CHAR16 *name, CHAR8 **buffer, UINTN *size) {
277 CHAR8 *buf;
278 UINTN l;
279 EFI_STATUS err;
280
281 l = sizeof(CHAR16 *) * EFI_MAXIMUM_VARIABLE_SIZE;
282 buf = AllocatePool(l);
283 if (!buf)
284 return EFI_OUT_OF_RESOURCES;
285
286 err = refit_call5_wrapper(RT->GetVariable, name, vendor, NULL, &l, buf);
287 if (EFI_ERROR(err) == EFI_SUCCESS) {
288 *buffer = buf;
289 if (size)
290 *size = l;
291 } else
292 MyFreePool(buf);
293 return err;
294 } // EFI_STATUS EfivarGetRaw()
295
296 // From gummiboot: Set an EFI variable
297 EFI_STATUS EfivarSetRaw(EFI_GUID *vendor, CHAR16 *name, CHAR8 *buf, UINTN size, BOOLEAN persistent) {
298 UINT32 flags;
299
300 flags = EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
301 if (persistent)
302 flags |= EFI_VARIABLE_NON_VOLATILE;
303
304 return refit_call5_wrapper(RT->SetVariable, name, vendor, flags, size, buf);
305 } // EFI_STATUS EfivarSetRaw()
306
307 //
308 // list functions
309 //
310
311 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
312 {
313 UINTN AllocateCount;
314
315 *ElementCount = InitialElementCount;
316 if (*ElementCount > 0) {
317 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
318 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
319 } else {
320 *ListPtr = NULL;
321 }
322 }
323
324 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
325 {
326 UINTN AllocateCount;
327
328 if ((*ElementCount & 7) == 0) {
329 AllocateCount = *ElementCount + 8;
330 if (*ElementCount == 0)
331 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
332 else
333 *ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
334 }
335 (*ListPtr)[*ElementCount] = NewElement;
336 (*ElementCount)++;
337 } /* VOID AddListElement() */
338
339 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
340 {
341 UINTN i;
342
343 if ((*ElementCount > 0) && (**ListPtr != NULL)) {
344 for (i = 0; i < *ElementCount; i++) {
345 // TODO: call a user-provided routine for each element here
346 MyFreePool((*ListPtr)[i]);
347 }
348 MyFreePool(*ListPtr);
349 }
350 } // VOID FreeList()
351
352 //
353 // firmware device path discovery
354 //
355
356 static UINT8 LegacyLoaderMediaPathData[] = {
357 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
358 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
359 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
360 };
361 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
362
363 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
364 {
365 EFI_STATUS Status;
366 UINTN HandleCount = 0;
367 UINTN HandleIndex, HardcodedIndex;
368 EFI_HANDLE *Handles;
369 EFI_HANDLE Handle;
370 UINTN PathCount = 0;
371 UINTN PathIndex;
372 EFI_LOADED_IMAGE *LoadedImage;
373 EFI_DEVICE_PATH *DevicePath;
374 BOOLEAN Seen;
375
376 MaxPaths--; // leave space for the terminating NULL pointer
377
378 // get all LoadedImage handles
379 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL, &HandleCount, &Handles);
380 if (CheckError(Status, L"while listing LoadedImage handles")) {
381 if (HardcodedPathList) {
382 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
383 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
384 }
385 PathList[PathCount] = NULL;
386 return;
387 }
388 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
389 Handle = Handles[HandleIndex];
390
391 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
392 if (EFI_ERROR(Status))
393 continue; // This can only happen if the firmware scewed up, ignore it.
394
395 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
396 if (EFI_ERROR(Status))
397 continue; // This happens, ignore it.
398
399 // Only grab memory range nodes
400 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
401 continue;
402
403 // Check if we have this device path in the list already
404 // WARNING: This assumes the first node in the device path is unique!
405 Seen = FALSE;
406 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
407 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
408 continue;
409 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
410 Seen = TRUE;
411 break;
412 }
413 }
414 if (Seen)
415 continue;
416
417 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
418 }
419 MyFreePool(Handles);
420
421 if (HardcodedPathList) {
422 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
423 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
424 }
425 PathList[PathCount] = NULL;
426 }
427
428 //
429 // volume functions
430 //
431
432 // Return a pointer to a string containing a filesystem type name. If the
433 // filesystem type is unknown, a blank (but non-null) string is returned.
434 // The returned variable is a constant that should NOT be freed.
435 static CHAR16 *FSTypeName(IN UINT32 TypeCode) {
436 CHAR16 *retval = NULL;
437
438 switch (TypeCode) {
439 case FS_TYPE_WHOLEDISK:
440 retval = L" whole disk";
441 break;
442 case FS_TYPE_FAT:
443 retval = L" FAT";
444 break;
445 case FS_TYPE_HFSPLUS:
446 retval = L" HFS+";
447 break;
448 case FS_TYPE_EXT2:
449 retval = L" ext2";
450 break;
451 case FS_TYPE_EXT3:
452 retval = L" ext3";
453 break;
454 case FS_TYPE_EXT4:
455 retval = L" ext4";
456 break;
457 case FS_TYPE_REISERFS:
458 retval = L" ReiserFS";
459 break;
460 case FS_TYPE_BTRFS:
461 retval = L" Btrfs";
462 break;
463 case FS_TYPE_ISO9660:
464 retval = L" ISO-9660";
465 break;
466 case FS_TYPE_NTFS:
467 retval = L" NTFS";
468 break;
469 default:
470 retval = L"";
471 break;
472 } // switch
473 return retval;
474 } // CHAR16 *FSTypeName()
475
476 // Identify the filesystem type and record the filesystem's UUID/serial number,
477 // if possible. Expects a Buffer containing the first few (normally at least
478 // 4096) bytes of the filesystem. Sets the filesystem type code in Volume->FSType
479 // and the UUID/serial number in Volume->VolUuid. Note that the UUID value is
480 // recognized differently for each filesystem, and is currently supported only
481 // for NTFS, ext2/3/4fs, and ReiserFS (and for NTFS it's really a 64-bit serial
482 // number not a UUID or GUID). If the UUID can't be determined, it's set to 0.
483 // Also, the UUID is just read directly into memory; it is *NOT* valid when
484 // displayed by GuidAsString() or used in other GUID/UUID-manipulating
485 // functions. (As I write, it's being used merely to detect partitions that are
486 // part of a RAID 1 array.)
487 static VOID SetFilesystemData(IN UINT8 *Buffer, IN UINTN BufferSize, IN OUT REFIT_VOLUME *Volume) {
488 UINT32 *Ext2Incompat, *Ext2Compat;
489 UINT16 *Magic16;
490 char *MagicString;
491 EFI_FILE *RootDir;
492
493 if ((Buffer != NULL) && (Volume != NULL)) {
494 SetMem(&(Volume->VolUuid), sizeof(EFI_GUID), 0);
495 Volume->FSType = FS_TYPE_UNKNOWN;
496
497 if (BufferSize >= 512) {
498
499 // Search for NTFS, FAT, and MBR/EBR.
500 // These all have 0xAA55 at the end of the first sector, but FAT and
501 // MBR/EBR are not easily distinguished. Thus, we first check to see
502 // if the "volume" is in fact a disk device; then look for NTFS
503 // "magic"; and then check to see if the volume can be mounted, thus
504 // relying on the EFI's built-in FAT driver to identify FAT.
505 Magic16 = (UINT16*) (Buffer + 510);
506 if (*Magic16 == FAT_MAGIC) {
507 MagicString = (char*) (Buffer + 3);
508 // Confusingly, "LogicalPartition" refers to the presence of a
509 // partition table, not an MBR logical partition.
510 if (Volume->BlockIO->Media->LogicalPartition) {
511 Volume->FSType = FS_TYPE_WHOLEDISK;
512 } else if (CompareMem(MagicString, NTFS_SIGNATURE, 8) == 0) {
513 Volume->FSType = FS_TYPE_NTFS;
514 CopyMem(&(Volume->VolUuid), Buffer + 0x48, sizeof(UINT64));
515 } else {
516 RootDir = LibOpenRoot(Volume->DeviceHandle);
517 if (RootDir != NULL)
518 Volume->FSType = FS_TYPE_FAT;
519 } // if/elseif/else
520 return;
521 } // if
522 } // search for FAT and NTFS magic
523
524 if (BufferSize >= (1024 + 100)) {
525 Magic16 = (UINT16*) (Buffer + 1024 + 56);
526 if (*Magic16 == EXT2_SUPER_MAGIC) { // ext2/3/4
527 Ext2Compat = (UINT32*) (Buffer + 1024 + 92);
528 Ext2Incompat = (UINT32*) (Buffer + 1024 + 96);
529 if ((*Ext2Incompat & 0x0040) || (*Ext2Incompat & 0x0200)) { // check for extents or flex_bg
530 Volume->FSType = FS_TYPE_EXT4;
531 } else if (*Ext2Compat & 0x0004) { // check for journal
532 Volume->FSType = FS_TYPE_EXT3;
533 } else { // none of these features; presume it's ext2...
534 Volume->FSType = FS_TYPE_EXT2;
535 }
536 CopyMem(&(Volume->VolUuid), Buffer + 1024 + 104, sizeof(EFI_GUID));
537 return;
538 }
539 } // search for ext2/3/4 magic
540
541 if (BufferSize >= (65536 + 100)) {
542 MagicString = (char*) (Buffer + 65536 + 52);
543 if ((CompareMem(MagicString, REISERFS_SUPER_MAGIC_STRING, 8) == 0) ||
544 (CompareMem(MagicString, REISER2FS_SUPER_MAGIC_STRING, 9) == 0) ||
545 (CompareMem(MagicString, REISER2FS_JR_SUPER_MAGIC_STRING, 9) == 0)) {
546 Volume->FSType = FS_TYPE_REISERFS;
547 CopyMem(&(Volume->VolUuid), Buffer + 65536 + 84, sizeof(EFI_GUID));
548 return;
549 } // if
550 } // search for ReiserFS magic
551
552 if (BufferSize >= (65536 + 64 + 8)) {
553 MagicString = (char*) (Buffer + 65536 + 64);
554 if (CompareMem(MagicString, BTRFS_SIGNATURE, 8) == 0) {
555 Volume->FSType = FS_TYPE_BTRFS;
556 return;
557 } // if
558 } // search for Btrfs magic
559
560 if (BufferSize >= (1024 + 2)) {
561 Magic16 = (UINT16*) (Buffer + 1024);
562 if ((*Magic16 == HFSPLUS_MAGIC1) || (*Magic16 == HFSPLUS_MAGIC2)) {
563 Volume->FSType = FS_TYPE_HFSPLUS;
564 return;
565 }
566 } // search for HFS+ magic
567
568 } // if (Buffer != NULL)
569
570 } // UINT32 SetFilesystemData()
571
572 static VOID ScanVolumeBootcode(REFIT_VOLUME *Volume, BOOLEAN *Bootable)
573 {
574 EFI_STATUS Status;
575 UINT8 Buffer[SAMPLE_SIZE];
576 UINTN i;
577 MBR_PARTITION_INFO *MbrTable;
578 BOOLEAN MbrTableFound = FALSE;
579
580 Volume->HasBootCode = FALSE;
581 Volume->OSIconName = NULL;
582 Volume->OSName = NULL;
583 *Bootable = FALSE;
584
585 if (Volume->BlockIO == NULL)
586 return;
587 if (Volume->BlockIO->Media->BlockSize > SAMPLE_SIZE)
588 return; // our buffer is too small...
589
590 // look at the boot sector (this is used for both hard disks and El Torito images!)
591 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
592 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
593 Volume->BlockIOOffset, SAMPLE_SIZE, Buffer);
594 if (!EFI_ERROR(Status)) {
595
596 // if (Volume->BlockIO->Media->LogicalPartition)
597 // Print(L"Skipping; whole disk!\n");
598 // else
599 SetFilesystemData(Buffer, SAMPLE_SIZE, Volume);
600 // PauseForKey();
601 if ((*((UINT16 *)(Buffer + 510)) == 0xaa55 && Buffer[0] != 0) && (FindMem(Buffer, 512, "EXFAT", 5) == -1)) {
602 *Bootable = TRUE;
603 Volume->HasBootCode = TRUE;
604 }
605
606 // detect specific boot codes
607 if (CompareMem(Buffer + 2, "LILO", 4) == 0 ||
608 CompareMem(Buffer + 6, "LILO", 4) == 0 ||
609 CompareMem(Buffer + 3, "SYSLINUX", 8) == 0 ||
610 FindMem(Buffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
611 Volume->HasBootCode = TRUE;
612 Volume->OSIconName = L"linux";
613 Volume->OSName = L"Linux";
614
615 } else if (FindMem(Buffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
616 Volume->HasBootCode = TRUE;
617 Volume->OSIconName = L"grub,linux";
618 Volume->OSName = L"Linux";
619
620 // // Below doesn't produce a bootable entry, so commented out for the moment....
621 // // GRUB in BIOS boot partition:
622 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
623 // Volume->HasBootCode = TRUE;
624 // Volume->OSIconName = L"grub,linux";
625 // Volume->OSName = L"Linux";
626 // Volume->VolName = L"BIOS Boot Partition";
627 // *Bootable = TRUE;
628
629 } else if ((*((UINT32 *)(Buffer + 502)) == 0 &&
630 *((UINT32 *)(Buffer + 506)) == 50000 &&
631 *((UINT16 *)(Buffer + 510)) == 0xaa55) ||
632 FindMem(Buffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
633 Volume->HasBootCode = TRUE;
634 Volume->OSIconName = L"freebsd";
635 Volume->OSName = L"FreeBSD";
636
637 // If more differentiation needed, also search for
638 // "Invalid partition table" &/or "Missing boot loader".
639 } else if ((*((UINT16 *)(Buffer + 510)) == 0xaa55) &&
640 (FindMem(Buffer, SECTOR_SIZE, "Boot loader too large", 21) >= 0) &&
641 (FindMem(Buffer, SECTOR_SIZE, "I/O error loading boot loader", 29) >= 0)) {
642 Volume->HasBootCode = TRUE;
643 Volume->OSIconName = L"freebsd";
644 Volume->OSName = L"FreeBSD";
645
646 } else if (FindMem(Buffer, 512, "!Loading", 8) >= 0 ||
647 FindMem(Buffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
648 Volume->HasBootCode = TRUE;
649 Volume->OSIconName = L"openbsd";
650 Volume->OSName = L"OpenBSD";
651
652 } else if (FindMem(Buffer, 512, "Not a bootxx image", 18) >= 0 ||
653 *((UINT32 *)(Buffer + 1028)) == 0x7886b6d1) {
654 Volume->HasBootCode = TRUE;
655 Volume->OSIconName = L"netbsd";
656 Volume->OSName = L"NetBSD";
657
658 // Windows NT/200x/XP
659 } else if (FindMem(Buffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
660 Volume->HasBootCode = TRUE;
661 Volume->OSIconName = L"win";
662 Volume->OSName = L"Windows";
663
664 // Windows Vista/7/8
665 } else if (FindMem(Buffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
666 Volume->HasBootCode = TRUE;
667 Volume->OSIconName = L"win8,win";
668 Volume->OSName = L"Windows";
669
670 } else if (FindMem(Buffer, 512, "CPUBOOT SYS", 11) >= 0 ||
671 FindMem(Buffer, 512, "KERNEL SYS", 11) >= 0) {
672 Volume->HasBootCode = TRUE;
673 Volume->OSIconName = L"freedos";
674 Volume->OSName = L"FreeDOS";
675
676 } else if (FindMem(Buffer, 512, "OS2LDR", 6) >= 0 ||
677 FindMem(Buffer, 512, "OS2BOOT", 7) >= 0) {
678 Volume->HasBootCode = TRUE;
679 Volume->OSIconName = L"ecomstation";
680 Volume->OSName = L"eComStation";
681
682 } else if (FindMem(Buffer, 512, "Be Boot Loader", 14) >= 0) {
683 Volume->HasBootCode = TRUE;
684 Volume->OSIconName = L"beos";
685 Volume->OSName = L"BeOS";
686
687 } else if (FindMem(Buffer, 512, "yT Boot Loader", 14) >= 0) {
688 Volume->HasBootCode = TRUE;
689 Volume->OSIconName = L"zeta,beos";
690 Volume->OSName = L"ZETA";
691
692 } else if (FindMem(Buffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
693 FindMem(Buffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
694 Volume->HasBootCode = TRUE;
695 Volume->OSIconName = L"haiku,beos";
696 Volume->OSName = L"Haiku";
697
698 }
699
700 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
701 // need to fix AddLegacyEntry in refind/legacy.c.
702
703 #if REFIT_DEBUG > 0
704 Print(L" Result of bootcode detection: %s %s (%s)\n",
705 Volume->HasBootCode ? L"bootable" : L"non-bootable",
706 Volume->OSName, Volume->OSIconName);
707 #endif
708
709 // dummy FAT boot sector (created by OS X's newfs_msdos)
710 if (FindMem(Buffer, 512, "Non-system disk", 15) >= 0)
711 Volume->HasBootCode = FALSE;
712
713 // dummy FAT boot sector (created by Linux's mkdosfs)
714 if (FindMem(Buffer, 512, "This is not a bootable disk", 27) >= 0)
715 Volume->HasBootCode = FALSE;
716
717 // dummy FAT boot sector (created by Windows)
718 if (FindMem(Buffer, 512, "Press any key to restart", 24) >= 0)
719 Volume->HasBootCode = FALSE;
720
721 // check for MBR partition table
722 if (*((UINT16 *)(Buffer + 510)) == 0xaa55) {
723 MbrTable = (MBR_PARTITION_INFO *)(Buffer + 446);
724 for (i = 0; i < 4; i++)
725 if (MbrTable[i].StartLBA && MbrTable[i].Size)
726 MbrTableFound = TRUE;
727 for (i = 0; i < 4; i++)
728 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
729 MbrTableFound = FALSE;
730 if (MbrTableFound) {
731 Volume->MbrPartitionTable = AllocatePool(4 * 16);
732 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
733 }
734 }
735
736 } else {
737 #if REFIT_DEBUG > 0
738 CheckError(Status, L"while reading boot sector");
739 #endif
740 }
741 } /* VOID ScanVolumeBootcode() */
742
743 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
744 VOID SetVolumeBadgeIcon(REFIT_VOLUME *Volume)
745 {
746 if (GlobalConfig.HideUIFlags & HIDEUI_FLAG_BADGES)
747 return;
748
749 if (Volume->VolBadgeImage == NULL) {
750 Volume->VolBadgeImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeBadge", GlobalConfig.IconSizes[ICON_SIZE_BADGE]);
751 }
752
753 if (Volume->VolBadgeImage == NULL) {
754 switch (Volume->DiskKind) {
755 case DISK_KIND_INTERNAL:
756 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
757 break;
758 case DISK_KIND_EXTERNAL:
759 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
760 break;
761 case DISK_KIND_OPTICAL:
762 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
763 break;
764 case DISK_KIND_NET:
765 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
766 break;
767 } // switch()
768 }
769 } // VOID SetVolumeBadgeIcon()
770
771 // Return a string representing the input size in IEEE-1541 units.
772 // The calling function is responsible for freeing the allocated memory.
773 static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
774 UINT64 SizeInIeee;
775 UINTN Index = 0, NumPrefixes;
776 CHAR16 *Units, *Prefixes = L" KMGTPEZ";
777 CHAR16 *TheValue;
778
779 TheValue = AllocateZeroPool(sizeof(CHAR16) * 256);
780 if (TheValue != NULL) {
781 NumPrefixes = StrLen(Prefixes);
782 SizeInIeee = SizeInBytes;
783 while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
784 Index++;
785 SizeInIeee /= 1024;
786 } // while
787 if (Prefixes[Index] == ' ') {
788 Units = StrDuplicate(L"-byte");
789 } else {
790 Units = StrDuplicate(L" iB");
791 Units[1] = Prefixes[Index];
792 } // if/else
793 SPrint(TheValue, 255, L"%ld%s", SizeInIeee, Units);
794 } // if
795 return TheValue;
796 } // CHAR16 *SizeInIEEEUnits()
797
798 // Return a name for the volume. Ideally this should be the label for the
799 // filesystem or volume, but this function falls back to describing the
800 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
801 // this information can be extracted.
802 // The calling function is responsible for freeing the memory allocated
803 // for the name string.
804 static CHAR16 *GetVolumeName(REFIT_VOLUME *Volume) {
805 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr = NULL;
806 CHAR16 *FoundName = NULL;
807 CHAR16 *SISize, *TypeName;
808
809 if (Volume->RootDir != NULL) {
810 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
811 }
812
813 if ((FileSystemInfoPtr != NULL) && (FileSystemInfoPtr->VolumeLabel != NULL) &&
814 (StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
815 FoundName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
816 }
817
818 // If no filesystem name, try to use the partition name....
819 if ((FoundName == NULL) && (Volume->PartName != NULL) && (StrLen(Volume->PartName) > 0) &&
820 !IsIn(Volume->PartName, IGNORE_PARTITION_NAMES)) {
821 FoundName = StrDuplicate(Volume->PartName);
822 } // if use partition name
823
824 // No filesystem or acceptable partition name, so use fs type and size
825 if ((FoundName == NULL) && (FileSystemInfoPtr != NULL)) {
826 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
827 if (FoundName != NULL) {
828 SISize = SizeInIEEEUnits(FileSystemInfoPtr->VolumeSize);
829 SPrint(FoundName, 255, L"%s%s volume", SISize, FSTypeName(Volume->FSType));
830 MyFreePool(SISize);
831 } // if allocated memory OK
832 } // if (FoundName == NULL)
833
834 MyFreePool(FileSystemInfoPtr);
835
836 if (FoundName == NULL) {
837 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
838 if (FoundName != NULL) {
839 TypeName = FSTypeName(Volume->FSType); // NOTE: Don't free TypeName; function returns constant
840 if (StrLen(TypeName) > 0)
841 SPrint(FoundName, 255, L"%s volume", TypeName);
842 else
843 SPrint(FoundName, 255, L"unknown volume");
844 } // if allocated memory OK
845 } // if
846
847 // TODO: Above could be improved/extended, in case filesystem name is not found,
848 // such as:
849 // - use or add disk/partition number (e.g., "(hd0,2)")
850
851 // Desperate fallback name....
852 if (FoundName == NULL) {
853 FoundName = StrDuplicate(L"unknown volume");
854 }
855 return FoundName;
856 } // static CHAR16 *GetVolumeName()
857
858 // Determine the unique GUID and name of the volume and store them.
859 static VOID SetPartGuidAndName(REFIT_VOLUME *Volume, EFI_DEVICE_PATH_PROTOCOL *DevicePath) {
860 HARDDRIVE_DEVICE_PATH *HdDevicePath;
861
862 if (Volume == NULL)
863 return;
864
865 if ((DevicePath->Type == MEDIA_DEVICE_PATH) && (DevicePath->SubType == MEDIA_HARDDRIVE_DP)) {
866 HdDevicePath = (HARDDRIVE_DEVICE_PATH*) DevicePath;
867 if (HdDevicePath->SignatureType == SIGNATURE_TYPE_GUID) {
868 Volume->PartGuid = *((EFI_GUID*) HdDevicePath->Signature);
869 Volume->PartName = PartNameFromGuid(&(Volume->PartGuid));
870 } // if
871 } // if
872 } // VOID SetPartGuid()
873
874 // Return TRUE if NTFS boot files are found or if Volume is unreadable,
875 // FALSE otherwise. The idea is to weed out non-boot NTFS volumes from
876 // BIOS/legacy boot list on Macs. We can't assume NTFS will be readable,
877 // so return TRUE if it's unreadable; but if it IS readable, return
878 // TRUE only if Windows boot files are found.
879 static BOOLEAN HasWindowsBiosBootFiles(REFIT_VOLUME *Volume) {
880 BOOLEAN FilesFound = TRUE;
881
882 if (Volume->RootDir != NULL) {
883 FilesFound = FileExists(Volume->RootDir, L"NTLDR") || // Windows NT/200x/XP boot file
884 FileExists(Volume->RootDir, L"bootmgr"); // Windows Vista/7/8 boot file
885 } // if
886 return FilesFound;
887 } // static VOID HasWindowsBiosBootFiles()
888
889 VOID ScanVolume(REFIT_VOLUME *Volume)
890 {
891 EFI_STATUS Status;
892 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
893 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
894 EFI_HANDLE WholeDiskHandle;
895 UINTN PartialLength;
896 BOOLEAN Bootable;
897
898 // get device path
899 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
900 #if REFIT_DEBUG > 0
901 if (Volume->DevicePath != NULL) {
902 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
903 #if REFIT_DEBUG >= 2
904 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
905 #endif
906 }
907 #endif
908
909 Volume->DiskKind = DISK_KIND_INTERNAL; // default
910
911 // get block i/o
912 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
913 if (EFI_ERROR(Status)) {
914 Volume->BlockIO = NULL;
915 Print(L"Warning: Can't get BlockIO protocol.\n");
916 } else {
917 if (Volume->BlockIO->Media->BlockSize == 2048)
918 Volume->DiskKind = DISK_KIND_OPTICAL;
919 }
920
921 // scan for bootcode and MBR table
922 Bootable = FALSE;
923 ScanVolumeBootcode(Volume, &Bootable);
924
925 // detect device type
926 DevicePath = Volume->DevicePath;
927 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
928 NextDevicePath = NextDevicePathNode(DevicePath);
929
930 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH) {
931 SetPartGuidAndName(Volume, DevicePath);
932 }
933 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
934 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
935 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
936 DevicePathSubType(DevicePath) == MSG_1394_DP ||
937 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
938 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
939 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
940 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
941 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
942 Bootable = TRUE;
943 }
944
945 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
946 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
947 // TODO: also check for Boot Camp GUID
948 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
949 }
950
951 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
952 // make a device path for the whole device
953 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
954 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
955 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
956 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
957
958 // get the handle for that path
959 RemainingDevicePath = DiskDevicePath;
960 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
961 FreePool(DiskDevicePath);
962
963 if (!EFI_ERROR(Status)) {
964 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
965
966 // get the device path for later
967 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
968 if (!EFI_ERROR(Status)) {
969 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
970 }
971
972 // look at the BlockIO protocol
973 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol,
974 (VOID **) &Volume->WholeDiskBlockIO);
975 if (!EFI_ERROR(Status)) {
976
977 // check the media block size
978 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
979 Volume->DiskKind = DISK_KIND_OPTICAL;
980
981 } else {
982 Volume->WholeDiskBlockIO = NULL;
983 //CheckError(Status, L"from HandleProtocol");
984 }
985 } //else
986 // CheckError(Status, L"from LocateDevicePath");
987 }
988
989 DevicePath = NextDevicePath;
990 } // while
991
992 if (!Bootable) {
993 #if REFIT_DEBUG > 0
994 if (Volume->HasBootCode)
995 Print(L" Volume considered non-bootable, but boot code is present\n");
996 #endif
997 Volume->HasBootCode = FALSE;
998 }
999
1000 // open the root directory of the volume
1001 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1002
1003 // Set volume icon based on .VolumeBadge icon or disk kind
1004 SetVolumeBadgeIcon(Volume);
1005
1006 Volume->VolName = GetVolumeName(Volume);
1007
1008 if (Volume->RootDir == NULL) {
1009 Volume->IsReadable = FALSE;
1010 return;
1011 } else {
1012 Volume->IsReadable = TRUE;
1013 if ((GlobalConfig.LegacyType == LEGACY_TYPE_MAC) && (Volume->FSType == FS_TYPE_NTFS) && Volume->HasBootCode) {
1014 // VBR boot code found on NTFS, but volume is not actually bootable
1015 // unless there are actual boot file, so check for them....
1016 Volume->HasBootCode = HasWindowsBiosBootFiles(Volume);
1017 }
1018 } // if/else
1019
1020 // get custom volume icons if present
1021 if (!Volume->VolIconImage) {
1022 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", GlobalConfig.IconSizes[ICON_SIZE_BIG]);
1023 }
1024 } // ScanVolume()
1025
1026 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
1027 {
1028 EFI_STATUS Status;
1029 REFIT_VOLUME *Volume;
1030 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
1031 UINTN i;
1032 UINTN LogicalPartitionIndex = 4;
1033 UINT8 SectorBuffer[512];
1034 BOOLEAN Bootable;
1035 MBR_PARTITION_INFO *EMbrTable;
1036
1037 ExtBase = MbrEntry->StartLBA;
1038
1039 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
1040 // read current EMBR
1041 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
1042 WholeDiskVolume->BlockIO,
1043 WholeDiskVolume->BlockIO->Media->MediaId,
1044 ExtCurrent, 512, SectorBuffer);
1045 if (EFI_ERROR(Status))
1046 break;
1047 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
1048 break;
1049 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
1050
1051 // scan logical partitions in this EMBR
1052 NextExtCurrent = 0;
1053 for (i = 0; i < 4; i++) {
1054 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
1055 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
1056 break;
1057 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
1058 // set next ExtCurrent
1059 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
1060 break;
1061 } else {
1062
1063 // found a logical partition
1064 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1065 Volume->DiskKind = WholeDiskVolume->DiskKind;
1066 Volume->IsMbrPartition = TRUE;
1067 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
1068 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
1069 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
1070 Volume->BlockIO = WholeDiskVolume->BlockIO;
1071 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
1072 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
1073
1074 Bootable = FALSE;
1075 ScanVolumeBootcode(Volume, &Bootable);
1076 if (!Bootable)
1077 Volume->HasBootCode = FALSE;
1078
1079 SetVolumeBadgeIcon(Volume);
1080
1081 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1082
1083 }
1084 }
1085 }
1086 } /* VOID ScanExtendedPartition() */
1087
1088 VOID ScanVolumes(VOID)
1089 {
1090 EFI_STATUS Status;
1091 EFI_HANDLE *Handles;
1092 REFIT_VOLUME *Volume, *WholeDiskVolume;
1093 MBR_PARTITION_INFO *MbrTable;
1094 UINTN HandleCount = 0;
1095 UINTN HandleIndex;
1096 UINTN VolumeIndex, VolumeIndex2;
1097 UINTN PartitionIndex;
1098 UINTN SectorSum, i, VolNumber = 0;
1099 UINT8 *SectorBuffer1, *SectorBuffer2;
1100 EFI_GUID *UuidList;
1101 EFI_GUID NullUuid = NULL_GUID_VALUE;
1102
1103 MyFreePool(Volumes);
1104 Volumes = NULL;
1105 VolumesCount = 0;
1106 ForgetPartitionTables();
1107
1108 // get all filesystem handles
1109 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
1110 UuidList = AllocateZeroPool(sizeof(EFI_GUID) * HandleCount);
1111 if (Status == EFI_NOT_FOUND) {
1112 return; // no filesystems. strange, but true...
1113 }
1114 if (CheckError(Status, L"while listing all file systems"))
1115 return;
1116
1117 // first pass: collect information about all handles
1118 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1119 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1120 Volume->DeviceHandle = Handles[HandleIndex];
1121 AddPartitionTable(Volume);
1122 ScanVolume(Volume);
1123 if (UuidList) {
1124 UuidList[HandleIndex] = Volume->VolUuid;
1125 for (i = 0; i < HandleIndex; i++) {
1126 if ((CompareMem(&(Volume->VolUuid), &(UuidList[i]), sizeof(EFI_GUID)) == 0) &&
1127 (CompareMem(&(Volume->VolUuid), &NullUuid, sizeof(EFI_GUID)) != 0)) { // Duplicate filesystem UUID
1128 Volume->IsReadable = FALSE;
1129 } // if
1130 } // for
1131 } // if
1132 if (Volume->IsReadable)
1133 Volume->VolNumber = VolNumber++;
1134 else
1135 Volume->VolNumber = VOL_UNREADABLE;
1136
1137 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1138
1139 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
1140 SelfVolume = Volume;
1141 }
1142 MyFreePool(Handles);
1143
1144 if (SelfVolume == NULL)
1145 Print(L"WARNING: SelfVolume not found");
1146
1147 // second pass: relate partitions and whole disk devices
1148 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1149 Volume = Volumes[VolumeIndex];
1150 // check MBR partition table for extended partitions
1151 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1152 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
1153 Volume->MbrPartitionTable != NULL) {
1154 MbrTable = Volume->MbrPartitionTable;
1155 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1156 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
1157 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
1158 }
1159 }
1160 }
1161
1162 // search for corresponding whole disk volume entry
1163 WholeDiskVolume = NULL;
1164 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1165 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1166 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1167 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1168 Volumes[VolumeIndex2]->BlockIOOffset == 0) {
1169 WholeDiskVolume = Volumes[VolumeIndex2];
1170 }
1171 }
1172 }
1173
1174 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1175 // check if this volume is one of the partitions in the table
1176 MbrTable = WholeDiskVolume->MbrPartitionTable;
1177 SectorBuffer1 = AllocatePool(512);
1178 SectorBuffer2 = AllocatePool(512);
1179 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1180 // check size
1181 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1182 continue;
1183
1184 // compare boot sector read through offset vs. directly
1185 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1186 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1187 Volume->BlockIOOffset, 512, SectorBuffer1);
1188 if (EFI_ERROR(Status))
1189 break;
1190 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1191 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1192 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1193 if (EFI_ERROR(Status))
1194 break;
1195 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1196 continue;
1197 SectorSum = 0;
1198 for (i = 0; i < 512; i++)
1199 SectorSum += SectorBuffer1[i];
1200 if (SectorSum < 1000)
1201 continue;
1202
1203 // TODO: mark entry as non-bootable if it is an extended partition
1204
1205 // now we're reasonably sure the association is correct...
1206 Volume->IsMbrPartition = TRUE;
1207 Volume->MbrPartitionIndex = PartitionIndex;
1208 if (Volume->VolName == NULL) {
1209 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1210 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1211 }
1212 break;
1213 }
1214
1215 MyFreePool(SectorBuffer1);
1216 MyFreePool(SectorBuffer2);
1217 }
1218 } // for
1219 } /* VOID ScanVolumes() */
1220
1221 static VOID UninitVolumes(VOID)
1222 {
1223 REFIT_VOLUME *Volume;
1224 UINTN VolumeIndex;
1225
1226 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1227 Volume = Volumes[VolumeIndex];
1228
1229 if (Volume->RootDir != NULL) {
1230 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
1231 Volume->RootDir = NULL;
1232 }
1233
1234 Volume->DeviceHandle = NULL;
1235 Volume->BlockIO = NULL;
1236 Volume->WholeDiskBlockIO = NULL;
1237 }
1238 }
1239
1240 VOID ReinitVolumes(VOID)
1241 {
1242 EFI_STATUS Status;
1243 REFIT_VOLUME *Volume;
1244 UINTN VolumeIndex;
1245 EFI_DEVICE_PATH *RemainingDevicePath;
1246 EFI_HANDLE DeviceHandle, WholeDiskHandle;
1247
1248 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1249 Volume = Volumes[VolumeIndex];
1250
1251 if (Volume->DevicePath != NULL) {
1252 // get the handle for that path
1253 RemainingDevicePath = Volume->DevicePath;
1254 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
1255
1256 if (!EFI_ERROR(Status)) {
1257 Volume->DeviceHandle = DeviceHandle;
1258
1259 // get the root directory
1260 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1261
1262 } else
1263 CheckError(Status, L"from LocateDevicePath");
1264 }
1265
1266 if (Volume->WholeDiskDevicePath != NULL) {
1267 // get the handle for that path
1268 RemainingDevicePath = Volume->WholeDiskDevicePath;
1269 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
1270
1271 if (!EFI_ERROR(Status)) {
1272 // get the BlockIO protocol
1273 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol,
1274 (VOID **) &Volume->WholeDiskBlockIO);
1275 if (EFI_ERROR(Status)) {
1276 Volume->WholeDiskBlockIO = NULL;
1277 CheckError(Status, L"from HandleProtocol");
1278 }
1279 } else
1280 CheckError(Status, L"from LocateDevicePath");
1281 }
1282 }
1283 }
1284
1285 //
1286 // file and dir functions
1287 //
1288
1289 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1290 {
1291 EFI_STATUS Status;
1292 EFI_FILE_HANDLE TestFile;
1293
1294 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1295 if (Status == EFI_SUCCESS) {
1296 refit_call1_wrapper(TestFile->Close, TestFile);
1297 return TRUE;
1298 }
1299 return FALSE;
1300 }
1301
1302 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1303 {
1304 EFI_STATUS Status;
1305 VOID *Buffer;
1306 UINTN LastBufferSize, BufferSize;
1307 INTN IterCount;
1308
1309 for (;;) {
1310
1311 // free pointer from last call
1312 if (*DirEntry != NULL) {
1313 FreePool(*DirEntry);
1314 *DirEntry = NULL;
1315 }
1316
1317 // read next directory entry
1318 LastBufferSize = BufferSize = 256;
1319 Buffer = AllocatePool(BufferSize);
1320 for (IterCount = 0; ; IterCount++) {
1321 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1322 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1323 break;
1324 if (BufferSize <= LastBufferSize) {
1325 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1326 BufferSize = LastBufferSize * 2;
1327 #if REFIT_DEBUG > 0
1328 } else {
1329 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1330 #endif
1331 }
1332 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1333 LastBufferSize = BufferSize;
1334 }
1335 if (EFI_ERROR(Status)) {
1336 MyFreePool(Buffer);
1337 Buffer = NULL;
1338 break;
1339 }
1340
1341 // check for end of listing
1342 if (BufferSize == 0) { // end of directory listing
1343 MyFreePool(Buffer);
1344 Buffer = NULL;
1345 break;
1346 }
1347
1348 // entry is ready to be returned
1349 *DirEntry = (EFI_FILE_INFO *)Buffer;
1350
1351 // filter results
1352 if (FilterMode == 1) { // only return directories
1353 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1354 break;
1355 } else if (FilterMode == 2) { // only return files
1356 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1357 break;
1358 } else // no filter or unknown filter -> return everything
1359 break;
1360
1361 }
1362 return Status;
1363 }
1364
1365 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1366 {
1367 if (RelativePath == NULL) {
1368 DirIter->LastStatus = EFI_SUCCESS;
1369 DirIter->DirHandle = BaseDir;
1370 DirIter->CloseDirHandle = FALSE;
1371 } else {
1372 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1373 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1374 }
1375 DirIter->LastFileInfo = NULL;
1376 }
1377
1378 #ifndef __MAKEWITH_GNUEFI
1379 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1380
1381 static EFI_STATUS
1382 InitializeUnicodeCollationProtocol (VOID)
1383 {
1384 EFI_STATUS Status;
1385
1386 if (mUnicodeCollation != NULL) {
1387 return EFI_SUCCESS;
1388 }
1389
1390 //
1391 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1392 // instances first and then select one which support English language.
1393 // Current implementation just pick the first instance.
1394 //
1395 Status = gBS->LocateProtocol (
1396 &gEfiUnicodeCollation2ProtocolGuid,
1397 NULL,
1398 (VOID **) &mUnicodeCollation
1399 );
1400 if (EFI_ERROR(Status)) {
1401 Status = gBS->LocateProtocol (
1402 &gEfiUnicodeCollationProtocolGuid,
1403 NULL,
1404 (VOID **) &mUnicodeCollation
1405 );
1406
1407 }
1408 return Status;
1409 }
1410
1411 static BOOLEAN
1412 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1413 {
1414 if (!mUnicodeCollation) {
1415 InitializeUnicodeCollationProtocol();
1416 }
1417 if (mUnicodeCollation)
1418 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1419 return FALSE; // Shouldn't happen
1420 }
1421
1422 static VOID StrLwr (IN OUT CHAR16 *Str) {
1423 if (!mUnicodeCollation) {
1424 InitializeUnicodeCollationProtocol();
1425 }
1426 if (mUnicodeCollation)
1427 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1428 }
1429
1430 #endif
1431
1432 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1433 OUT EFI_FILE_INFO **DirEntry)
1434 {
1435 BOOLEAN KeepGoing = TRUE;
1436 UINTN i;
1437 CHAR16 *OnePattern;
1438
1439 if (DirIter->LastFileInfo != NULL) {
1440 FreePool(DirIter->LastFileInfo);
1441 DirIter->LastFileInfo = NULL;
1442 }
1443
1444 if (EFI_ERROR(DirIter->LastStatus))
1445 return FALSE; // stop iteration
1446
1447 do {
1448 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1449 if (EFI_ERROR(DirIter->LastStatus))
1450 return FALSE;
1451 if (DirIter->LastFileInfo == NULL) // end of listing
1452 return FALSE;
1453 if (FilePattern != NULL) {
1454 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1455 KeepGoing = FALSE;
1456 i = 0;
1457 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1458 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1459 KeepGoing = FALSE;
1460 } // while
1461 // else continue loop
1462 } else
1463 break;
1464 } while (KeepGoing && FilePattern);
1465
1466 *DirEntry = DirIter->LastFileInfo;
1467 return TRUE;
1468 }
1469
1470 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1471 {
1472 if (DirIter->LastFileInfo != NULL) {
1473 FreePool(DirIter->LastFileInfo);
1474 DirIter->LastFileInfo = NULL;
1475 }
1476 if (DirIter->CloseDirHandle)
1477 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1478 return DirIter->LastStatus;
1479 }
1480
1481 //
1482 // file name manipulation
1483 //
1484
1485 // Returns the filename portion (minus path name) of the
1486 // specified file
1487 CHAR16 * Basename(IN CHAR16 *Path)
1488 {
1489 CHAR16 *FileName;
1490 UINTN i;
1491
1492 FileName = Path;
1493
1494 if (Path != NULL) {
1495 for (i = StrLen(Path); i > 0; i--) {
1496 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1497 FileName = Path + i;
1498 break;
1499 }
1500 }
1501 }
1502
1503 return FileName;
1504 }
1505
1506 // Remove the .efi extension from FileName -- for instance, if FileName is
1507 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1508 // returns a copy of the original input.
1509 CHAR16 * StripEfiExtension(CHAR16 *FileName) {
1510 UINTN Length;
1511 CHAR16 *Copy = NULL;
1512
1513 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1514 Length = StrLen(Copy);
1515 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1516 if ((Length >= 4) && ((StriCmp(&Copy[Length - 4], L".efi") == 0) || (StriCmp(&Copy[Length - 4], L".EFI") == 0))) {
1517 Copy[Length - 4] = 0;
1518 } // if
1519 } // if
1520 return Copy;
1521 } // CHAR16 * StripExtension()
1522
1523 //
1524 // memory string search
1525 //
1526
1527 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1528 {
1529 UINT8 *BufferPtr;
1530 UINTN Offset;
1531
1532 BufferPtr = Buffer;
1533 BufferLength -= SearchStringLength;
1534 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1535 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1536 return (INTN)Offset;
1537 }
1538
1539 return -1;
1540 }
1541
1542 // Performs a case-insensitive search of BigStr for SmallStr.
1543 // Returns TRUE if found, FALSE if not.
1544 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1545 CHAR16 *SmallCopy, *BigCopy;
1546 BOOLEAN Found = FALSE;
1547 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1548
1549 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1550 SmallCopy = StrDuplicate(SmallStr);
1551 BigCopy = StrDuplicate(BigStr);
1552 StrLwr(SmallCopy);
1553 StrLwr(BigCopy);
1554 SmallLen = StrLen(SmallCopy);
1555 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1556 while ((!Found) && (StartPoint < NumCompares)) {
1557 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1558 } // while
1559 MyFreePool(SmallCopy);
1560 MyFreePool(BigCopy);
1561 } // if
1562
1563 return (Found);
1564 } // BOOLEAN StriSubCmp()
1565
1566 // Merges two strings, creating a new one and returning a pointer to it.
1567 // If AddChar != 0, the specified character is placed between the two original
1568 // strings (unless the first string is NULL or empty). The original input
1569 // string *First is de-allocated and replaced by the new merged string.
1570 // This is similar to StrCat, but safer and more flexible because
1571 // MergeStrings allocates memory that's the correct size for the
1572 // new merged string, so it can take a NULL *First and it cleans
1573 // up the old memory. It should *NOT* be used with a constant
1574 // *First, though....
1575 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1576 UINTN Length1 = 0, Length2 = 0;
1577 CHAR16* NewString;
1578
1579 if (*First != NULL)
1580 Length1 = StrLen(*First);
1581 if (Second != NULL)
1582 Length2 = StrLen(Second);
1583 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1584 if (NewString != NULL) {
1585 if ((*First != NULL) && (StrLen(*First) == 0)) {
1586 MyFreePool(*First);
1587 *First = NULL;
1588 }
1589 NewString[0] = L'\0';
1590 if (*First != NULL) {
1591 StrCat(NewString, *First);
1592 if (AddChar) {
1593 NewString[Length1] = AddChar;
1594 NewString[Length1 + 1] = '\0';
1595 } // if (AddChar)
1596 } // if (*First != NULL)
1597 if (Second != NULL)
1598 StrCat(NewString, Second);
1599 MyFreePool(*First);
1600 *First = NewString;
1601 } else {
1602 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1603 } // if/else
1604 } // static CHAR16* MergeStrings()
1605
1606 // Takes an input pathname (*Path) and returns the part of the filename from
1607 // the final dot onwards, converted to lowercase. If the filename includes
1608 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1609 // The calling function is responsible for freeing the memory associated with
1610 // the return value.
1611 CHAR16 *FindExtension(IN CHAR16 *Path) {
1612 CHAR16 *Extension;
1613 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1614 INTN i;
1615
1616 Extension = AllocateZeroPool(sizeof(CHAR16));
1617 if (Path) {
1618 i = StrLen(Path);
1619 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1620 if (Path[i] == L'.')
1621 Found = TRUE;
1622 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1623 FoundSlash = TRUE;
1624 if (!Found)
1625 i--;
1626 } // while
1627 if (Found) {
1628 MergeStrings(&Extension, &Path[i], 0);
1629 StrLwr(Extension);
1630 } // if (Found)
1631 } // if
1632 return (Extension);
1633 } // CHAR16 *FindExtension
1634
1635 // Takes an input pathname (*Path) and locates the final directory component
1636 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1637 // function returns the string 'foo'.
1638 // Assumes the pathname is separated with backslashes.
1639 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1640 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1641 CHAR16 *Found = NULL;
1642
1643 if (Path == NULL)
1644 return NULL;
1645
1646 PathLength = StrLen(Path);
1647 // Find start & end of target element
1648 for (i = 0; i < PathLength; i++) {
1649 if (Path[i] == '\\') {
1650 StartOfElement = EndOfElement;
1651 EndOfElement = i;
1652 } // if
1653 } // for
1654 // Extract the target element
1655 if (EndOfElement > 0) {
1656 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1657 StartOfElement++;
1658 } // while
1659 EndOfElement--;
1660 if (EndOfElement >= StartOfElement) {
1661 CopyLength = EndOfElement - StartOfElement + 1;
1662 Found = StrDuplicate(&Path[StartOfElement]);
1663 if (Found != NULL)
1664 Found[CopyLength] = 0;
1665 } // if (EndOfElement >= StartOfElement)
1666 } // if (EndOfElement > 0)
1667 return (Found);
1668 } // CHAR16 *FindLastDirName
1669
1670 // Returns the directory portion of a pathname. For instance,
1671 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1672 // string 'EFI\foo'. The calling function is responsible for
1673 // freeing the returned string's memory.
1674 CHAR16 *FindPath(IN CHAR16* FullPath) {
1675 UINTN i, LastBackslash = 0;
1676 CHAR16 *PathOnly = NULL;
1677
1678 if (FullPath != NULL) {
1679 for (i = 0; i < StrLen(FullPath); i++) {
1680 if (FullPath[i] == '\\')
1681 LastBackslash = i;
1682 } // for
1683 PathOnly = StrDuplicate(FullPath);
1684 if (PathOnly != NULL)
1685 PathOnly[LastBackslash] = 0;
1686 } // if
1687 return (PathOnly);
1688 }
1689
1690 /*++
1691 *
1692 * Routine Description:
1693 *
1694 * Find a substring.
1695 *
1696 * Arguments:
1697 *
1698 * String - Null-terminated string to search.
1699 * StrCharSet - Null-terminated string to search for.
1700 *
1701 * Returns:
1702 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1703 * --*/
1704 CHAR16* MyStrStr (CHAR16 *String, CHAR16 *StrCharSet)
1705 {
1706 CHAR16 *Src;
1707 CHAR16 *Sub;
1708
1709 if ((String == NULL) || (StrCharSet == NULL))
1710 return NULL;
1711
1712 Src = String;
1713 Sub = StrCharSet;
1714
1715 while ((*String != L'\0') && (*StrCharSet != L'\0')) {
1716 if (*String++ != *StrCharSet) {
1717 String = ++Src;
1718 StrCharSet = Sub;
1719 } else {
1720 StrCharSet++;
1721 }
1722 }
1723 if (*StrCharSet == L'\0') {
1724 return Src;
1725 } else {
1726 return NULL;
1727 }
1728 } // CHAR16 *MyStrStr()
1729
1730 // Restrict TheString to at most Limit characters.
1731 // Does this in two ways:
1732 // - Locates stretches of two or more spaces and compresses
1733 // them down to one space.
1734 // - Truncates TheString
1735 // Returns TRUE if changes were made, FALSE otherwise
1736 BOOLEAN LimitStringLength(CHAR16 *TheString, UINTN Limit) {
1737 CHAR16 *SubString, *TempString;
1738 UINTN i;
1739 BOOLEAN HasChanged = FALSE;
1740
1741 // SubString will be NULL or point WITHIN TheString
1742 SubString = MyStrStr(TheString, L" ");
1743 while (SubString != NULL) {
1744 i = 0;
1745 while (SubString[i] == L' ')
1746 i++;
1747 if (i >= StrLen(SubString)) {
1748 SubString[0] = '\0';
1749 HasChanged = TRUE;
1750 } else {
1751 TempString = StrDuplicate(&SubString[i]);
1752 if (TempString != NULL) {
1753 StrCpy(&SubString[1], TempString);
1754 MyFreePool(TempString);
1755 HasChanged = TRUE;
1756 } else {
1757 // memory allocation problem; abort to avoid potentially infinite loop!
1758 break;
1759 } // if/else
1760 } // if/else
1761 SubString = MyStrStr(TheString, L" ");
1762 } // while
1763
1764 // If the string is still too long, truncate it....
1765 if (StrLen(TheString) > Limit) {
1766 TheString[Limit] = '\0';
1767 HasChanged = TRUE;
1768 } // if
1769
1770 return HasChanged;
1771 } // BOOLEAN LimitStringLength()
1772
1773 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1774 // DeviceVolume, and returns that and the filename (*loader).
1775 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1776 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1777 UINTN i = 0;
1778 BOOLEAN Found = FALSE;
1779
1780 MyFreePool(*loader);
1781 MyFreePool(*DeviceVolume);
1782 *DeviceVolume = NULL;
1783 DeviceString = DevicePathToStr(loadpath);
1784 *loader = SplitDeviceString(DeviceString);
1785
1786 while ((i < VolumesCount) && (!Found)) {
1787 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1788 Temp = SplitDeviceString(VolumeDeviceString);
1789 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1790 Found = TRUE;
1791 *DeviceVolume = Volumes[i];
1792 }
1793 MyFreePool(Temp);
1794 MyFreePool(VolumeDeviceString);
1795 i++;
1796 } // while
1797
1798 MyFreePool(DeviceString);
1799 } // VOID FindVolumeAndFilename()
1800
1801 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1802 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1803 // the filename component in the original *Path variable and the split-off
1804 // volume component in the *VolName variable.
1805 // Returns TRUE if both components are found, FALSE otherwise.
1806 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1807 UINTN i = 0, Length;
1808 CHAR16 *Filename;
1809
1810 if (*Path == NULL)
1811 return FALSE;
1812
1813 if (*VolName != NULL) {
1814 MyFreePool(*VolName);
1815 *VolName = NULL;
1816 }
1817
1818 Length = StrLen(*Path);
1819 while ((i < Length) && ((*Path)[i] != L':')) {
1820 i++;
1821 } // while
1822
1823 if (i < Length) {
1824 Filename = StrDuplicate((*Path) + i + 1);
1825 (*Path)[i] = 0;
1826 *VolName = *Path;
1827 *Path = Filename;
1828 return TRUE;
1829 } else {
1830 return FALSE;
1831 }
1832 } // BOOLEAN SplitVolumeAndFilename()
1833
1834 // Returns all the digits in the input string, including intervening
1835 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1836 // this function returns "3.3.4-7". If InString contains no digits,
1837 // the return value is NULL.
1838 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1839 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1840 CHAR16 *Found = NULL;
1841
1842 if (InString == NULL)
1843 return NULL;
1844
1845 InLength = StartOfElement = StrLen(InString);
1846 // Find start & end of target element
1847 for (i = 0; i < InLength; i++) {
1848 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1849 if (StartOfElement > i)
1850 StartOfElement = i;
1851 if (EndOfElement < i)
1852 EndOfElement = i;
1853 } // if
1854 } // for
1855 // Extract the target element
1856 if (EndOfElement > 0) {
1857 if (EndOfElement >= StartOfElement) {
1858 CopyLength = EndOfElement - StartOfElement + 1;
1859 Found = StrDuplicate(&InString[StartOfElement]);
1860 if (Found != NULL)
1861 Found[CopyLength] = 0;
1862 } // if (EndOfElement >= StartOfElement)
1863 } // if (EndOfElement > 0)
1864 return (Found);
1865 } // CHAR16 *FindNumbers()
1866
1867 // Find the #Index element (numbered from 0) in a comma-delimited string
1868 // of elements.
1869 // Returns the found element, or NULL if Index is out of range or InString
1870 // is NULL. Note that the calling function is responsible for freeing the
1871 // memory associated with the returned string pointer.
1872 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1873 UINTN StartPos = 0, CurPos = 0;
1874 BOOLEAN Found = FALSE;
1875 CHAR16 *FoundString = NULL;
1876
1877 if (InString != NULL) {
1878 // After while() loop, StartPos marks start of item #Index
1879 while ((Index > 0) && (CurPos < StrLen(InString))) {
1880 if (InString[CurPos] == L',') {
1881 Index--;
1882 StartPos = CurPos + 1;
1883 } // if
1884 CurPos++;
1885 } // while
1886 // After while() loop, CurPos is one past the end of the element
1887 while ((CurPos < StrLen(InString)) && (!Found)) {
1888 if (InString[CurPos] == L',')
1889 Found = TRUE;
1890 else
1891 CurPos++;
1892 } // while
1893 if (Index == 0)
1894 FoundString = StrDuplicate(&InString[StartPos]);
1895 if (FoundString != NULL)
1896 FoundString[CurPos - StartPos] = 0;
1897 } // if
1898 return (FoundString);
1899 } // CHAR16 *FindCommaDelimited()
1900
1901 // Return the position of SmallString within BigString, or -1 if
1902 // not found.
1903 INTN FindSubString(IN CHAR16 *SmallString, IN CHAR16 *BigString) {
1904 INTN Position = -1;
1905 UINTN i = 0, SmallSize, BigSize;
1906 BOOLEAN Found = FALSE;
1907
1908 if ((SmallString == NULL) || (BigString == NULL))
1909 return -1;
1910
1911 SmallSize = StrLen(SmallString);
1912 BigSize = StrLen(BigString);
1913 if ((SmallSize > BigSize) || (SmallSize == 0) || (BigSize == 0))
1914 return -1;
1915
1916 while ((i <= (BigSize - SmallSize) && !Found)) {
1917 if (CompareMem(BigString + i, SmallString, SmallSize) == 0) {
1918 Found = TRUE;
1919 Position = i;
1920 } // if
1921 i++;
1922 } // while()
1923 return Position;
1924 } // INTN FindSubString()
1925
1926 // Take an input path name, which may include a volume specification and/or
1927 // a path, and return separate volume, path, and file names. For instance,
1928 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1929 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1930 // the returned pointer is NULL. The calling function is responsible for
1931 // freeing the allocated memory.
1932 VOID SplitPathName(CHAR16 *InPath, CHAR16 **VolName, CHAR16 **Path, CHAR16 **Filename) {
1933 CHAR16 *Temp = NULL;
1934
1935 MyFreePool(*VolName);
1936 MyFreePool(*Path);
1937 MyFreePool(*Filename);
1938 *VolName = *Path = *Filename = NULL;
1939 Temp = StrDuplicate(InPath);
1940 SplitVolumeAndFilename(&Temp, VolName); // VolName is NULL or has volume; Temp has rest of path
1941 CleanUpPathNameSlashes(Temp);
1942 *Path = FindPath(Temp); // *Path has path (may be 0-length); Temp unchanged.
1943 *Filename = StrDuplicate(Temp + StrLen(*Path));
1944 CleanUpPathNameSlashes(*Filename);
1945 if (StrLen(*Path) == 0) {
1946 MyFreePool(*Path);
1947 *Path = NULL;
1948 }
1949 if (StrLen(*Filename) == 0) {
1950 MyFreePool(*Filename);
1951 *Filename = NULL;
1952 }
1953 MyFreePool(Temp);
1954 } // VOID SplitPathName
1955
1956 // Returns TRUE if SmallString is an element in the comma-delimited List,
1957 // FALSE otherwise. Performs comparison case-insensitively (except on
1958 // buggy EFIs with case-sensitive StriCmp() functions).
1959 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1960 UINTN i = 0;
1961 BOOLEAN Found = FALSE;
1962 CHAR16 *OneElement;
1963
1964 if (SmallString && List) {
1965 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1966 if (StriCmp(OneElement, SmallString) == 0)
1967 Found = TRUE;
1968 } // while
1969 } // if
1970 return Found;
1971 } // BOOLEAN IsIn()
1972
1973 // Returns TRUE if any element of List can be found as a substring of
1974 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1975 BOOLEAN IsInSubstring(IN CHAR16 *BigString, IN CHAR16 *List) {
1976 UINTN i = 0, ElementLength;
1977 BOOLEAN Found = FALSE;
1978 CHAR16 *OneElement;
1979
1980 if (BigString && List) {
1981 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1982 ElementLength = StrLen(OneElement);
1983 if ((ElementLength <= StrLen(BigString)) && (StriSubCmp(OneElement, BigString)))
1984 Found = TRUE;
1985 } // while
1986 } // if
1987 return Found;
1988 } // BOOLEAN IsSubstringIn()
1989
1990 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1991 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1992 // Filename must *NOT* include a volume or path specification (that's part of
1993 // the Volume variable), but the List elements may. Performs comparison
1994 // case-insensitively (except on buggy EFIs with case-sensitive StriCmp()
1995 // functions).
1996 BOOLEAN FilenameIn(REFIT_VOLUME *Volume, CHAR16 *Directory, CHAR16 *Filename, CHAR16 *List) {
1997 UINTN i = 0;
1998 BOOLEAN Found = FALSE;
1999 CHAR16 *OneElement;
2000 CHAR16 *TargetVolName = NULL, *TargetPath = NULL, *TargetFilename = NULL;
2001
2002 if (Filename && List) {
2003 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
2004 Found = TRUE;
2005 SplitPathName(OneElement, &TargetVolName, &TargetPath, &TargetFilename);
2006 VolumeNumberToName(Volume, &TargetVolName);
2007 if (((TargetVolName != NULL) && ((Volume == NULL) || (StriCmp(TargetVolName, Volume->VolName) != 0))) ||
2008 ((TargetPath != NULL) && (StriCmp(TargetPath, Directory) != 0)) ||
2009 ((TargetFilename != NULL) && (StriCmp(TargetFilename, Filename) != 0))) {
2010 Found = FALSE;
2011 } // if
2012 MyFreePool(OneElement);
2013 } // while
2014 } // if
2015
2016 MyFreePool(TargetVolName);
2017 MyFreePool(TargetPath);
2018 MyFreePool(TargetFilename);
2019 return Found;
2020 } // BOOLEAN FilenameIn()
2021
2022 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
2023 // to this volume number, returns with *VolName changed to the volume name, as
2024 // stored in the Volume data structure.
2025 // Returns TRUE if this substitution was made, FALSE otherwise.
2026 BOOLEAN VolumeNumberToName(REFIT_VOLUME *Volume, CHAR16 **VolName) {
2027 BOOLEAN MadeSubstitution = FALSE;
2028 UINTN VolNum;
2029
2030 if ((VolName == NULL) || (*VolName == NULL))
2031 return FALSE;
2032
2033 if ((StrLen(*VolName) > 2) && (*VolName[0] == L'f') && (*VolName[1] == L's') && (*VolName[2] >= L'0') && (*VolName[2] <= L'9')) {
2034 VolNum = Atoi(*VolName + 2);
2035 if (VolNum == Volume->VolNumber) {
2036 MyFreePool(*VolName);
2037 *VolName = StrDuplicate(Volume->VolName);
2038 MadeSubstitution = TRUE;
2039 } // if
2040 } // if
2041 return MadeSubstitution;
2042 } // BOOLEAN VolumeMatchesNumber()
2043
2044 // Implement FreePool the way it should have been done to begin with, so that
2045 // it doesn't throw an ASSERT message if fed a NULL pointer....
2046 VOID MyFreePool(IN VOID *Pointer) {
2047 if (Pointer != NULL)
2048 FreePool(Pointer);
2049 }
2050
2051 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
2052
2053 // Eject all removable media.
2054 // Returns TRUE if any media were ejected, FALSE otherwise.
2055 BOOLEAN EjectMedia(VOID) {
2056 EFI_STATUS Status;
2057 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
2058 EFI_HANDLE *Handles, Handle;
2059 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
2060
2061 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
2062 if (EFI_ERROR(Status) || HandleCount == 0)
2063 return (FALSE); // probably not an Apple system
2064
2065 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
2066 Handle = Handles[HandleIndex];
2067 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
2068 if (EFI_ERROR(Status))
2069 continue;
2070 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
2071 if (!EFI_ERROR(Status))
2072 Ejected++;
2073 }
2074 MyFreePool(Handles);
2075 return (Ejected > 0);
2076 } // VOID EjectMedia()
2077
2078 // Converts consecutive characters in the input string into a
2079 // number, interpreting the string as a hexadecimal number, starting
2080 // at the specified position and continuing for the specified number
2081 // of characters or until the end of the string, whichever is first.
2082 // NumChars must be between 1 and 16. Ignores invalid characters.
2083 UINT64 StrToHex(CHAR16 *Input, UINTN Pos, UINTN NumChars) {
2084 UINT64 retval = 0x00;
2085 UINTN NumDone = 0;
2086 CHAR16 a;
2087
2088 if ((Input == NULL) || (StrLen(Input) < Pos) || (NumChars == 0) || (NumChars > 16)) {
2089 return 0;
2090 }
2091
2092 while ((StrLen(Input) >= Pos) && (NumDone < NumChars)) {
2093 a = Input[Pos];
2094 if ((a >= '0') && (a <= '9')) {
2095 retval *= 0x10;
2096 retval += (a - '0');
2097 NumDone++;
2098 }
2099 if ((a >= 'a') && (a <= 'f')) {
2100 retval *= 0x10;
2101 retval += (a - 'a' + 0x0a);
2102 NumDone++;
2103 }
2104 if ((a >= 'A') && (a <= 'F')) {
2105 retval *= 0x10;
2106 retval += (a - 'A' + 0x0a);
2107 NumDone++;
2108 }
2109 Pos++;
2110 } // while()
2111 return retval;
2112 } // StrToHex()
2113
2114 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2115 // Note that the input string must have no extraneous spaces and must be
2116 // conventionally formatted as a 36-character GUID, complete with dashes in
2117 // appropriate places.
2118 BOOLEAN IsGuid(CHAR16 *UnknownString) {
2119 UINTN Length, i;
2120 BOOLEAN retval = TRUE;
2121 CHAR16 a;
2122
2123 if (UnknownString == NULL)
2124 return FALSE;
2125
2126 Length = StrLen(UnknownString);
2127 if (Length != 36)
2128 return FALSE;
2129
2130 for (i = 0; i < Length; i++) {
2131 a = UnknownString[i];
2132 if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) {
2133 if (a != '-')
2134 retval = FALSE;
2135 } else if (((a < 'a') || (a > 'f')) && ((a < 'A') || (a > 'F')) && ((a < '0') && (a > '9'))) {
2136 retval = FALSE;
2137 } // if/else if
2138 } // for
2139 return retval;
2140 } // BOOLEAN IsGuid()
2141
2142 // Return the GUID as a string, suitable for display to the user. Note that the calling
2143 // function is responsible for freeing the allocated memory.
2144 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
2145 CHAR16 *TheString;
2146
2147 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
2148 if (TheString != 0) {
2149 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2150 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
2151 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
2152 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
2153 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
2154 }
2155 return TheString;
2156 } // GuidAsString(EFI_GUID *GuidData)
2157
2158 EFI_GUID StringAsGuid(CHAR16 * InString) {
2159 EFI_GUID Guid = NULL_GUID_VALUE;
2160
2161 if (!IsGuid(InString)) {
2162 return Guid;
2163 }
2164
2165 Guid.Data1 = (UINT32) StrToHex(InString, 0, 8);
2166 Guid.Data2 = (UINT16) StrToHex(InString, 9, 4);
2167 Guid.Data3 = (UINT16) StrToHex(InString, 14, 4);
2168 Guid.Data4[0] = (UINT8) StrToHex(InString, 19, 2);
2169 Guid.Data4[1] = (UINT8) StrToHex(InString, 21, 2);
2170 Guid.Data4[2] = (UINT8) StrToHex(InString, 23, 2);
2171 Guid.Data4[3] = (UINT8) StrToHex(InString, 26, 2);
2172 Guid.Data4[4] = (UINT8) StrToHex(InString, 28, 2);
2173 Guid.Data4[5] = (UINT8) StrToHex(InString, 30, 2);
2174 Guid.Data4[6] = (UINT8) StrToHex(InString, 32, 2);
2175 Guid.Data4[7] = (UINT8) StrToHex(InString, 34, 2);
2176
2177 return Guid;
2178 } // EFI_GUID StringAsGuid()
2179
2180 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2181 BOOLEAN GuidsAreEqual(EFI_GUID *Guid1, EFI_GUID *Guid2) {
2182 return (CompareMem(Guid1, Guid2, 16) == 0);
2183 } // BOOLEAN CompareGuids()
2184