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