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