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