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