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