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