]> code.delx.au - refind/blob - refind/lib.c
Remove second and subsequent occurrences of ext2/3/4 and ReiserFS filesystems
[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-2013 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 + 62)) {
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 Print(L"Found ReiserFS UUID: %s\n", GuidAsString(&(Volume->VolUuid)));
482 PauseForKey();
483 return;
484 } // if
485 } // search for ReiserFS magic
486
487 if (BufferSize >= (65536 + 64 + 8)) {
488 MagicString = (char*) (Buffer + 65536 + 64);
489 if (CompareMem(MagicString, BTRFS_SIGNATURE, 8) == 0) {
490 Volume->FSType = FS_TYPE_BTRFS;
491 return;
492 } // if
493 } // search for Btrfs magic
494
495 if (BufferSize >= (1024 + 2)) {
496 Magic16 = (UINT16*) (Buffer + 1024);
497 if ((*Magic16 == HFSPLUS_MAGIC1) || (*Magic16 == HFSPLUS_MAGIC2)) {
498 Volume->FSType = FS_TYPE_HFSPLUS;
499 return;
500 }
501 } // search for HFS+ magic
502 } // if (Buffer != NULL)
503
504 } // UINT32 SetFilesystemData()
505
506 static VOID ScanVolumeBootcode(REFIT_VOLUME *Volume, BOOLEAN *Bootable)
507 {
508 EFI_STATUS Status;
509 UINT8 Buffer[SAMPLE_SIZE];
510 UINTN i;
511 MBR_PARTITION_INFO *MbrTable;
512 BOOLEAN MbrTableFound;
513
514 Volume->HasBootCode = FALSE;
515 Volume->OSIconName = NULL;
516 Volume->OSName = NULL;
517 *Bootable = FALSE;
518
519 if (Volume->BlockIO == NULL)
520 return;
521 if (Volume->BlockIO->Media->BlockSize > SAMPLE_SIZE)
522 return; // our buffer is too small...
523
524 // look at the boot sector (this is used for both hard disks and El Torito images!)
525 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
526 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
527 Volume->BlockIOOffset, SAMPLE_SIZE, Buffer);
528 if (!EFI_ERROR(Status)) {
529
530 SetFilesystemData(Buffer, SAMPLE_SIZE, Volume);
531 if ((*((UINT16 *)(Buffer + 510)) == 0xaa55 && Buffer[0] != 0) && (FindMem(Buffer, 512, "EXFAT", 5) == -1)) {
532 *Bootable = TRUE;
533 Volume->HasBootCode = TRUE;
534 }
535
536 // detect specific boot codes
537 if (CompareMem(Buffer + 2, "LILO", 4) == 0 ||
538 CompareMem(Buffer + 6, "LILO", 4) == 0 ||
539 CompareMem(Buffer + 3, "SYSLINUX", 8) == 0 ||
540 FindMem(Buffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
541 Volume->HasBootCode = TRUE;
542 Volume->OSIconName = L"linux";
543 Volume->OSName = L"Linux";
544
545 } else if (FindMem(Buffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
546 Volume->HasBootCode = TRUE;
547 Volume->OSIconName = L"grub,linux";
548 Volume->OSName = L"Linux";
549
550 // // Below doesn't produce a bootable entry, so commented out for the moment....
551 // // GRUB in BIOS boot partition:
552 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
553 // Volume->HasBootCode = TRUE;
554 // Volume->OSIconName = L"grub,linux";
555 // Volume->OSName = L"Linux";
556 // Volume->VolName = L"BIOS Boot Partition";
557 // *Bootable = TRUE;
558
559 } else if ((*((UINT32 *)(Buffer + 502)) == 0 &&
560 *((UINT32 *)(Buffer + 506)) == 50000 &&
561 *((UINT16 *)(Buffer + 510)) == 0xaa55) ||
562 FindMem(Buffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
563 Volume->HasBootCode = TRUE;
564 Volume->OSIconName = L"freebsd";
565 Volume->OSName = L"FreeBSD";
566
567 } else if (FindMem(Buffer, 512, "!Loading", 8) >= 0 ||
568 FindMem(Buffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
569 Volume->HasBootCode = TRUE;
570 Volume->OSIconName = L"openbsd";
571 Volume->OSName = L"OpenBSD";
572
573 } else if (FindMem(Buffer, 512, "Not a bootxx image", 18) >= 0 ||
574 *((UINT32 *)(Buffer + 1028)) == 0x7886b6d1) {
575 Volume->HasBootCode = TRUE;
576 Volume->OSIconName = L"netbsd";
577 Volume->OSName = L"NetBSD";
578
579 } else if (FindMem(Buffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
580 Volume->HasBootCode = TRUE;
581 Volume->OSIconName = L"win";
582 Volume->OSName = L"Windows";
583
584 } else if (FindMem(Buffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
585 Volume->HasBootCode = TRUE;
586 Volume->OSIconName = L"winvista,win";
587 Volume->OSName = L"Windows";
588
589 } else if (FindMem(Buffer, 512, "CPUBOOT SYS", 11) >= 0 ||
590 FindMem(Buffer, 512, "KERNEL SYS", 11) >= 0) {
591 Volume->HasBootCode = TRUE;
592 Volume->OSIconName = L"freedos";
593 Volume->OSName = L"FreeDOS";
594
595 } else if (FindMem(Buffer, 512, "OS2LDR", 6) >= 0 ||
596 FindMem(Buffer, 512, "OS2BOOT", 7) >= 0) {
597 Volume->HasBootCode = TRUE;
598 Volume->OSIconName = L"ecomstation";
599 Volume->OSName = L"eComStation";
600
601 } else if (FindMem(Buffer, 512, "Be Boot Loader", 14) >= 0) {
602 Volume->HasBootCode = TRUE;
603 Volume->OSIconName = L"beos";
604 Volume->OSName = L"BeOS";
605
606 } else if (FindMem(Buffer, 512, "yT Boot Loader", 14) >= 0) {
607 Volume->HasBootCode = TRUE;
608 Volume->OSIconName = L"zeta,beos";
609 Volume->OSName = L"ZETA";
610
611 } else if (FindMem(Buffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
612 FindMem(Buffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
613 Volume->HasBootCode = TRUE;
614 Volume->OSIconName = L"haiku,beos";
615 Volume->OSName = L"Haiku";
616
617 }
618
619 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
620 // need to fix AddLegacyEntry in main.c.
621
622 #if REFIT_DEBUG > 0
623 Print(L" Result of bootcode detection: %s %s (%s)\n",
624 Volume->HasBootCode ? L"bootable" : L"non-bootable",
625 Volume->OSName, Volume->OSIconName);
626 #endif
627
628 // dummy FAT boot sector (created by OS X's newfs_msdos)
629 if (FindMem(Buffer, 512, "Non-system disk", 15) >= 0)
630 Volume->HasBootCode = FALSE;
631
632 // dummy FAT boot sector (created by Linux's mkdosfs)
633 if (FindMem(Buffer, 512, "This is not a bootable disk", 27) >= 0)
634 Volume->HasBootCode = FALSE;
635
636 // dummy FAT boot sector (created by Windows)
637 if (FindMem(Buffer, 512, "Press any key to restart", 24) >= 0)
638 Volume->HasBootCode = FALSE;
639
640 // check for MBR partition table
641 if (*((UINT16 *)(Buffer + 510)) == 0xaa55) {
642 MbrTableFound = FALSE;
643 MbrTable = (MBR_PARTITION_INFO *)(Buffer + 446);
644 for (i = 0; i < 4; i++)
645 if (MbrTable[i].StartLBA && MbrTable[i].Size)
646 MbrTableFound = TRUE;
647 for (i = 0; i < 4; i++)
648 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
649 MbrTableFound = FALSE;
650 if (MbrTableFound) {
651 Volume->MbrPartitionTable = AllocatePool(4 * 16);
652 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
653 }
654 }
655
656 } else {
657 #if REFIT_DEBUG > 0
658 CheckError(Status, L"while reading boot sector");
659 #endif
660 }
661 } /* VOID ScanVolumeBootcode() */
662
663 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
664 VOID SetVolumeBadgeIcon(REFIT_VOLUME *Volume)
665 {
666 if (Volume->VolBadgeImage == NULL) {
667 Volume->VolBadgeImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeBadge", 128);
668 }
669
670 if (Volume->VolBadgeImage == NULL) {
671 switch (Volume->DiskKind) {
672 case DISK_KIND_INTERNAL:
673 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
674 break;
675 case DISK_KIND_EXTERNAL:
676 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
677 break;
678 case DISK_KIND_OPTICAL:
679 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
680 break;
681 } // switch()
682 }
683 } // VOID SetVolumeBadgeIcon()
684
685 // Return a string representing the input size in IEEE-1541 units.
686 // The calling function is responsible for freeing the allocated memory.
687 static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
688 UINT64 SizeInIeee;
689 UINTN Index = 0, NumPrefixes;
690 CHAR16 *Units, *Prefixes = L" KMGTPEZ";
691 CHAR16 *TheValue;
692
693 TheValue = AllocateZeroPool(sizeof(CHAR16) * 256);
694 if (TheValue != NULL) {
695 NumPrefixes = StrLen(Prefixes);
696 SizeInIeee = SizeInBytes;
697 while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
698 Index++;
699 SizeInIeee /= 1024;
700 } // while
701 if (Prefixes[Index] == ' ') {
702 Units = StrDuplicate(L"-byte");
703 } else {
704 Units = StrDuplicate(L" iB");
705 Units[1] = Prefixes[Index];
706 } // if/else
707 SPrint(TheValue, 255, L"%ld%s", SizeInIeee, Units);
708 } // if
709 return TheValue;
710 } // CHAR16 *SizeInSIUnits()
711
712 // Return a name for the volume. Ideally this should be the label for the
713 // filesystem it contains, but this function falls back to describing the
714 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
715 // this information can be extracted.
716 // The calling function is responsible for freeing the memory allocated
717 // for the name string.
718 static CHAR16 *GetVolumeName(IN REFIT_VOLUME *Volume) {
719 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
720 CHAR16 *FoundName = NULL;
721 CHAR16 *SISize, *TypeName;
722
723 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
724 if (FileSystemInfoPtr != NULL) { // we have filesystem information (size, label)....
725 if ((FileSystemInfoPtr->VolumeLabel != NULL) && (StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
726 FoundName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
727 }
728
729 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
730 // this so that we can build a new name that includes the size....
731 if ((FoundName != NULL) && (StrCmp(FoundName, L"HFS+ volume") == 0) && (Volume->FSType == FS_TYPE_HFSPLUS)) {
732 MyFreePool(FoundName);
733 FoundName = NULL;
734 } // if rEFInd HFS+ driver suspected
735
736 if (FoundName == NULL) { // filesystem has no name, so use fs type and size
737 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
738 if (FoundName != NULL) {
739 SISize = SizeInIEEEUnits(FileSystemInfoPtr->VolumeSize);
740 SPrint(FoundName, 255, L"%s%s volume", SISize, FSTypeName(Volume->FSType));
741 MyFreePool(SISize);
742 } // if allocated memory OK
743 } // if (FoundName == NULL)
744
745 FreePool(FileSystemInfoPtr);
746
747 } else { // fs driver not returning info; fall back on our own information....
748 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
749 if (FoundName != NULL) {
750 TypeName = FSTypeName(Volume->FSType); // NOTE: Don't free TypeName; function returns constant
751 if (StrLen(TypeName) > 0)
752 SPrint(FoundName, 255, L"%s volume", FSTypeName(Volume->FSType));
753 else
754 SPrint(FoundName, 255, L"unknown volume");
755 } // if allocated memory OK
756 } // if
757
758 // TODO: Above could be improved/extended, in case filesystem name is not found,
759 // such as:
760 // - use partition label
761 // - use or add disk/partition number (e.g., "(hd0,2)")
762
763 // Desperate fallback name....
764 if (FoundName == NULL) {
765 FoundName = StrDuplicate(L"unknown volume");
766 }
767 return FoundName;
768 } // static CHAR16 *GetVolumeName()
769
770 VOID ScanVolume(REFIT_VOLUME *Volume)
771 {
772 EFI_STATUS Status;
773 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
774 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
775 EFI_HANDLE WholeDiskHandle;
776 UINTN PartialLength;
777 BOOLEAN Bootable;
778
779 // get device path
780 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
781 #if REFIT_DEBUG > 0
782 if (Volume->DevicePath != NULL) {
783 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
784 #if REFIT_DEBUG >= 2
785 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
786 #endif
787 }
788 #endif
789
790 Volume->DiskKind = DISK_KIND_INTERNAL; // default
791
792 // get block i/o
793 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
794 if (EFI_ERROR(Status)) {
795 Volume->BlockIO = NULL;
796 Print(L"Warning: Can't get BlockIO protocol.\n");
797 } else {
798 if (Volume->BlockIO->Media->BlockSize == 2048)
799 Volume->DiskKind = DISK_KIND_OPTICAL;
800 }
801
802 // scan for bootcode and MBR table
803 Bootable = FALSE;
804 ScanVolumeBootcode(Volume, &Bootable);
805
806 // detect device type
807 DevicePath = Volume->DevicePath;
808 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
809 NextDevicePath = NextDevicePathNode(DevicePath);
810
811 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
812 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
813 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
814 DevicePathSubType(DevicePath) == MSG_1394_DP ||
815 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
816 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
817 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
818 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
819 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
820 Bootable = TRUE;
821 }
822
823 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
824 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
825 // TODO: also check for Boot Camp GUID
826 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
827 }
828
829 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
830 // make a device path for the whole device
831 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
832 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
833 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
834 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
835
836 // get the handle for that path
837 RemainingDevicePath = DiskDevicePath;
838 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
839 FreePool(DiskDevicePath);
840
841 if (!EFI_ERROR(Status)) {
842 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
843
844 // get the device path for later
845 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
846 if (!EFI_ERROR(Status)) {
847 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
848 }
849
850 // look at the BlockIO protocol
851 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
852 if (!EFI_ERROR(Status)) {
853
854 // check the media block size
855 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
856 Volume->DiskKind = DISK_KIND_OPTICAL;
857
858 } else {
859 Volume->WholeDiskBlockIO = NULL;
860 //CheckError(Status, L"from HandleProtocol");
861 }
862 } //else
863 // CheckError(Status, L"from LocateDevicePath");
864 }
865
866 DevicePath = NextDevicePath;
867 } // while
868
869 if (!Bootable) {
870 #if REFIT_DEBUG > 0
871 if (Volume->HasBootCode)
872 Print(L" Volume considered non-bootable, but boot code is present\n");
873 #endif
874 Volume->HasBootCode = FALSE;
875 }
876
877 // open the root directory of the volume
878 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
879
880 // Set volume icon based on .VolumeBadge icon or disk kind
881 SetVolumeBadgeIcon(Volume);
882
883 if (Volume->RootDir == NULL) {
884 Volume->IsReadable = FALSE;
885 return;
886 } else {
887 Volume->IsReadable = TRUE;
888 }
889
890 Volume->VolName = GetVolumeName(Volume);
891
892 // get custom volume icons if present
893 if (!Volume->VolIconImage)
894 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", 128);
895 } // ScanVolume()
896
897 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
898 {
899 EFI_STATUS Status;
900 REFIT_VOLUME *Volume;
901 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
902 UINTN i;
903 UINTN LogicalPartitionIndex = 4;
904 UINT8 SectorBuffer[512];
905 BOOLEAN Bootable;
906 MBR_PARTITION_INFO *EMbrTable;
907
908 ExtBase = MbrEntry->StartLBA;
909
910 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
911 // read current EMBR
912 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
913 WholeDiskVolume->BlockIO,
914 WholeDiskVolume->BlockIO->Media->MediaId,
915 ExtCurrent, 512, SectorBuffer);
916 if (EFI_ERROR(Status))
917 break;
918 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
919 break;
920 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
921
922 // scan logical partitions in this EMBR
923 NextExtCurrent = 0;
924 for (i = 0; i < 4; i++) {
925 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
926 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
927 break;
928 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
929 // set next ExtCurrent
930 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
931 break;
932 } else {
933
934 // found a logical partition
935 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
936 Volume->DiskKind = WholeDiskVolume->DiskKind;
937 Volume->IsMbrPartition = TRUE;
938 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
939 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
940 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
941 Volume->BlockIO = WholeDiskVolume->BlockIO;
942 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
943 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
944
945 Bootable = FALSE;
946 ScanVolumeBootcode(Volume, &Bootable);
947 if (!Bootable)
948 Volume->HasBootCode = FALSE;
949
950 SetVolumeBadgeIcon(Volume);
951
952 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
953
954 }
955 }
956 }
957 } /* VOID ScanExtendedPartition() */
958
959 VOID ScanVolumes(VOID)
960 {
961 EFI_STATUS Status;
962 EFI_HANDLE *Handles;
963 REFIT_VOLUME *Volume, *WholeDiskVolume;
964 MBR_PARTITION_INFO *MbrTable;
965 UINTN HandleCount = 0;
966 UINTN HandleIndex;
967 UINTN VolumeIndex, VolumeIndex2;
968 UINTN PartitionIndex;
969 UINTN SectorSum, i, VolNumber = 0;
970 UINT8 *SectorBuffer1, *SectorBuffer2;
971 EFI_GUID *UuidList;
972 EFI_GUID NullUuid = { 00000000, 0000, 0000, {0000, 0000, 0000, 0000} };
973
974 MyFreePool(Volumes);
975 Volumes = NULL;
976 VolumesCount = 0;
977
978 // get all filesystem handles
979 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
980 UuidList = AllocateZeroPool(sizeof(EFI_GUID) * HandleCount);
981 // was: &FileSystemProtocol
982 if (Status == EFI_NOT_FOUND) {
983 return; // no filesystems. strange, but true...
984 }
985 if (CheckError(Status, L"while listing all file systems"))
986 return;
987
988 // first pass: collect information about all handles
989 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
990 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
991 Volume->DeviceHandle = Handles[HandleIndex];
992 ScanVolume(Volume);
993 if (UuidList) {
994 UuidList[HandleIndex] = Volume->VolUuid;
995 for (i = 0; i < HandleIndex; i++) {
996 if ((CompareMem(&(Volume->VolUuid), &(UuidList[i]), sizeof(EFI_GUID)) == 0) &&
997 (CompareMem(&(Volume->VolUuid), &NullUuid, sizeof(EFI_GUID)) != 0)) { // Duplicate filesystem UUID
998 Volume->IsReadable = FALSE;
999 } // if
1000 } // for
1001 } // if
1002 if (Volume->IsReadable)
1003 Volume->VolNumber = VolNumber++;
1004 else
1005 Volume->VolNumber = VOL_UNREADABLE;
1006
1007 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1008
1009 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
1010 SelfVolume = Volume;
1011 }
1012 MyFreePool(Handles);
1013
1014 if (SelfVolume == NULL)
1015 Print(L"WARNING: SelfVolume not found");
1016
1017 // second pass: relate partitions and whole disk devices
1018 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1019 Volume = Volumes[VolumeIndex];
1020 // check MBR partition table for extended partitions
1021 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1022 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
1023 Volume->MbrPartitionTable != NULL) {
1024 MbrTable = Volume->MbrPartitionTable;
1025 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1026 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
1027 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
1028 }
1029 }
1030 }
1031
1032 // search for corresponding whole disk volume entry
1033 WholeDiskVolume = NULL;
1034 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1035 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1036 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1037 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1038 Volumes[VolumeIndex2]->BlockIOOffset == 0)
1039 WholeDiskVolume = Volumes[VolumeIndex2];
1040 }
1041 }
1042
1043 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1044 // check if this volume is one of the partitions in the table
1045 MbrTable = WholeDiskVolume->MbrPartitionTable;
1046 SectorBuffer1 = AllocatePool(512);
1047 SectorBuffer2 = AllocatePool(512);
1048 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1049 // check size
1050 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1051 continue;
1052
1053 // compare boot sector read through offset vs. directly
1054 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1055 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1056 Volume->BlockIOOffset, 512, SectorBuffer1);
1057 if (EFI_ERROR(Status))
1058 break;
1059 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1060 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1061 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1062 if (EFI_ERROR(Status))
1063 break;
1064 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1065 continue;
1066 SectorSum = 0;
1067 for (i = 0; i < 512; i++)
1068 SectorSum += SectorBuffer1[i];
1069 if (SectorSum < 1000)
1070 continue;
1071
1072 // TODO: mark entry as non-bootable if it is an extended partition
1073
1074 // now we're reasonably sure the association is correct...
1075 Volume->IsMbrPartition = TRUE;
1076 Volume->MbrPartitionIndex = PartitionIndex;
1077 if (Volume->VolName == NULL) {
1078 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1079 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1080 }
1081 break;
1082 }
1083
1084 MyFreePool(SectorBuffer1);
1085 MyFreePool(SectorBuffer2);
1086 }
1087
1088 } // for
1089 } /* VOID ScanVolumes() */
1090
1091 static VOID UninitVolumes(VOID)
1092 {
1093 REFIT_VOLUME *Volume;
1094 UINTN VolumeIndex;
1095
1096 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1097 Volume = Volumes[VolumeIndex];
1098
1099 if (Volume->RootDir != NULL) {
1100 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
1101 Volume->RootDir = NULL;
1102 }
1103
1104 Volume->DeviceHandle = NULL;
1105 Volume->BlockIO = NULL;
1106 Volume->WholeDiskBlockIO = NULL;
1107 }
1108 }
1109
1110 VOID ReinitVolumes(VOID)
1111 {
1112 EFI_STATUS Status;
1113 REFIT_VOLUME *Volume;
1114 UINTN VolumeIndex;
1115 EFI_DEVICE_PATH *RemainingDevicePath;
1116 EFI_HANDLE DeviceHandle, WholeDiskHandle;
1117
1118 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1119 Volume = Volumes[VolumeIndex];
1120
1121 if (Volume->DevicePath != NULL) {
1122 // get the handle for that path
1123 RemainingDevicePath = Volume->DevicePath;
1124 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
1125
1126 if (!EFI_ERROR(Status)) {
1127 Volume->DeviceHandle = DeviceHandle;
1128
1129 // get the root directory
1130 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1131
1132 } else
1133 CheckError(Status, L"from LocateDevicePath");
1134 }
1135
1136 if (Volume->WholeDiskDevicePath != NULL) {
1137 // get the handle for that path
1138 RemainingDevicePath = Volume->WholeDiskDevicePath;
1139 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
1140
1141 if (!EFI_ERROR(Status)) {
1142 // get the BlockIO protocol
1143 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
1144 if (EFI_ERROR(Status)) {
1145 Volume->WholeDiskBlockIO = NULL;
1146 CheckError(Status, L"from HandleProtocol");
1147 }
1148 } else
1149 CheckError(Status, L"from LocateDevicePath");
1150 }
1151 }
1152 }
1153
1154 //
1155 // file and dir functions
1156 //
1157
1158 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1159 {
1160 EFI_STATUS Status;
1161 EFI_FILE_HANDLE TestFile;
1162
1163 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1164 if (Status == EFI_SUCCESS) {
1165 refit_call1_wrapper(TestFile->Close, TestFile);
1166 return TRUE;
1167 }
1168 return FALSE;
1169 }
1170
1171 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1172 {
1173 EFI_STATUS Status;
1174 VOID *Buffer;
1175 UINTN LastBufferSize, BufferSize;
1176 INTN IterCount;
1177
1178 for (;;) {
1179
1180 // free pointer from last call
1181 if (*DirEntry != NULL) {
1182 FreePool(*DirEntry);
1183 *DirEntry = NULL;
1184 }
1185
1186 // read next directory entry
1187 LastBufferSize = BufferSize = 256;
1188 Buffer = AllocatePool(BufferSize);
1189 for (IterCount = 0; ; IterCount++) {
1190 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1191 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1192 break;
1193 if (BufferSize <= LastBufferSize) {
1194 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1195 BufferSize = LastBufferSize * 2;
1196 #if REFIT_DEBUG > 0
1197 } else {
1198 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1199 #endif
1200 }
1201 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1202 LastBufferSize = BufferSize;
1203 }
1204 if (EFI_ERROR(Status)) {
1205 MyFreePool(Buffer);
1206 Buffer = NULL;
1207 break;
1208 }
1209
1210 // check for end of listing
1211 if (BufferSize == 0) { // end of directory listing
1212 MyFreePool(Buffer);
1213 Buffer = NULL;
1214 break;
1215 }
1216
1217 // entry is ready to be returned
1218 *DirEntry = (EFI_FILE_INFO *)Buffer;
1219
1220 // filter results
1221 if (FilterMode == 1) { // only return directories
1222 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1223 break;
1224 } else if (FilterMode == 2) { // only return files
1225 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1226 break;
1227 } else // no filter or unknown filter -> return everything
1228 break;
1229
1230 }
1231 return Status;
1232 }
1233
1234 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1235 {
1236 if (RelativePath == NULL) {
1237 DirIter->LastStatus = EFI_SUCCESS;
1238 DirIter->DirHandle = BaseDir;
1239 DirIter->CloseDirHandle = FALSE;
1240 } else {
1241 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1242 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1243 }
1244 DirIter->LastFileInfo = NULL;
1245 }
1246
1247 #ifndef __MAKEWITH_GNUEFI
1248 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1249
1250 static EFI_STATUS
1251 InitializeUnicodeCollationProtocol (VOID)
1252 {
1253 EFI_STATUS Status;
1254
1255 if (mUnicodeCollation != NULL) {
1256 return EFI_SUCCESS;
1257 }
1258
1259 //
1260 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1261 // instances first and then select one which support English language.
1262 // Current implementation just pick the first instance.
1263 //
1264 Status = gBS->LocateProtocol (
1265 &gEfiUnicodeCollation2ProtocolGuid,
1266 NULL,
1267 (VOID **) &mUnicodeCollation
1268 );
1269 if (EFI_ERROR(Status)) {
1270 Status = gBS->LocateProtocol (
1271 &gEfiUnicodeCollationProtocolGuid,
1272 NULL,
1273 (VOID **) &mUnicodeCollation
1274 );
1275
1276 }
1277 return Status;
1278 }
1279
1280 static BOOLEAN
1281 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1282 {
1283 if (!mUnicodeCollation) {
1284 InitializeUnicodeCollationProtocol();
1285 }
1286 if (mUnicodeCollation)
1287 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1288 return FALSE; // Shouldn't happen
1289 }
1290
1291 static VOID StrLwr (IN OUT CHAR16 *Str) {
1292 if (!mUnicodeCollation) {
1293 InitializeUnicodeCollationProtocol();
1294 }
1295 if (mUnicodeCollation)
1296 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1297 }
1298
1299 #endif
1300
1301 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1302 OUT EFI_FILE_INFO **DirEntry)
1303 {
1304 BOOLEAN KeepGoing = TRUE;
1305 UINTN i;
1306 CHAR16 *OnePattern;
1307
1308 if (DirIter->LastFileInfo != NULL) {
1309 FreePool(DirIter->LastFileInfo);
1310 DirIter->LastFileInfo = NULL;
1311 }
1312
1313 if (EFI_ERROR(DirIter->LastStatus))
1314 return FALSE; // stop iteration
1315
1316 do {
1317 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1318 if (EFI_ERROR(DirIter->LastStatus))
1319 return FALSE;
1320 if (DirIter->LastFileInfo == NULL) // end of listing
1321 return FALSE;
1322 if (FilePattern != NULL) {
1323 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1324 KeepGoing = FALSE;
1325 i = 0;
1326 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1327 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1328 KeepGoing = FALSE;
1329 } // while
1330 // else continue loop
1331 } else
1332 break;
1333 } while (KeepGoing && FilePattern);
1334
1335 *DirEntry = DirIter->LastFileInfo;
1336 return TRUE;
1337 }
1338
1339 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1340 {
1341 if (DirIter->LastFileInfo != NULL) {
1342 FreePool(DirIter->LastFileInfo);
1343 DirIter->LastFileInfo = NULL;
1344 }
1345 if (DirIter->CloseDirHandle)
1346 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1347 return DirIter->LastStatus;
1348 }
1349
1350 //
1351 // file name manipulation
1352 //
1353
1354 // Returns the filename portion (minus path name) of the
1355 // specified file
1356 CHAR16 * Basename(IN CHAR16 *Path)
1357 {
1358 CHAR16 *FileName;
1359 UINTN i;
1360
1361 FileName = Path;
1362
1363 if (Path != NULL) {
1364 for (i = StrLen(Path); i > 0; i--) {
1365 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1366 FileName = Path + i;
1367 break;
1368 }
1369 }
1370 }
1371
1372 return FileName;
1373 }
1374
1375 // Remove the .efi extension from FileName -- for instance, if FileName is
1376 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1377 // returns a copy of the original input.
1378 CHAR16 * StripEfiExtension(CHAR16 *FileName) {
1379 UINTN Length;
1380 CHAR16 *Copy = NULL;
1381
1382 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1383 Length = StrLen(Copy);
1384 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1385 if ((Length >= 4) && ((StriCmp(&Copy[Length - 4], L".efi") == 0) || (StriCmp(&Copy[Length - 4], L".EFI") == 0))) {
1386 Copy[Length - 4] = 0;
1387 } // if
1388 } // if
1389 return Copy;
1390 } // CHAR16 * StripExtension()
1391
1392 //
1393 // memory string search
1394 //
1395
1396 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1397 {
1398 UINT8 *BufferPtr;
1399 UINTN Offset;
1400
1401 BufferPtr = Buffer;
1402 BufferLength -= SearchStringLength;
1403 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1404 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1405 return (INTN)Offset;
1406 }
1407
1408 return -1;
1409 }
1410
1411 // Performs a case-insensitive search of BigStr for SmallStr.
1412 // Returns TRUE if found, FALSE if not.
1413 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1414 CHAR16 *SmallCopy, *BigCopy;
1415 BOOLEAN Found = FALSE;
1416 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1417
1418 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1419 SmallCopy = StrDuplicate(SmallStr);
1420 BigCopy = StrDuplicate(BigStr);
1421 StrLwr(SmallCopy);
1422 StrLwr(BigCopy);
1423 SmallLen = StrLen(SmallCopy);
1424 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1425 while ((!Found) && (StartPoint < NumCompares)) {
1426 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1427 } // while
1428 MyFreePool(SmallCopy);
1429 MyFreePool(BigCopy);
1430 } // if
1431
1432 return (Found);
1433 } // BOOLEAN StriSubCmp()
1434
1435 // Merges two strings, creating a new one and returning a pointer to it.
1436 // If AddChar != 0, the specified character is placed between the two original
1437 // strings (unless the first string is NULL or empty). The original input
1438 // string *First is de-allocated and replaced by the new merged string.
1439 // This is similar to StrCat, but safer and more flexible because
1440 // MergeStrings allocates memory that's the correct size for the
1441 // new merged string, so it can take a NULL *First and it cleans
1442 // up the old memory. It should *NOT* be used with a constant
1443 // *First, though....
1444 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1445 UINTN Length1 = 0, Length2 = 0;
1446 CHAR16* NewString;
1447
1448 if (*First != NULL)
1449 Length1 = StrLen(*First);
1450 if (Second != NULL)
1451 Length2 = StrLen(Second);
1452 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1453 if (NewString != NULL) {
1454 if ((*First != NULL) && (StrLen(*First) == 0)) {
1455 MyFreePool(*First);
1456 *First = NULL;
1457 }
1458 NewString[0] = L'\0';
1459 if (*First != NULL) {
1460 StrCat(NewString, *First);
1461 if (AddChar) {
1462 NewString[Length1] = AddChar;
1463 NewString[Length1 + 1] = '\0';
1464 } // if (AddChar)
1465 } // if (*First != NULL)
1466 if (Second != NULL)
1467 StrCat(NewString, Second);
1468 MyFreePool(*First);
1469 *First = NewString;
1470 } else {
1471 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1472 } // if/else
1473 } // static CHAR16* MergeStrings()
1474
1475 // Takes an input pathname (*Path) and returns the part of the filename from
1476 // the final dot onwards, converted to lowercase. If the filename includes
1477 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1478 // The calling function is responsible for freeing the memory associated with
1479 // the return value.
1480 CHAR16 *FindExtension(IN CHAR16 *Path) {
1481 CHAR16 *Extension;
1482 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1483 INTN i;
1484
1485 Extension = AllocateZeroPool(sizeof(CHAR16));
1486 if (Path) {
1487 i = StrLen(Path);
1488 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1489 if (Path[i] == L'.')
1490 Found = TRUE;
1491 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1492 FoundSlash = TRUE;
1493 if (!Found)
1494 i--;
1495 } // while
1496 if (Found) {
1497 MergeStrings(&Extension, &Path[i], 0);
1498 StrLwr(Extension);
1499 } // if (Found)
1500 } // if
1501 return (Extension);
1502 } // CHAR16 *FindExtension
1503
1504 // Takes an input pathname (*Path) and locates the final directory component
1505 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1506 // function returns the string 'foo'.
1507 // Assumes the pathname is separated with backslashes.
1508 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1509 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1510 CHAR16 *Found = NULL;
1511
1512 if (Path == NULL)
1513 return NULL;
1514
1515 PathLength = StrLen(Path);
1516 // Find start & end of target element
1517 for (i = 0; i < PathLength; i++) {
1518 if (Path[i] == '\\') {
1519 StartOfElement = EndOfElement;
1520 EndOfElement = i;
1521 } // if
1522 } // for
1523 // Extract the target element
1524 if (EndOfElement > 0) {
1525 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1526 StartOfElement++;
1527 } // while
1528 EndOfElement--;
1529 if (EndOfElement >= StartOfElement) {
1530 CopyLength = EndOfElement - StartOfElement + 1;
1531 Found = StrDuplicate(&Path[StartOfElement]);
1532 if (Found != NULL)
1533 Found[CopyLength] = 0;
1534 } // if (EndOfElement >= StartOfElement)
1535 } // if (EndOfElement > 0)
1536 return (Found);
1537 } // CHAR16 *FindLastDirName
1538
1539 // Returns the directory portion of a pathname. For instance,
1540 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1541 // string 'EFI\foo'. The calling function is responsible for
1542 // freeing the returned string's memory.
1543 CHAR16 *FindPath(IN CHAR16* FullPath) {
1544 UINTN i, LastBackslash = 0;
1545 CHAR16 *PathOnly = NULL;
1546
1547 if (FullPath != NULL) {
1548 for (i = 0; i < StrLen(FullPath); i++) {
1549 if (FullPath[i] == '\\')
1550 LastBackslash = i;
1551 } // for
1552 PathOnly = StrDuplicate(FullPath);
1553 PathOnly[LastBackslash] = 0;
1554 } // if
1555 return (PathOnly);
1556 }
1557
1558 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1559 // DeviceVolume, and returns that and the filename (*loader).
1560 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1561 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1562 UINTN i = 0;
1563 BOOLEAN Found = FALSE;
1564
1565 MyFreePool(*loader);
1566 MyFreePool(*DeviceVolume);
1567 *DeviceVolume = NULL;
1568 DeviceString = DevicePathToStr(loadpath);
1569 *loader = SplitDeviceString(DeviceString);
1570
1571 while ((i < VolumesCount) && (!Found)) {
1572 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1573 Temp = SplitDeviceString(VolumeDeviceString);
1574 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1575 Found = TRUE;
1576 *DeviceVolume = Volumes[i];
1577 }
1578 MyFreePool(Temp);
1579 MyFreePool(VolumeDeviceString);
1580 i++;
1581 } // while
1582
1583 MyFreePool(DeviceString);
1584 } // VOID FindVolumeAndFilename()
1585
1586 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1587 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1588 // the filename component in the original *Path variable and the split-off
1589 // volume component in the *VolName variable.
1590 // Returns TRUE if both components are found, FALSE otherwise.
1591 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1592 UINTN i = 0, Length;
1593 CHAR16 *Filename;
1594
1595 if (*Path == NULL)
1596 return FALSE;
1597
1598 if (*VolName != NULL) {
1599 MyFreePool(*VolName);
1600 *VolName = NULL;
1601 }
1602
1603 Length = StrLen(*Path);
1604 while ((i < Length) && ((*Path)[i] != L':')) {
1605 i++;
1606 } // while
1607
1608 if (i < Length) {
1609 Filename = StrDuplicate((*Path) + i + 1);
1610 (*Path)[i] = 0;
1611 *VolName = *Path;
1612 *Path = Filename;
1613 return TRUE;
1614 } else {
1615 return FALSE;
1616 }
1617 } // BOOLEAN SplitVolumeAndFilename()
1618
1619 // Returns all the digits in the input string, including intervening
1620 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1621 // this function returns "3.3.4-7". If InString contains no digits,
1622 // the return value is NULL.
1623 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1624 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1625 CHAR16 *Found = NULL;
1626
1627 if (InString == NULL)
1628 return NULL;
1629
1630 InLength = StartOfElement = StrLen(InString);
1631 // Find start & end of target element
1632 for (i = 0; i < InLength; i++) {
1633 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1634 if (StartOfElement > i)
1635 StartOfElement = i;
1636 if (EndOfElement < i)
1637 EndOfElement = i;
1638 } // if
1639 } // for
1640 // Extract the target element
1641 if (EndOfElement > 0) {
1642 if (EndOfElement >= StartOfElement) {
1643 CopyLength = EndOfElement - StartOfElement + 1;
1644 Found = StrDuplicate(&InString[StartOfElement]);
1645 if (Found != NULL)
1646 Found[CopyLength] = 0;
1647 } // if (EndOfElement >= StartOfElement)
1648 } // if (EndOfElement > 0)
1649 return (Found);
1650 } // CHAR16 *FindNumbers()
1651
1652 // Find the #Index element (numbered from 0) in a comma-delimited string
1653 // of elements.
1654 // Returns the found element, or NULL if Index is out of range or InString
1655 // is NULL. Note that the calling function is responsible for freeing the
1656 // memory associated with the returned string pointer.
1657 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1658 UINTN StartPos = 0, CurPos = 0;
1659 BOOLEAN Found = FALSE;
1660 CHAR16 *FoundString = NULL;
1661
1662 if (InString != NULL) {
1663 // After while() loop, StartPos marks start of item #Index
1664 while ((Index > 0) && (CurPos < StrLen(InString))) {
1665 if (InString[CurPos] == L',') {
1666 Index--;
1667 StartPos = CurPos + 1;
1668 } // if
1669 CurPos++;
1670 } // while
1671 // After while() loop, CurPos is one past the end of the element
1672 while ((CurPos < StrLen(InString)) && (!Found)) {
1673 if (InString[CurPos] == L',')
1674 Found = TRUE;
1675 else
1676 CurPos++;
1677 } // while
1678 if (Index == 0)
1679 FoundString = StrDuplicate(&InString[StartPos]);
1680 if (FoundString != NULL)
1681 FoundString[CurPos - StartPos] = 0;
1682 } // if
1683 return (FoundString);
1684 } // CHAR16 *FindCommaDelimited()
1685
1686 // Returns TRUE if SmallString is an element in the comma-delimited List,
1687 // FALSE otherwise. Performs comparison case-insensitively (except on
1688 // buggy EFIs with case-sensitive StriCmp() functions).
1689 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1690 UINTN i = 0;
1691 BOOLEAN Found = FALSE;
1692 CHAR16 *OneElement;
1693
1694 if (SmallString && List) {
1695 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1696 if (StriCmp(OneElement, SmallString) == 0)
1697 Found = TRUE;
1698 } // while
1699 } // if
1700 return Found;
1701 } // BOOLEAN IsIn()
1702
1703 // Implement FreePool the way it should have been done to begin with, so that
1704 // it doesn't throw an ASSERT message if fed a NULL pointer....
1705 VOID MyFreePool(IN VOID *Pointer) {
1706 if (Pointer != NULL)
1707 FreePool(Pointer);
1708 }
1709
1710 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1711
1712 // Eject all removable media.
1713 // Returns TRUE if any media were ejected, FALSE otherwise.
1714 BOOLEAN EjectMedia(VOID) {
1715 EFI_STATUS Status;
1716 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1717 EFI_HANDLE *Handles, Handle;
1718 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1719
1720 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1721 if (EFI_ERROR(Status) || HandleCount == 0)
1722 return (FALSE); // probably not an Apple system
1723
1724 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1725 Handle = Handles[HandleIndex];
1726 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1727 if (EFI_ERROR(Status))
1728 continue;
1729 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1730 if (!EFI_ERROR(Status))
1731 Ejected++;
1732 }
1733 MyFreePool(Handles);
1734 return (Ejected > 0);
1735 } // VOID EjectMedia()
1736
1737
1738 // Return the GUID as a string, suitable for display to the user. Note that the calling
1739 // function is responsible for freeing the allocated memory.
1740 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1741 CHAR16 *TheString;
1742
1743 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1744 if (TheString != 0) {
1745 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1746 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1747 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1748 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1749 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1750 }
1751 return TheString;
1752 } // GuidAsString(EFI_GUID *GuidData)