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