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