]> code.delx.au - refind/blob - refind/lib.c
Version 0.8.5 release.
[refind] / refind / lib.c
1 /*
2 * refind/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012-2015 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), a copy of which must be distributed
41 * with this source code or binaries made from it.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
51 #include "gpt.h"
52
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 case DISK_KIND_NET:
717 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
718 break;
719 } // switch()
720 }
721 } // VOID SetVolumeBadgeIcon()
722
723 // Return a string representing the input size in IEEE-1541 units.
724 // The calling function is responsible for freeing the allocated memory.
725 static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
726 UINT64 SizeInIeee;
727 UINTN Index = 0, NumPrefixes;
728 CHAR16 *Units, *Prefixes = L" KMGTPEZ";
729 CHAR16 *TheValue;
730
731 TheValue = AllocateZeroPool(sizeof(CHAR16) * 256);
732 if (TheValue != NULL) {
733 NumPrefixes = StrLen(Prefixes);
734 SizeInIeee = SizeInBytes;
735 while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
736 Index++;
737 SizeInIeee /= 1024;
738 } // while
739 if (Prefixes[Index] == ' ') {
740 Units = StrDuplicate(L"-byte");
741 } else {
742 Units = StrDuplicate(L" iB");
743 Units[1] = Prefixes[Index];
744 } // if/else
745 SPrint(TheValue, 255, L"%ld%s", SizeInIeee, Units);
746 } // if
747 return TheValue;
748 } // CHAR16 *SizeInIEEEUnits()
749
750 // Return a name for the volume. Ideally this should be the label for the
751 // filesystem it contains, but this function falls back to describing the
752 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
753 // this information can be extracted.
754 // The calling function is responsible for freeing the memory allocated
755 // for the name string.
756 static CHAR16 *GetVolumeName(REFIT_VOLUME *Volume) {
757 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr = NULL;
758 CHAR16 *FoundName = NULL;
759 CHAR16 *SISize, *TypeName;
760
761 if (Volume->RootDir != NULL) {
762 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
763 }
764
765 if ((FileSystemInfoPtr != NULL) && (FileSystemInfoPtr->VolumeLabel != NULL) &&
766 (StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
767 FoundName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
768 }
769
770 // Special case: Old versions of the rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
771 // this so that we can build a new name that includes the size....
772 if ((FoundName != NULL) && (StrCmp(FoundName, L"HFS+ volume") == 0) && (Volume->FSType == FS_TYPE_HFSPLUS)) {
773 MyFreePool(FoundName);
774 FoundName = NULL;
775 } // if rEFInd HFS+ driver suspected
776
777 // If no filesystem name, try to use the partition name....
778 if ((FoundName == NULL) && (Volume->PartName != NULL) && (StrLen(Volume->PartName) > 0) &&
779 !IsIn(Volume->PartName, IGNORE_PARTITION_NAMES)) {
780 FoundName = StrDuplicate(Volume->PartName);
781 } // if use partition name
782
783 // No filesystem or acceptable partition name, so use fs type and size
784 if ((FoundName == NULL) && (FileSystemInfoPtr != NULL)) {
785 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
786 if (FoundName != NULL) {
787 SISize = SizeInIEEEUnits(FileSystemInfoPtr->VolumeSize);
788 SPrint(FoundName, 255, L"%s%s volume", SISize, FSTypeName(Volume->FSType));
789 MyFreePool(SISize);
790 } // if allocated memory OK
791 } // if (FoundName == NULL)
792
793 MyFreePool(FileSystemInfoPtr);
794
795 if (FoundName == NULL) {
796 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
797 if (FoundName != NULL) {
798 TypeName = FSTypeName(Volume->FSType); // NOTE: Don't free TypeName; function returns constant
799 if (StrLen(TypeName) > 0)
800 SPrint(FoundName, 255, L"%s volume", TypeName);
801 else
802 SPrint(FoundName, 255, L"unknown volume");
803 } // if allocated memory OK
804 } // if
805
806 // TODO: Above could be improved/extended, in case filesystem name is not found,
807 // such as:
808 // - use or add disk/partition number (e.g., "(hd0,2)")
809
810 // Desperate fallback name....
811 if (FoundName == NULL) {
812 FoundName = StrDuplicate(L"unknown volume");
813 }
814 return FoundName;
815 } // static CHAR16 *GetVolumeName()
816
817 // Determine the unique GUID of the volume and store it.
818 static VOID SetPartGuidAndName(REFIT_VOLUME *Volume, EFI_DEVICE_PATH_PROTOCOL *DevicePath) {
819 HARDDRIVE_DEVICE_PATH *HdDevicePath;
820
821 if (Volume == NULL)
822 return;
823
824 if ((DevicePath->Type == MEDIA_DEVICE_PATH) && (DevicePath->SubType == MEDIA_HARDDRIVE_DP)) {
825 HdDevicePath = (HARDDRIVE_DEVICE_PATH*) DevicePath;
826 if (HdDevicePath->SignatureType == SIGNATURE_TYPE_GUID) {
827 Volume->PartGuid = *((EFI_GUID*) HdDevicePath->Signature);
828 Volume->PartName = PartNameFromGuid(&(Volume->PartGuid));
829 } // if
830 } // if
831 } // VOID SetPartGuid()
832
833 VOID ScanVolume(REFIT_VOLUME *Volume)
834 {
835 EFI_STATUS Status;
836 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
837 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
838 EFI_HANDLE WholeDiskHandle;
839 UINTN PartialLength;
840 BOOLEAN Bootable;
841
842 // get device path
843 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
844 #if REFIT_DEBUG > 0
845 if (Volume->DevicePath != NULL) {
846 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
847 #if REFIT_DEBUG >= 2
848 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
849 #endif
850 }
851 #endif
852
853 Volume->DiskKind = DISK_KIND_INTERNAL; // default
854
855 // get block i/o
856 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
857 if (EFI_ERROR(Status)) {
858 Volume->BlockIO = NULL;
859 Print(L"Warning: Can't get BlockIO protocol.\n");
860 } else {
861 if (Volume->BlockIO->Media->BlockSize == 2048)
862 Volume->DiskKind = DISK_KIND_OPTICAL;
863 }
864
865 // scan for bootcode and MBR table
866 Bootable = FALSE;
867 ScanVolumeBootcode(Volume, &Bootable);
868
869 // detect device type
870 DevicePath = Volume->DevicePath;
871 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
872 NextDevicePath = NextDevicePathNode(DevicePath);
873
874 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH) {
875 SetPartGuidAndName(Volume, DevicePath);
876 }
877 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
878 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
879 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
880 DevicePathSubType(DevicePath) == MSG_1394_DP ||
881 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
882 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
883 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
884 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
885 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
886 Bootable = TRUE;
887 }
888
889 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
890 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
891 // TODO: also check for Boot Camp GUID
892 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
893 }
894
895 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
896 // make a device path for the whole device
897 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
898 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
899 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
900 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
901
902 // get the handle for that path
903 RemainingDevicePath = DiskDevicePath;
904 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
905 FreePool(DiskDevicePath);
906
907 if (!EFI_ERROR(Status)) {
908 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
909
910 // get the device path for later
911 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
912 if (!EFI_ERROR(Status)) {
913 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
914 }
915
916 // look at the BlockIO protocol
917 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol,
918 (VOID **) &Volume->WholeDiskBlockIO);
919 if (!EFI_ERROR(Status)) {
920
921 // check the media block size
922 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
923 Volume->DiskKind = DISK_KIND_OPTICAL;
924
925 } else {
926 Volume->WholeDiskBlockIO = NULL;
927 //CheckError(Status, L"from HandleProtocol");
928 }
929 } //else
930 // CheckError(Status, L"from LocateDevicePath");
931 }
932
933 DevicePath = NextDevicePath;
934 } // while
935
936 if (!Bootable) {
937 #if REFIT_DEBUG > 0
938 if (Volume->HasBootCode)
939 Print(L" Volume considered non-bootable, but boot code is present\n");
940 #endif
941 Volume->HasBootCode = FALSE;
942 }
943
944 // open the root directory of the volume
945 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
946
947 // Set volume icon based on .VolumeBadge icon or disk kind
948 SetVolumeBadgeIcon(Volume);
949
950 Volume->VolName = GetVolumeName(Volume);
951
952 if (Volume->RootDir == NULL) {
953 Volume->IsReadable = FALSE;
954 return;
955 } else {
956 Volume->IsReadable = TRUE;
957 }
958
959 // get custom volume icons if present
960 if (!Volume->VolIconImage)
961 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", GlobalConfig.IconSizes[ICON_SIZE_BIG]);
962 } // ScanVolume()
963
964 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
965 {
966 EFI_STATUS Status;
967 REFIT_VOLUME *Volume;
968 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
969 UINTN i;
970 UINTN LogicalPartitionIndex = 4;
971 UINT8 SectorBuffer[512];
972 BOOLEAN Bootable;
973 MBR_PARTITION_INFO *EMbrTable;
974
975 ExtBase = MbrEntry->StartLBA;
976
977 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
978 // read current EMBR
979 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
980 WholeDiskVolume->BlockIO,
981 WholeDiskVolume->BlockIO->Media->MediaId,
982 ExtCurrent, 512, SectorBuffer);
983 if (EFI_ERROR(Status))
984 break;
985 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
986 break;
987 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
988
989 // scan logical partitions in this EMBR
990 NextExtCurrent = 0;
991 for (i = 0; i < 4; i++) {
992 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
993 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
994 break;
995 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
996 // set next ExtCurrent
997 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
998 break;
999 } else {
1000
1001 // found a logical partition
1002 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1003 Volume->DiskKind = WholeDiskVolume->DiskKind;
1004 Volume->IsMbrPartition = TRUE;
1005 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
1006 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
1007 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
1008 Volume->BlockIO = WholeDiskVolume->BlockIO;
1009 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
1010 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
1011
1012 Bootable = FALSE;
1013 ScanVolumeBootcode(Volume, &Bootable);
1014 if (!Bootable)
1015 Volume->HasBootCode = FALSE;
1016
1017 SetVolumeBadgeIcon(Volume);
1018
1019 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1020
1021 }
1022 }
1023 }
1024 } /* VOID ScanExtendedPartition() */
1025
1026 VOID ScanVolumes(VOID)
1027 {
1028 EFI_STATUS Status;
1029 EFI_HANDLE *Handles;
1030 REFIT_VOLUME *Volume, *WholeDiskVolume;
1031 MBR_PARTITION_INFO *MbrTable;
1032 UINTN HandleCount = 0;
1033 UINTN HandleIndex;
1034 UINTN VolumeIndex, VolumeIndex2;
1035 UINTN PartitionIndex;
1036 UINTN SectorSum, i, VolNumber = 0;
1037 UINT8 *SectorBuffer1, *SectorBuffer2;
1038 EFI_GUID *UuidList;
1039 EFI_GUID NullUuid = NULL_GUID_VALUE;
1040
1041 MyFreePool(Volumes);
1042 Volumes = NULL;
1043 VolumesCount = 0;
1044 ForgetPartitionTables();
1045
1046 // get all filesystem handles
1047 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
1048 UuidList = AllocateZeroPool(sizeof(EFI_GUID) * HandleCount);
1049 if (Status == EFI_NOT_FOUND) {
1050 return; // no filesystems. strange, but true...
1051 }
1052 if (CheckError(Status, L"while listing all file systems"))
1053 return;
1054
1055 // first pass: collect information about all handles
1056 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1057 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
1058 Volume->DeviceHandle = Handles[HandleIndex];
1059 AddPartitionTable(Volume);
1060 ScanVolume(Volume);
1061 if (UuidList) {
1062 UuidList[HandleIndex] = Volume->VolUuid;
1063 for (i = 0; i < HandleIndex; i++) {
1064 if ((CompareMem(&(Volume->VolUuid), &(UuidList[i]), sizeof(EFI_GUID)) == 0) &&
1065 (CompareMem(&(Volume->VolUuid), &NullUuid, sizeof(EFI_GUID)) != 0)) { // Duplicate filesystem UUID
1066 Volume->IsReadable = FALSE;
1067 } // if
1068 } // for
1069 } // if
1070 if (Volume->IsReadable)
1071 Volume->VolNumber = VolNumber++;
1072 else
1073 Volume->VolNumber = VOL_UNREADABLE;
1074
1075 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
1076
1077 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
1078 SelfVolume = Volume;
1079 }
1080 MyFreePool(Handles);
1081
1082 if (SelfVolume == NULL)
1083 Print(L"WARNING: SelfVolume not found");
1084
1085 // second pass: relate partitions and whole disk devices
1086 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1087 Volume = Volumes[VolumeIndex];
1088 // check MBR partition table for extended partitions
1089 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1090 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
1091 Volume->MbrPartitionTable != NULL) {
1092 MbrTable = Volume->MbrPartitionTable;
1093 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1094 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
1095 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
1096 }
1097 }
1098 }
1099
1100 // search for corresponding whole disk volume entry
1101 WholeDiskVolume = NULL;
1102 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
1103 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1104 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1105 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1106 Volumes[VolumeIndex2]->BlockIOOffset == 0) {
1107 WholeDiskVolume = Volumes[VolumeIndex2];
1108 }
1109 }
1110 }
1111
1112 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1113 // check if this volume is one of the partitions in the table
1114 MbrTable = WholeDiskVolume->MbrPartitionTable;
1115 SectorBuffer1 = AllocatePool(512);
1116 SectorBuffer2 = AllocatePool(512);
1117 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1118 // check size
1119 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1120 continue;
1121
1122 // compare boot sector read through offset vs. directly
1123 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1124 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1125 Volume->BlockIOOffset, 512, SectorBuffer1);
1126 if (EFI_ERROR(Status))
1127 break;
1128 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1129 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1130 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1131 if (EFI_ERROR(Status))
1132 break;
1133 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1134 continue;
1135 SectorSum = 0;
1136 for (i = 0; i < 512; i++)
1137 SectorSum += SectorBuffer1[i];
1138 if (SectorSum < 1000)
1139 continue;
1140
1141 // TODO: mark entry as non-bootable if it is an extended partition
1142
1143 // now we're reasonably sure the association is correct...
1144 Volume->IsMbrPartition = TRUE;
1145 Volume->MbrPartitionIndex = PartitionIndex;
1146 if (Volume->VolName == NULL) {
1147 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1148 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1149 }
1150 break;
1151 }
1152
1153 MyFreePool(SectorBuffer1);
1154 MyFreePool(SectorBuffer2);
1155 }
1156 } // for
1157 } /* VOID ScanVolumes() */
1158
1159 static VOID UninitVolumes(VOID)
1160 {
1161 REFIT_VOLUME *Volume;
1162 UINTN VolumeIndex;
1163
1164 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1165 Volume = Volumes[VolumeIndex];
1166
1167 if (Volume->RootDir != NULL) {
1168 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
1169 Volume->RootDir = NULL;
1170 }
1171
1172 Volume->DeviceHandle = NULL;
1173 Volume->BlockIO = NULL;
1174 Volume->WholeDiskBlockIO = NULL;
1175 }
1176 }
1177
1178 VOID ReinitVolumes(VOID)
1179 {
1180 EFI_STATUS Status;
1181 REFIT_VOLUME *Volume;
1182 UINTN VolumeIndex;
1183 EFI_DEVICE_PATH *RemainingDevicePath;
1184 EFI_HANDLE DeviceHandle, WholeDiskHandle;
1185
1186 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1187 Volume = Volumes[VolumeIndex];
1188
1189 if (Volume->DevicePath != NULL) {
1190 // get the handle for that path
1191 RemainingDevicePath = Volume->DevicePath;
1192 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
1193
1194 if (!EFI_ERROR(Status)) {
1195 Volume->DeviceHandle = DeviceHandle;
1196
1197 // get the root directory
1198 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1199
1200 } else
1201 CheckError(Status, L"from LocateDevicePath");
1202 }
1203
1204 if (Volume->WholeDiskDevicePath != NULL) {
1205 // get the handle for that path
1206 RemainingDevicePath = Volume->WholeDiskDevicePath;
1207 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
1208
1209 if (!EFI_ERROR(Status)) {
1210 // get the BlockIO protocol
1211 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol,
1212 (VOID **) &Volume->WholeDiskBlockIO);
1213 if (EFI_ERROR(Status)) {
1214 Volume->WholeDiskBlockIO = NULL;
1215 CheckError(Status, L"from HandleProtocol");
1216 }
1217 } else
1218 CheckError(Status, L"from LocateDevicePath");
1219 }
1220 }
1221 }
1222
1223 //
1224 // file and dir functions
1225 //
1226
1227 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1228 {
1229 EFI_STATUS Status;
1230 EFI_FILE_HANDLE TestFile;
1231
1232 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1233 if (Status == EFI_SUCCESS) {
1234 refit_call1_wrapper(TestFile->Close, TestFile);
1235 return TRUE;
1236 }
1237 return FALSE;
1238 }
1239
1240 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1241 {
1242 EFI_STATUS Status;
1243 VOID *Buffer;
1244 UINTN LastBufferSize, BufferSize;
1245 INTN IterCount;
1246
1247 for (;;) {
1248
1249 // free pointer from last call
1250 if (*DirEntry != NULL) {
1251 FreePool(*DirEntry);
1252 *DirEntry = NULL;
1253 }
1254
1255 // read next directory entry
1256 LastBufferSize = BufferSize = 256;
1257 Buffer = AllocatePool(BufferSize);
1258 for (IterCount = 0; ; IterCount++) {
1259 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1260 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1261 break;
1262 if (BufferSize <= LastBufferSize) {
1263 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1264 BufferSize = LastBufferSize * 2;
1265 #if REFIT_DEBUG > 0
1266 } else {
1267 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1268 #endif
1269 }
1270 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1271 LastBufferSize = BufferSize;
1272 }
1273 if (EFI_ERROR(Status)) {
1274 MyFreePool(Buffer);
1275 Buffer = NULL;
1276 break;
1277 }
1278
1279 // check for end of listing
1280 if (BufferSize == 0) { // end of directory listing
1281 MyFreePool(Buffer);
1282 Buffer = NULL;
1283 break;
1284 }
1285
1286 // entry is ready to be returned
1287 *DirEntry = (EFI_FILE_INFO *)Buffer;
1288
1289 // filter results
1290 if (FilterMode == 1) { // only return directories
1291 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1292 break;
1293 } else if (FilterMode == 2) { // only return files
1294 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1295 break;
1296 } else // no filter or unknown filter -> return everything
1297 break;
1298
1299 }
1300 return Status;
1301 }
1302
1303 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1304 {
1305 if (RelativePath == NULL) {
1306 DirIter->LastStatus = EFI_SUCCESS;
1307 DirIter->DirHandle = BaseDir;
1308 DirIter->CloseDirHandle = FALSE;
1309 } else {
1310 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1311 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1312 }
1313 DirIter->LastFileInfo = NULL;
1314 }
1315
1316 #ifndef __MAKEWITH_GNUEFI
1317 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1318
1319 static EFI_STATUS
1320 InitializeUnicodeCollationProtocol (VOID)
1321 {
1322 EFI_STATUS Status;
1323
1324 if (mUnicodeCollation != NULL) {
1325 return EFI_SUCCESS;
1326 }
1327
1328 //
1329 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1330 // instances first and then select one which support English language.
1331 // Current implementation just pick the first instance.
1332 //
1333 Status = gBS->LocateProtocol (
1334 &gEfiUnicodeCollation2ProtocolGuid,
1335 NULL,
1336 (VOID **) &mUnicodeCollation
1337 );
1338 if (EFI_ERROR(Status)) {
1339 Status = gBS->LocateProtocol (
1340 &gEfiUnicodeCollationProtocolGuid,
1341 NULL,
1342 (VOID **) &mUnicodeCollation
1343 );
1344
1345 }
1346 return Status;
1347 }
1348
1349 static BOOLEAN
1350 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1351 {
1352 if (!mUnicodeCollation) {
1353 InitializeUnicodeCollationProtocol();
1354 }
1355 if (mUnicodeCollation)
1356 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1357 return FALSE; // Shouldn't happen
1358 }
1359
1360 static VOID StrLwr (IN OUT CHAR16 *Str) {
1361 if (!mUnicodeCollation) {
1362 InitializeUnicodeCollationProtocol();
1363 }
1364 if (mUnicodeCollation)
1365 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1366 }
1367
1368 #endif
1369
1370 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1371 OUT EFI_FILE_INFO **DirEntry)
1372 {
1373 BOOLEAN KeepGoing = TRUE;
1374 UINTN i;
1375 CHAR16 *OnePattern;
1376
1377 if (DirIter->LastFileInfo != NULL) {
1378 FreePool(DirIter->LastFileInfo);
1379 DirIter->LastFileInfo = NULL;
1380 }
1381
1382 if (EFI_ERROR(DirIter->LastStatus))
1383 return FALSE; // stop iteration
1384
1385 do {
1386 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1387 if (EFI_ERROR(DirIter->LastStatus))
1388 return FALSE;
1389 if (DirIter->LastFileInfo == NULL) // end of listing
1390 return FALSE;
1391 if (FilePattern != NULL) {
1392 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1393 KeepGoing = FALSE;
1394 i = 0;
1395 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1396 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1397 KeepGoing = FALSE;
1398 } // while
1399 // else continue loop
1400 } else
1401 break;
1402 } while (KeepGoing && FilePattern);
1403
1404 *DirEntry = DirIter->LastFileInfo;
1405 return TRUE;
1406 }
1407
1408 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1409 {
1410 if (DirIter->LastFileInfo != NULL) {
1411 FreePool(DirIter->LastFileInfo);
1412 DirIter->LastFileInfo = NULL;
1413 }
1414 if (DirIter->CloseDirHandle)
1415 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1416 return DirIter->LastStatus;
1417 }
1418
1419 //
1420 // file name manipulation
1421 //
1422
1423 // Returns the filename portion (minus path name) of the
1424 // specified file
1425 CHAR16 * Basename(IN CHAR16 *Path)
1426 {
1427 CHAR16 *FileName;
1428 UINTN i;
1429
1430 FileName = Path;
1431
1432 if (Path != NULL) {
1433 for (i = StrLen(Path); i > 0; i--) {
1434 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1435 FileName = Path + i;
1436 break;
1437 }
1438 }
1439 }
1440
1441 return FileName;
1442 }
1443
1444 // Remove the .efi extension from FileName -- for instance, if FileName is
1445 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1446 // returns a copy of the original input.
1447 CHAR16 * StripEfiExtension(CHAR16 *FileName) {
1448 UINTN Length;
1449 CHAR16 *Copy = NULL;
1450
1451 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1452 Length = StrLen(Copy);
1453 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1454 if ((Length >= 4) && ((StriCmp(&Copy[Length - 4], L".efi") == 0) || (StriCmp(&Copy[Length - 4], L".EFI") == 0))) {
1455 Copy[Length - 4] = 0;
1456 } // if
1457 } // if
1458 return Copy;
1459 } // CHAR16 * StripExtension()
1460
1461 //
1462 // memory string search
1463 //
1464
1465 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1466 {
1467 UINT8 *BufferPtr;
1468 UINTN Offset;
1469
1470 BufferPtr = Buffer;
1471 BufferLength -= SearchStringLength;
1472 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1473 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1474 return (INTN)Offset;
1475 }
1476
1477 return -1;
1478 }
1479
1480 // Performs a case-insensitive search of BigStr for SmallStr.
1481 // Returns TRUE if found, FALSE if not.
1482 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1483 CHAR16 *SmallCopy, *BigCopy;
1484 BOOLEAN Found = FALSE;
1485 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1486
1487 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1488 SmallCopy = StrDuplicate(SmallStr);
1489 BigCopy = StrDuplicate(BigStr);
1490 StrLwr(SmallCopy);
1491 StrLwr(BigCopy);
1492 SmallLen = StrLen(SmallCopy);
1493 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1494 while ((!Found) && (StartPoint < NumCompares)) {
1495 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1496 } // while
1497 MyFreePool(SmallCopy);
1498 MyFreePool(BigCopy);
1499 } // if
1500
1501 return (Found);
1502 } // BOOLEAN StriSubCmp()
1503
1504 // Merges two strings, creating a new one and returning a pointer to it.
1505 // If AddChar != 0, the specified character is placed between the two original
1506 // strings (unless the first string is NULL or empty). The original input
1507 // string *First is de-allocated and replaced by the new merged string.
1508 // This is similar to StrCat, but safer and more flexible because
1509 // MergeStrings allocates memory that's the correct size for the
1510 // new merged string, so it can take a NULL *First and it cleans
1511 // up the old memory. It should *NOT* be used with a constant
1512 // *First, though....
1513 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1514 UINTN Length1 = 0, Length2 = 0;
1515 CHAR16* NewString;
1516
1517 if (*First != NULL)
1518 Length1 = StrLen(*First);
1519 if (Second != NULL)
1520 Length2 = StrLen(Second);
1521 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1522 if (NewString != NULL) {
1523 if ((*First != NULL) && (StrLen(*First) == 0)) {
1524 MyFreePool(*First);
1525 *First = NULL;
1526 }
1527 NewString[0] = L'\0';
1528 if (*First != NULL) {
1529 StrCat(NewString, *First);
1530 if (AddChar) {
1531 NewString[Length1] = AddChar;
1532 NewString[Length1 + 1] = '\0';
1533 } // if (AddChar)
1534 } // if (*First != NULL)
1535 if (Second != NULL)
1536 StrCat(NewString, Second);
1537 MyFreePool(*First);
1538 *First = NewString;
1539 } else {
1540 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1541 } // if/else
1542 } // static CHAR16* MergeStrings()
1543
1544 // Takes an input pathname (*Path) and returns the part of the filename from
1545 // the final dot onwards, converted to lowercase. If the filename includes
1546 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1547 // The calling function is responsible for freeing the memory associated with
1548 // the return value.
1549 CHAR16 *FindExtension(IN CHAR16 *Path) {
1550 CHAR16 *Extension;
1551 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1552 INTN i;
1553
1554 Extension = AllocateZeroPool(sizeof(CHAR16));
1555 if (Path) {
1556 i = StrLen(Path);
1557 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1558 if (Path[i] == L'.')
1559 Found = TRUE;
1560 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1561 FoundSlash = TRUE;
1562 if (!Found)
1563 i--;
1564 } // while
1565 if (Found) {
1566 MergeStrings(&Extension, &Path[i], 0);
1567 StrLwr(Extension);
1568 } // if (Found)
1569 } // if
1570 return (Extension);
1571 } // CHAR16 *FindExtension
1572
1573 // Takes an input pathname (*Path) and locates the final directory component
1574 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1575 // function returns the string 'foo'.
1576 // Assumes the pathname is separated with backslashes.
1577 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1578 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1579 CHAR16 *Found = NULL;
1580
1581 if (Path == NULL)
1582 return NULL;
1583
1584 PathLength = StrLen(Path);
1585 // Find start & end of target element
1586 for (i = 0; i < PathLength; i++) {
1587 if (Path[i] == '\\') {
1588 StartOfElement = EndOfElement;
1589 EndOfElement = i;
1590 } // if
1591 } // for
1592 // Extract the target element
1593 if (EndOfElement > 0) {
1594 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1595 StartOfElement++;
1596 } // while
1597 EndOfElement--;
1598 if (EndOfElement >= StartOfElement) {
1599 CopyLength = EndOfElement - StartOfElement + 1;
1600 Found = StrDuplicate(&Path[StartOfElement]);
1601 if (Found != NULL)
1602 Found[CopyLength] = 0;
1603 } // if (EndOfElement >= StartOfElement)
1604 } // if (EndOfElement > 0)
1605 return (Found);
1606 } // CHAR16 *FindLastDirName
1607
1608 // Returns the directory portion of a pathname. For instance,
1609 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1610 // string 'EFI\foo'. The calling function is responsible for
1611 // freeing the returned string's memory.
1612 CHAR16 *FindPath(IN CHAR16* FullPath) {
1613 UINTN i, LastBackslash = 0;
1614 CHAR16 *PathOnly = NULL;
1615
1616 if (FullPath != NULL) {
1617 for (i = 0; i < StrLen(FullPath); i++) {
1618 if (FullPath[i] == '\\')
1619 LastBackslash = i;
1620 } // for
1621 PathOnly = StrDuplicate(FullPath);
1622 if (PathOnly != NULL)
1623 PathOnly[LastBackslash] = 0;
1624 } // if
1625 return (PathOnly);
1626 }
1627
1628 /*++
1629 *
1630 * Routine Description:
1631 *
1632 * Find a substring.
1633 *
1634 * Arguments:
1635 *
1636 * String - Null-terminated string to search.
1637 * StrCharSet - Null-terminated string to search for.
1638 *
1639 * Returns:
1640 * The address of the first occurrence of the matching substring if successful, or NULL otherwise.
1641 * --*/
1642 CHAR16* MyStrStr (CHAR16 *String, CHAR16 *StrCharSet)
1643 {
1644 CHAR16 *Src;
1645 CHAR16 *Sub;
1646
1647 if ((String == NULL) || (StrCharSet == NULL))
1648 return NULL;
1649
1650 Src = String;
1651 Sub = StrCharSet;
1652
1653 while ((*String != L'\0') && (*StrCharSet != L'\0')) {
1654 if (*String++ != *StrCharSet) {
1655 String = ++Src;
1656 StrCharSet = Sub;
1657 } else {
1658 StrCharSet++;
1659 }
1660 }
1661 if (*StrCharSet == L'\0') {
1662 return Src;
1663 } else {
1664 return NULL;
1665 }
1666 } // CHAR16 *MyStrStr()
1667
1668 // Restrict TheString to at most Limit characters.
1669 // Does this in two ways:
1670 // - Locates stretches of two or more spaces and compresses
1671 // them down to one space.
1672 // - Truncates TheString
1673 // Returns TRUE if changes were made, FALSE otherwise
1674 BOOLEAN LimitStringLength(CHAR16 *TheString, UINTN Limit) {
1675 CHAR16 *SubString, *TempString;
1676 UINTN i;
1677 BOOLEAN HasChanged = FALSE;
1678
1679 // SubString will be NULL or point WITHIN TheString
1680 SubString = MyStrStr(TheString, L" ");
1681 while (SubString != NULL) {
1682 i = 0;
1683 while (SubString[i] == L' ')
1684 i++;
1685 if (i >= StrLen(SubString)) {
1686 SubString[0] = '\0';
1687 HasChanged = TRUE;
1688 } else {
1689 TempString = StrDuplicate(&SubString[i]);
1690 if (TempString != NULL) {
1691 StrCpy(&SubString[1], TempString);
1692 MyFreePool(TempString);
1693 HasChanged = TRUE;
1694 } else {
1695 // memory allocation problem; abort to avoid potentially infinite loop!
1696 break;
1697 } // if/else
1698 } // if/else
1699 SubString = MyStrStr(TheString, L" ");
1700 } // while
1701
1702 // If the string is still too long, truncate it....
1703 if (StrLen(TheString) > Limit) {
1704 TheString[Limit] = '\0';
1705 HasChanged = TRUE;
1706 } // if
1707
1708 return HasChanged;
1709 } // BOOLEAN LimitStringLength()
1710
1711 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1712 // DeviceVolume, and returns that and the filename (*loader).
1713 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1714 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1715 UINTN i = 0;
1716 BOOLEAN Found = FALSE;
1717
1718 MyFreePool(*loader);
1719 MyFreePool(*DeviceVolume);
1720 *DeviceVolume = NULL;
1721 DeviceString = DevicePathToStr(loadpath);
1722 *loader = SplitDeviceString(DeviceString);
1723
1724 while ((i < VolumesCount) && (!Found)) {
1725 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1726 Temp = SplitDeviceString(VolumeDeviceString);
1727 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1728 Found = TRUE;
1729 *DeviceVolume = Volumes[i];
1730 }
1731 MyFreePool(Temp);
1732 MyFreePool(VolumeDeviceString);
1733 i++;
1734 } // while
1735
1736 MyFreePool(DeviceString);
1737 } // VOID FindVolumeAndFilename()
1738
1739 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1740 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1741 // the filename component in the original *Path variable and the split-off
1742 // volume component in the *VolName variable.
1743 // Returns TRUE if both components are found, FALSE otherwise.
1744 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1745 UINTN i = 0, Length;
1746 CHAR16 *Filename;
1747
1748 if (*Path == NULL)
1749 return FALSE;
1750
1751 if (*VolName != NULL) {
1752 MyFreePool(*VolName);
1753 *VolName = NULL;
1754 }
1755
1756 Length = StrLen(*Path);
1757 while ((i < Length) && ((*Path)[i] != L':')) {
1758 i++;
1759 } // while
1760
1761 if (i < Length) {
1762 Filename = StrDuplicate((*Path) + i + 1);
1763 (*Path)[i] = 0;
1764 *VolName = *Path;
1765 *Path = Filename;
1766 return TRUE;
1767 } else {
1768 return FALSE;
1769 }
1770 } // BOOLEAN SplitVolumeAndFilename()
1771
1772 // Returns all the digits in the input string, including intervening
1773 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1774 // this function returns "3.3.4-7". If InString contains no digits,
1775 // the return value is NULL.
1776 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1777 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1778 CHAR16 *Found = NULL;
1779
1780 if (InString == NULL)
1781 return NULL;
1782
1783 InLength = StartOfElement = StrLen(InString);
1784 // Find start & end of target element
1785 for (i = 0; i < InLength; i++) {
1786 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1787 if (StartOfElement > i)
1788 StartOfElement = i;
1789 if (EndOfElement < i)
1790 EndOfElement = i;
1791 } // if
1792 } // for
1793 // Extract the target element
1794 if (EndOfElement > 0) {
1795 if (EndOfElement >= StartOfElement) {
1796 CopyLength = EndOfElement - StartOfElement + 1;
1797 Found = StrDuplicate(&InString[StartOfElement]);
1798 if (Found != NULL)
1799 Found[CopyLength] = 0;
1800 } // if (EndOfElement >= StartOfElement)
1801 } // if (EndOfElement > 0)
1802 return (Found);
1803 } // CHAR16 *FindNumbers()
1804
1805 // Find the #Index element (numbered from 0) in a comma-delimited string
1806 // of elements.
1807 // Returns the found element, or NULL if Index is out of range or InString
1808 // is NULL. Note that the calling function is responsible for freeing the
1809 // memory associated with the returned string pointer.
1810 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1811 UINTN StartPos = 0, CurPos = 0;
1812 BOOLEAN Found = FALSE;
1813 CHAR16 *FoundString = NULL;
1814
1815 if (InString != NULL) {
1816 // After while() loop, StartPos marks start of item #Index
1817 while ((Index > 0) && (CurPos < StrLen(InString))) {
1818 if (InString[CurPos] == L',') {
1819 Index--;
1820 StartPos = CurPos + 1;
1821 } // if
1822 CurPos++;
1823 } // while
1824 // After while() loop, CurPos is one past the end of the element
1825 while ((CurPos < StrLen(InString)) && (!Found)) {
1826 if (InString[CurPos] == L',')
1827 Found = TRUE;
1828 else
1829 CurPos++;
1830 } // while
1831 if (Index == 0)
1832 FoundString = StrDuplicate(&InString[StartPos]);
1833 if (FoundString != NULL)
1834 FoundString[CurPos - StartPos] = 0;
1835 } // if
1836 return (FoundString);
1837 } // CHAR16 *FindCommaDelimited()
1838
1839 // Return the position of SmallString within BigString, or -1 if
1840 // not found.
1841 INTN FindSubString(IN CHAR16 *SmallString, IN CHAR16 *BigString) {
1842 INTN Position = -1;
1843 UINTN i = 0, SmallSize, BigSize;
1844 BOOLEAN Found = FALSE;
1845
1846 if ((SmallString == NULL) || (BigString == NULL))
1847 return -1;
1848
1849 SmallSize = StrLen(SmallString);
1850 BigSize = StrLen(BigString);
1851 if ((SmallSize > BigSize) || (SmallSize == 0) || (BigSize == 0))
1852 return -1;
1853
1854 while ((i <= (BigSize - SmallSize) && !Found)) {
1855 if (CompareMem(BigString + i, SmallString, SmallSize) == 0) {
1856 Found = TRUE;
1857 Position = i;
1858 } // if
1859 i++;
1860 } // while()
1861 return Position;
1862 } // INTN FindSubString()
1863
1864 // Take an input path name, which may include a volume specification and/or
1865 // a path, and return separate volume, path, and file names. For instance,
1866 // "BIGVOL:\EFI\ubuntu\grubx64.efi" will return a VolName of "BIGVOL", a Path
1867 // of "EFI\ubuntu", and a Filename of "grubx64.efi". If an element is missing,
1868 // the returned pointer is NULL. The calling function is responsible for
1869 // freeing the allocated memory.
1870 VOID SplitPathName(CHAR16 *InPath, CHAR16 **VolName, CHAR16 **Path, CHAR16 **Filename) {
1871 CHAR16 *Temp = NULL;
1872
1873 MyFreePool(*VolName);
1874 MyFreePool(*Path);
1875 MyFreePool(*Filename);
1876 *VolName = *Path = *Filename = NULL;
1877 Temp = StrDuplicate(InPath);
1878 SplitVolumeAndFilename(&Temp, VolName); // VolName is NULL or has volume; Temp has rest of path
1879 CleanUpPathNameSlashes(Temp);
1880 *Path = FindPath(Temp); // *Path has path (may be 0-length); Temp unchanged.
1881 *Filename = StrDuplicate(Temp + StrLen(*Path));
1882 CleanUpPathNameSlashes(*Filename);
1883 if (StrLen(*Path) == 0) {
1884 MyFreePool(*Path);
1885 *Path = NULL;
1886 }
1887 if (StrLen(*Filename) == 0) {
1888 MyFreePool(*Filename);
1889 *Filename = NULL;
1890 }
1891 MyFreePool(Temp);
1892 } // VOID SplitPathName
1893
1894 // Returns TRUE if SmallString is an element in the comma-delimited List,
1895 // FALSE otherwise. Performs comparison case-insensitively (except on
1896 // buggy EFIs with case-sensitive StriCmp() functions).
1897 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1898 UINTN i = 0;
1899 BOOLEAN Found = FALSE;
1900 CHAR16 *OneElement;
1901
1902 if (SmallString && List) {
1903 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1904 if (StriCmp(OneElement, SmallString) == 0)
1905 Found = TRUE;
1906 } // while
1907 } // if
1908 return Found;
1909 } // BOOLEAN IsIn()
1910
1911 // Returns TRUE if any element of List can be found as a substring of
1912 // BigString, FALSE otherwise. Performs comparisons case-insensitively.
1913 BOOLEAN IsInSubstring(IN CHAR16 *BigString, IN CHAR16 *List) {
1914 UINTN i = 0, ElementLength;
1915 BOOLEAN Found = FALSE;
1916 CHAR16 *OneElement;
1917
1918 if (BigString && List) {
1919 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1920 ElementLength = StrLen(OneElement);
1921 if ((ElementLength <= StrLen(BigString)) && (StriSubCmp(OneElement, BigString)))
1922 Found = TRUE;
1923 } // while
1924 } // if
1925 return Found;
1926 } // BOOLEAN IsSubstringIn()
1927
1928 // Returns TRUE if specified Volume, Directory, and Filename correspond to an
1929 // element in the comma-delimited List, FALSE otherwise. Note that Directory and
1930 // Filename must *NOT* include a volume or path specification (that's part of
1931 // the Volume variable), but the List elements may. Performs comparison
1932 // case-insensitively (except on buggy EFIs with case-sensitive StriCmp()
1933 // functions).
1934 BOOLEAN FilenameIn(REFIT_VOLUME *Volume, CHAR16 *Directory, CHAR16 *Filename, CHAR16 *List) {
1935 UINTN i = 0;
1936 BOOLEAN Found = FALSE;
1937 CHAR16 *OneElement;
1938 CHAR16 *TargetVolName = NULL, *TargetPath = NULL, *TargetFilename = NULL;
1939
1940 if (Filename && List) {
1941 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1942 Found = TRUE;
1943 SplitPathName(OneElement, &TargetVolName, &TargetPath, &TargetFilename);
1944 VolumeNumberToName(Volume, &TargetVolName);
1945 if (((TargetVolName != NULL) && ((Volume == NULL) || (StriCmp(TargetVolName, Volume->VolName) != 0))) ||
1946 ((TargetPath != NULL) && (StriCmp(TargetPath, Directory) != 0)) ||
1947 ((TargetFilename != NULL) && (StriCmp(TargetFilename, Filename) != 0))) {
1948 Found = FALSE;
1949 } // if
1950 MyFreePool(OneElement);
1951 } // while
1952 } // if
1953
1954 MyFreePool(TargetVolName);
1955 MyFreePool(TargetPath);
1956 MyFreePool(TargetFilename);
1957 return Found;
1958 } // BOOLEAN FilenameIn()
1959
1960 // If *VolName is of the form "fs#", where "#" is a number, and if Volume points
1961 // to this volume number, returns with *VolName changed to the volume name, as
1962 // stored in the Volume data structure.
1963 // Returns TRUE if this substitution was made, FALSE otherwise.
1964 BOOLEAN VolumeNumberToName(REFIT_VOLUME *Volume, CHAR16 **VolName) {
1965 BOOLEAN MadeSubstitution = FALSE;
1966 UINTN VolNum;
1967
1968 if ((VolName == NULL) || (*VolName == NULL))
1969 return FALSE;
1970
1971 if ((StrLen(*VolName) > 2) && (*VolName[0] == L'f') && (*VolName[1] == L's') && (*VolName[2] >= L'0') && (*VolName[2] <= L'9')) {
1972 VolNum = Atoi(*VolName + 2);
1973 if (VolNum == Volume->VolNumber) {
1974 MyFreePool(*VolName);
1975 *VolName = StrDuplicate(Volume->VolName);
1976 MadeSubstitution = TRUE;
1977 } // if
1978 } // if
1979 return MadeSubstitution;
1980 } // BOOLEAN VolumeMatchesNumber()
1981
1982 // Implement FreePool the way it should have been done to begin with, so that
1983 // it doesn't throw an ASSERT message if fed a NULL pointer....
1984 VOID MyFreePool(IN VOID *Pointer) {
1985 if (Pointer != NULL)
1986 FreePool(Pointer);
1987 }
1988
1989 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1990
1991 // Eject all removable media.
1992 // Returns TRUE if any media were ejected, FALSE otherwise.
1993 BOOLEAN EjectMedia(VOID) {
1994 EFI_STATUS Status;
1995 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1996 EFI_HANDLE *Handles, Handle;
1997 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1998
1999 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
2000 if (EFI_ERROR(Status) || HandleCount == 0)
2001 return (FALSE); // probably not an Apple system
2002
2003 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
2004 Handle = Handles[HandleIndex];
2005 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
2006 if (EFI_ERROR(Status))
2007 continue;
2008 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
2009 if (!EFI_ERROR(Status))
2010 Ejected++;
2011 }
2012 MyFreePool(Handles);
2013 return (Ejected > 0);
2014 } // VOID EjectMedia()
2015
2016 // Converts consecutive characters in the input string into a
2017 // number, interpreting the string as a hexadecimal number, starting
2018 // at the specified position and continuing for the specified number
2019 // of characters or until the end of the string, whichever is first.
2020 // NumChars must be between 1 and 16. Ignores invalid characters.
2021 UINT64 StrToHex(CHAR16 *Input, UINTN Pos, UINTN NumChars) {
2022 UINT64 retval = 0x00;
2023 UINTN NumDone = 0;
2024 CHAR16 a;
2025
2026 if ((Input == NULL) || (StrLen(Input) < Pos) || (NumChars == 0) || (NumChars > 16)) {
2027 return 0;
2028 }
2029
2030 while ((StrLen(Input) >= Pos) && (NumDone < NumChars)) {
2031 a = Input[Pos];
2032 if ((a >= '0') && (a <= '9')) {
2033 retval *= 0x10;
2034 retval += (a - '0');
2035 NumDone++;
2036 }
2037 if ((a >= 'a') && (a <= 'f')) {
2038 retval *= 0x10;
2039 retval += (a - 'a' + 0x0a);
2040 NumDone++;
2041 }
2042 if ((a >= 'A') && (a <= 'F')) {
2043 retval *= 0x10;
2044 retval += (a - 'A' + 0x0a);
2045 NumDone++;
2046 }
2047 Pos++;
2048 } // while()
2049 return retval;
2050 } // StrToHex()
2051
2052 // Returns TRUE if UnknownString can be interpreted as a GUID, FALSE otherwise.
2053 // Note that the input string must have no extraneous spaces and must be
2054 // conventionally formatted as a 36-character GUID, complete with dashes in
2055 // appropriate places.
2056 BOOLEAN IsGuid(CHAR16 *UnknownString) {
2057 UINTN Length, i;
2058 BOOLEAN retval = TRUE;
2059 CHAR16 a;
2060
2061 if (UnknownString == NULL)
2062 return FALSE;
2063
2064 Length = StrLen(UnknownString);
2065 if (Length != 36)
2066 return FALSE;
2067
2068 for (i = 0; i < Length; i++) {
2069 a = UnknownString[i];
2070 if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) {
2071 if (a != '-')
2072 retval = FALSE;
2073 } else if (((a < 'a') || (a > 'f')) && ((a < 'A') || (a > 'F')) && ((a < '0') && (a > '9'))) {
2074 retval = FALSE;
2075 } // if/else if
2076 } // for
2077 return retval;
2078 } // BOOLEAN IsGuid()
2079
2080 // Return the GUID as a string, suitable for display to the user. Note that the calling
2081 // function is responsible for freeing the allocated memory.
2082 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
2083 CHAR16 *TheString;
2084
2085 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
2086 if (TheString != 0) {
2087 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2088 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
2089 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
2090 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
2091 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
2092 }
2093 return TheString;
2094 } // GuidAsString(EFI_GUID *GuidData)
2095
2096 EFI_GUID StringAsGuid(CHAR16 * InString) {
2097 EFI_GUID Guid = NULL_GUID_VALUE;
2098
2099 if (!IsGuid(InString)) {
2100 return Guid;
2101 }
2102
2103 Guid.Data1 = (UINT32) StrToHex(InString, 0, 8);
2104 Guid.Data2 = (UINT16) StrToHex(InString, 9, 4);
2105 Guid.Data3 = (UINT16) StrToHex(InString, 14, 4);
2106 Guid.Data4[0] = (UINT8) StrToHex(InString, 19, 2);
2107 Guid.Data4[1] = (UINT8) StrToHex(InString, 21, 2);
2108 Guid.Data4[2] = (UINT8) StrToHex(InString, 23, 2);
2109 Guid.Data4[3] = (UINT8) StrToHex(InString, 26, 2);
2110 Guid.Data4[4] = (UINT8) StrToHex(InString, 28, 2);
2111 Guid.Data4[5] = (UINT8) StrToHex(InString, 30, 2);
2112 Guid.Data4[6] = (UINT8) StrToHex(InString, 32, 2);
2113 Guid.Data4[7] = (UINT8) StrToHex(InString, 34, 2);
2114
2115 return Guid;
2116 } // EFI_GUID StringAsGuid()
2117
2118 // Returns TRUE if the two GUIDs are equal, FALSE otherwise
2119 BOOLEAN GuidsAreEqual(EFI_GUID *Guid1, EFI_GUID *Guid2) {
2120 return (CompareMem(Guid1, Guid2, 16) == 0);
2121 } // BOOLEAN CompareGuids()
2122