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