]> code.delx.au - refind/blob - refind/lib.c
Merge remote-tracking branch 'tianon/master'
[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 // Set volume icon based on .VolumeBadge icon or disk kind
1002 SetVolumeBadgeIcon(Volume);
1003
1004 Volume->VolName = GetVolumeName(Volume);
1005
1006 if (Volume->RootDir == NULL) {
1007 Volume->IsReadable = FALSE;
1008 return;
1009 } else {
1010 Volume->IsReadable = TRUE;
1011 if ((GlobalConfig.LegacyType == LEGACY_TYPE_MAC) && (Volume->FSType == FS_TYPE_NTFS) && Volume->HasBootCode) {
1012 // VBR boot code found on NTFS, but volume is not actually bootable
1013 // unless there are actual boot file, so check for them....
1014 Volume->HasBootCode = HasWindowsBiosBootFiles(Volume);
1015 }
1016 } // if/else
1017
1018 // get custom volume icons if present
1019 if (!Volume->VolIconImage) {
1020 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", GlobalConfig.IconSizes[ICON_SIZE_BIG]);
1021 }
1022 } // ScanVolume()
1023
1024 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
1025 {
1026 EFI_STATUS Status;
1027 REFIT_VOLUME *Volume;
1028 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
1029 UINTN i;
1030 UINTN LogicalPartitionIndex = 4;
1031 UINT8 SectorBuffer[512];
1032 BOOLEAN Bootable;
1033 MBR_PARTITION_INFO *EMbrTable;
1034
1035 ExtBase = MbrEntry->StartLBA;
1036
1037 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
1038 // read current EMBR
1039 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
1040 WholeDiskVolume->BlockIO,
1041 WholeDiskVolume->BlockIO->Media->MediaId,
1042 ExtCurrent, 512, SectorBuffer);
1043 if (EFI_ERROR(Status))
1044 break;
1045 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
1046 break;
1047 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
1048
1049 // scan logical partitions in this EMBR
1050 NextExtCurrent = 0;
1051 for (i = 0; i < 4; i++) {
1052 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
1053 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
1054 break;
1055 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
1056 // set next ExtCurrent
1057 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
1058 break;
1059 } else {
1060 // found a logical partition
1061 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1062 Volume->DiskKind = WholeDiskVolume->DiskKind;
1063 Volume->IsMbrPartition = TRUE;
1064 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
1065 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
1066 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
1067 Volume->BlockIO = WholeDiskVolume->BlockIO;
1068 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
1069 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
1070
1071 Bootable = FALSE;
1072 ScanVolumeBootcode(Volume, &Bootable);
1073 if (!Bootable)
1074 Volume->HasBootCode = FALSE;
1075 SetVolumeBadgeIcon(Volume);
1076 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1077 } // if/else
1078 } // for
1079 } // for
1080 } /* VOID ScanExtendedPartition() */
1081
1082 VOID ScanVolumes(VOID)
1083 {
1084 EFI_STATUS Status;
1085 EFI_HANDLE *Handles;
1086 REFIT_VOLUME *Volume, *WholeDiskVolume;
1087 MBR_PARTITION_INFO *MbrTable;
1088 UINTN HandleCount = 0;
1089 UINTN HandleIndex;
1090 UINTN VolumeIndex, VolumeIndex2;
1091 UINTN PartitionIndex;
1092 UINTN SectorSum, i, VolNumber = 0;
1093 UINT8 *SectorBuffer1, *SectorBuffer2;
1094 EFI_GUID *UuidList;
1095 EFI_GUID NullUuid = NULL_GUID_VALUE;
1096
1097 MyFreePool(Volumes);
1098 Volumes = NULL;
1099 VolumesCount = 0;
1100 ForgetPartitionTables();
1101
1102 // get all filesystem handles
1103 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
1104 UuidList = AllocateZeroPool(sizeof(EFI_GUID) * HandleCount);
1105 if (Status == EFI_NOT_FOUND) {
1106 return; // no filesystems. strange, but true...
1107 }
1108 if (CheckError(Status, L"while listing all file systems"))
1109 return;
1110
1111 // first pass: collect information about all handles
1112 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1113 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1114 Volume->DeviceHandle = Handles[HandleIndex];
1115 AddPartitionTable(Volume);
1116 ScanVolume(Volume);
1117 if (UuidList) {
1118 UuidList[HandleIndex] = Volume->VolUuid;
1119 for (i = 0; i < HandleIndex; i++) {
1120 if ((CompareMem(&(Volume->VolUuid), &(UuidList[i]), sizeof(EFI_GUID)) == 0) &&
1121 (CompareMem(&(Volume->VolUuid), &NullUuid, sizeof(EFI_GUID)) != 0)) { // Duplicate filesystem UUID
1122 Volume->IsReadable = FALSE;
1123 } // if
1124 } // for
1125 } // if
1126 if (Volume->IsReadable)
1127 Volume->VolNumber = VolNumber++;
1128 else
1129 Volume->VolNumber = VOL_UNREADABLE;
1130
1131 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1132
1133 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
1134 SelfVolume = Volume;
1135 }
1136 MyFreePool(Handles);
1137
1138 if (SelfVolume == NULL)
1139 Print(L"WARNING: SelfVolume not found");
1140
1141 // second pass: relate partitions and whole disk devices
1142 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1143 Volume = Volumes[VolumeIndex];
1144 // check MBR partition table for extended partitions
1145 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1146 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
1147 Volume->MbrPartitionTable != NULL) {
1148 MbrTable = Volume->MbrPartitionTable;
1149 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1150 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
1151 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
1152 }
1153 }
1154 }
1155
1156 // search for corresponding whole disk volume entry
1157 WholeDiskVolume = NULL;
1158 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1159 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1160 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1161 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1162 Volumes[VolumeIndex2]->BlockIOOffset == 0) {
1163 WholeDiskVolume = Volumes[VolumeIndex2];
1164 }
1165 }
1166 }
1167
1168 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1169 // check if this volume is one of the partitions in the table
1170 MbrTable = WholeDiskVolume->MbrPartitionTable;
1171 SectorBuffer1 = AllocatePool(512);
1172 SectorBuffer2 = AllocatePool(512);
1173 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1174 // check size
1175 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1176 continue;
1177
1178 // compare boot sector read through offset vs. directly
1179 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1180 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1181 Volume->BlockIOOffset, 512, SectorBuffer1);
1182 if (EFI_ERROR(Status))
1183 break;
1184 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1185 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1186 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1187 if (EFI_ERROR(Status))
1188 break;
1189 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1190 continue;
1191 SectorSum = 0;
1192 for (i = 0; i < 512; i++)
1193 SectorSum += SectorBuffer1[i];
1194 if (SectorSum < 1000)
1195 continue;
1196
1197 // TODO: mark entry as non-bootable if it is an extended partition
1198
1199 // now we're reasonably sure the association is correct...
1200 Volume->IsMbrPartition = TRUE;
1201 Volume->MbrPartitionIndex = PartitionIndex;
1202 if (Volume->VolName == NULL) {
1203 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1204 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1205 }
1206 break;
1207 }
1208
1209 MyFreePool(SectorBuffer1);
1210 MyFreePool(SectorBuffer2);
1211 }
1212 } // for
1213 } /* VOID ScanVolumes() */
1214
1215 //
1216 // file and dir functions
1217 //
1218
1219 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1220 {
1221 EFI_STATUS Status;
1222 EFI_FILE_HANDLE TestFile;
1223
1224 if (BaseDir != NULL) {
1225 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1226 if (Status == EFI_SUCCESS) {
1227 refit_call1_wrapper(TestFile->Close, TestFile);
1228 return TRUE;
1229 }
1230 }
1231 return FALSE;
1232 }
1233
1234 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1235 {
1236 EFI_STATUS Status;
1237 VOID *Buffer;
1238 UINTN LastBufferSize, BufferSize;
1239 INTN IterCount;
1240
1241 for (;;) {
1242
1243 // free pointer from last call
1244 if (*DirEntry != NULL) {
1245 FreePool(*DirEntry);
1246 *DirEntry = NULL;
1247 }
1248
1249 // read next directory entry
1250 LastBufferSize = BufferSize = 256;
1251 Buffer = AllocatePool(BufferSize);
1252 for (IterCount = 0; ; IterCount++) {
1253 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1254 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1255 break;
1256 if (BufferSize <= LastBufferSize) {
1257 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1258 BufferSize = LastBufferSize * 2;
1259 #if REFIT_DEBUG > 0
1260 } else {
1261 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1262 #endif
1263 }
1264 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1265 LastBufferSize = BufferSize;
1266 }
1267 if (EFI_ERROR(Status)) {
1268 MyFreePool(Buffer);
1269 Buffer = NULL;
1270 break;
1271 }
1272
1273 // check for end of listing
1274 if (BufferSize == 0) { // end of directory listing
1275 MyFreePool(Buffer);
1276 Buffer = NULL;
1277 break;
1278 }
1279
1280 // entry is ready to be returned
1281 *DirEntry = (EFI_FILE_INFO *)Buffer;
1282
1283 // filter results
1284 if (FilterMode == 1) { // only return directories
1285 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1286 break;
1287 } else if (FilterMode == 2) { // only return files
1288 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1289 break;
1290 } else // no filter or unknown filter -> return everything
1291 break;
1292
1293 }
1294 return Status;
1295 }
1296
1297 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1298 {
1299 if (RelativePath == NULL) {
1300 DirIter->LastStatus = EFI_SUCCESS;
1301 DirIter->DirHandle = BaseDir;
1302 DirIter->CloseDirHandle = FALSE;
1303 } else {
1304 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1305 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1306 }
1307 DirIter->LastFileInfo = NULL;
1308 }
1309
1310 #ifndef __MAKEWITH_GNUEFI
1311 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1312
1313 static EFI_STATUS
1314 InitializeUnicodeCollationProtocol (VOID)
1315 {
1316 EFI_STATUS Status;
1317
1318 if (mUnicodeCollation != NULL) {
1319 return EFI_SUCCESS;
1320 }
1321
1322 //
1323 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1324 // instances first and then select one which support English language.
1325 // Current implementation just pick the first instance.
1326 //
1327 Status = gBS->LocateProtocol (
1328 &gEfiUnicodeCollation2ProtocolGuid,
1329 NULL,
1330 (VOID **) &mUnicodeCollation
1331 );
1332 if (EFI_ERROR(Status)) {
1333 Status = gBS->LocateProtocol (
1334 &gEfiUnicodeCollationProtocolGuid,
1335 NULL,
1336 (VOID **) &mUnicodeCollation
1337 );
1338
1339 }
1340 return Status;
1341 }
1342
1343 static BOOLEAN
1344 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1345 {
1346 if (!mUnicodeCollation) {
1347 InitializeUnicodeCollationProtocol();
1348 }
1349 if (mUnicodeCollation)
1350 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1351 return FALSE; // Shouldn't happen
1352 }
1353
1354 #endif
1355
1356 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1357 OUT EFI_FILE_INFO **DirEntry)
1358 {
1359 BOOLEAN KeepGoing = TRUE;
1360 UINTN i;
1361 CHAR16 *OnePattern;
1362
1363 if (DirIter->LastFileInfo != NULL) {
1364 FreePool(DirIter->LastFileInfo);
1365 DirIter->LastFileInfo = NULL;
1366 }
1367
1368 if (EFI_ERROR(DirIter->LastStatus))
1369 return FALSE; // stop iteration
1370
1371 do {
1372 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1373 if (EFI_ERROR(DirIter->LastStatus))
1374 return FALSE;
1375 if (DirIter->LastFileInfo == NULL) // end of listing
1376 return FALSE;
1377 if (FilePattern != NULL) {
1378 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1379 KeepGoing = FALSE;
1380 i = 0;
1381 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1382 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1383 KeepGoing = FALSE;
1384 } // while
1385 // else continue loop
1386 } else
1387 break;
1388 } while (KeepGoing && FilePattern);
1389
1390 *DirEntry = DirIter->LastFileInfo;
1391 return TRUE;
1392 }
1393
1394 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1395 {
1396 if (DirIter->LastFileInfo != NULL) {
1397 FreePool(DirIter->LastFileInfo);
1398 DirIter->LastFileInfo = NULL;
1399 }
1400 if (DirIter->CloseDirHandle)
1401 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1402 return DirIter->LastStatus;
1403 }
1404
1405 //
1406 // file name manipulation
1407 //
1408
1409 // Returns the filename portion (minus path name) of the
1410 // specified file
1411 CHAR16 * Basename(IN CHAR16 *Path)
1412 {
1413 CHAR16 *FileName;
1414 UINTN i;
1415
1416 FileName = Path;
1417
1418 if (Path != NULL) {
1419 for (i = StrLen(Path); i > 0; i--) {
1420 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1421 FileName = Path + i;
1422 break;
1423 }
1424 }
1425 }
1426
1427 return FileName;
1428 }
1429
1430 // Remove the .efi extension from FileName -- for instance, if FileName is
1431 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1432 // returns a copy of the original input.
1433 CHAR16 * StripEfiExtension(IN CHAR16 *FileName) {
1434 UINTN Length;
1435 CHAR16 *Copy = NULL;
1436
1437 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1438 Length = StrLen(Copy);
1439 if ((Length >= 4) && MyStriCmp(&Copy[Length - 4], L".efi")) {
1440 Copy[Length - 4] = 0;
1441 } // if
1442 } // if
1443 return Copy;
1444 } // CHAR16 * StripExtension()
1445
1446 //
1447 // memory string search
1448 //
1449
1450 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1451 {
1452 UINT8 *BufferPtr;
1453 UINTN Offset;
1454
1455 BufferPtr = Buffer;
1456 BufferLength -= SearchStringLength;
1457 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1458 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1459 return (INTN)Offset;
1460 }
1461
1462 return -1;
1463 }
1464
1465 // Takes an input pathname (*Path) and returns the part of the filename from
1466 // the final dot onwards, converted to lowercase. If the filename includes
1467 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1468 // The calling function is responsible for freeing the memory associated with
1469 // the return value.
1470 CHAR16 *FindExtension(IN CHAR16 *Path) {
1471 CHAR16 *Extension;
1472 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1473 INTN i;
1474
1475 Extension = AllocateZeroPool(sizeof(CHAR16));
1476 if (Path) {
1477 i = StrLen(Path);
1478 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1479 if (Path[i] == L'.')
1480 Found = TRUE;
1481 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1482 FoundSlash = TRUE;
1483 if (!Found)
1484 i--;
1485 } // while
1486 if (Found) {
1487 MergeStrings(&Extension, &Path[i], 0);
1488 ToLower(Extension);
1489 } // if (Found)
1490 } // if
1491 return (Extension);
1492 } // CHAR16 *FindExtension()
1493
1494 // Takes an input pathname (*Path) and locates the final directory component
1495 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1496 // function returns the string 'foo'.
1497 // Assumes the pathname is separated with backslashes.
1498 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1499 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1500 CHAR16 *Found = NULL;
1501
1502 if (Path == NULL)
1503 return NULL;
1504
1505 PathLength = StrLen(Path);
1506 // Find start & end of target element
1507 for (i = 0; i < PathLength; i++) {
1508 if (Path[i] == '\\') {
1509 StartOfElement = EndOfElement;
1510 EndOfElement = i;
1511 } // if
1512 } // for
1513 // Extract the target element
1514 if (EndOfElement > 0) {
1515 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1516 StartOfElement++;
1517 } // while
1518 EndOfElement--;
1519 if (EndOfElement >= StartOfElement) {
1520 CopyLength = EndOfElement - StartOfElement + 1;
1521 Found = StrDuplicate(&Path[StartOfElement]);
1522 if (Found != NULL)
1523 Found[CopyLength] = 0;
1524 } // if (EndOfElement >= StartOfElement)
1525 } // if (EndOfElement > 0)
1526 return (Found);
1527 } // CHAR16 *FindLastDirName()
1528
1529 // Returns the directory portion of a pathname. For instance,
1530 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1531 // string 'EFI\foo'. The calling function is responsible for
1532 // freeing the returned string's memory.
1533 CHAR16 *FindPath(IN CHAR16* FullPath) {
1534 UINTN i, LastBackslash = 0;
1535 CHAR16 *PathOnly = NULL;
1536
1537 if (FullPath != NULL) {
1538 for (i = 0; i < StrLen(FullPath); i++) {
1539 if (FullPath[i] == '\\')
1540 LastBackslash = i;
1541 } // for
1542 PathOnly = StrDuplicate(FullPath);
1543 if (PathOnly != NULL)
1544 PathOnly[LastBackslash] = 0;
1545 } // if
1546 return (PathOnly);
1547 }
1548
1549 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1550 // DeviceVolume, and returns that and the filename (*loader).
1551 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1552 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1553 UINTN i = 0;
1554 BOOLEAN Found = FALSE;
1555
1556 MyFreePool(*loader);
1557 MyFreePool(*DeviceVolume);
1558 *DeviceVolume = NULL;
1559 DeviceString = DevicePathToStr(loadpath);
1560 *loader = SplitDeviceString(DeviceString);
1561
1562 while ((i < VolumesCount) && (!Found)) {
1563 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1564 Temp = SplitDeviceString(VolumeDeviceString);
1565 if (MyStriCmp(DeviceString, VolumeDeviceString)) {
1566 Found = TRUE;
1567 *DeviceVolume = Volumes[i];
1568 }
1569 MyFreePool(Temp);
1570 MyFreePool(VolumeDeviceString);
1571 i++;
1572 } // while
1573
1574 MyFreePool(DeviceString);
1575 } // VOID FindVolumeAndFilename()
1576
1577 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1578 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1579 // the filename component in the original *Path variable and the split-off
1580 // volume component in the *VolName variable.
1581 // Returns TRUE if both components are found, FALSE otherwise.
1582 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1583 UINTN i = 0, Length;
1584 CHAR16 *Filename;
1585
1586 if (*Path == NULL)
1587 return FALSE;
1588
1589 if (*VolName != NULL) {
1590 MyFreePool(*VolName);
1591 *VolName = NULL;
1592 }
1593
1594 Length = StrLen(*Path);
1595 while ((i < Length) && ((*Path)[i] != L':')) {
1596 i++;
1597 } // while
1598
1599 if (i < Length) {
1600 Filename = StrDuplicate((*Path) + i + 1);
1601 (*Path)[i] = 0;
1602 *VolName = *Path;
1603 *Path = Filename;
1604 return TRUE;
1605 } else {
1606 return FALSE;
1607 }
1608 } // BOOLEAN SplitVolumeAndFilename()
1609
1610 // Take an input path name, which may include a volume specification and/or
1611 // a path, and return separate volume, path, and file names. For instance,
1612 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1613 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1614 // the returned pointer is NULL. The calling function is responsible for
1615 // freeing the allocated memory.
1616 VOID SplitPathName(CHAR16 *InPath, CHAR16 **VolName, CHAR16 **Path, CHAR16 **Filename) {
1617 CHAR16 *Temp = NULL;
1618
1619 MyFreePool(*VolName);
1620 MyFreePool(*Path);
1621 MyFreePool(*Filename);
1622 *VolName = *Path = *Filename = NULL;
1623 Temp = StrDuplicate(InPath);
1624 SplitVolumeAndFilename(&Temp, VolName); // VolName is NULL or has volume; Temp has rest of path
1625 CleanUpPathNameSlashes(Temp);
1626 *Path = FindPath(Temp); // *Path has path (may be 0-length); Temp unchanged.
1627 *Filename = StrDuplicate(Temp + StrLen(*Path));
1628 CleanUpPathNameSlashes(*Filename);
1629 if (StrLen(*Path) == 0) {
1630 MyFreePool(*Path);
1631 *Path = NULL;
1632 }
1633 if (StrLen(*Filename) == 0) {
1634 MyFreePool(*Filename);
1635 *Filename = NULL;
1636 }
1637 MyFreePool(Temp);
1638 } // VOID SplitPathName()
1639
1640 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1641 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1642 // Filename must *NOT* include a volume or path specification (that's part of
1643 // the Volume variable), but the List elements may. Performs comparison
1644 // case-insensitively.
1645 BOOLEAN FilenameIn(REFIT_VOLUME *Volume, CHAR16 *Directory, CHAR16 *Filename, CHAR16 *List) {
1646 UINTN i = 0;
1647 BOOLEAN Found = FALSE;
1648 CHAR16 *OneElement;
1649 CHAR16 *TargetVolName = NULL, *TargetPath = NULL, *TargetFilename = NULL;
1650
1651 if (Filename && List) {
1652 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1653 Found = TRUE;
1654 SplitPathName(OneElement, &TargetVolName, &TargetPath, &TargetFilename);
1655 VolumeNumberToName(Volume, &TargetVolName);
1656 if (((TargetVolName != NULL) && ((Volume == NULL) || (!MyStriCmp(TargetVolName, Volume->VolName)))) ||
1657 ((TargetPath != NULL) && (!MyStriCmp(TargetPath, Directory))) ||
1658 ((TargetFilename != NULL) && (!MyStriCmp(TargetFilename, Filename)))) {
1659 Found = FALSE;
1660 } // if
1661 MyFreePool(OneElement);
1662 } // while
1663 } // if
1664
1665 MyFreePool(TargetVolName);
1666 MyFreePool(TargetPath);
1667 MyFreePool(TargetFilename);
1668 return Found;
1669 } // BOOLEAN FilenameIn()
1670
1671 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1672 // to this volume number, returns with *VolName changed to the volume name, as
1673 // stored in the Volume data structure.
1674 // Returns TRUE if this substitution was made, FALSE otherwise.
1675 BOOLEAN VolumeNumberToName(REFIT_VOLUME *Volume, CHAR16 **VolName) {
1676 BOOLEAN MadeSubstitution = FALSE;
1677 UINTN VolNum;
1678
1679 if ((VolName == NULL) || (*VolName == NULL))
1680 return FALSE;
1681
1682 if ((StrLen(*VolName) > 2) && (*VolName[0] == L'f') && (*VolName[1] == L's') && (*VolName[2] >= L'0') && (*VolName[2] <= L'9')) {
1683 VolNum = Atoi(*VolName + 2);
1684 if (VolNum == Volume->VolNumber) {
1685 MyFreePool(*VolName);
1686 *VolName = StrDuplicate(Volume->VolName);
1687 MadeSubstitution = TRUE;
1688 } // if
1689 } // if
1690 return MadeSubstitution;
1691 } // BOOLEAN VolumeMatchesNumber()
1692
1693 // Implement FreePool the way it should have been done to begin with, so that
1694 // it doesn't throw an ASSERT message if fed a NULL pointer....
1695 VOID MyFreePool(IN VOID *Pointer) {
1696 if (Pointer != NULL)
1697 FreePool(Pointer);
1698 }
1699
1700 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1701
1702 // Eject all removable media.
1703 // Returns TRUE if any media were ejected, FALSE otherwise.
1704 BOOLEAN EjectMedia(VOID) {
1705 EFI_STATUS Status;
1706 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1707 EFI_HANDLE *Handles, Handle;
1708 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1709
1710 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1711 if (EFI_ERROR(Status) || HandleCount == 0)
1712 return (FALSE); // probably not an Apple system
1713
1714 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1715 Handle = Handles[HandleIndex];
1716 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1717 if (EFI_ERROR(Status))
1718 continue;
1719 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1720 if (!EFI_ERROR(Status))
1721 Ejected++;
1722 }
1723 MyFreePool(Handles);
1724 return (Ejected > 0);
1725 } // VOID EjectMedia()
1726
1727 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
1728 BOOLEAN GuidsAreEqual(EFI_GUID *Guid1, EFI_GUID *Guid2) {
1729 return (CompareMem(Guid1, Guid2, 16) == 0);
1730 } // BOOLEAN GuidsAreEqual()
1731
1732 // Erase linked-list of UINT32 values....
1733 VOID EraseUint32List(UINT32_LIST **TheList) {
1734 UINT32_LIST *NextItem;
1735
1736 while (*TheList) {
1737 NextItem = (*TheList)->Next;
1738 FreePool(*TheList);
1739 *TheList = NextItem;
1740 } // while
1741 } // EraseUin32List()