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