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