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