]> code.delx.au - refind/blob - refind/lib.c
Refinements, mostly to shim/MOK support.
[refind] / refind / lib.c
1 /*
2 * refit/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 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
52 #ifdef __MAKEWITH_GNUEFI
53 #define EfiReallocatePool ReallocatePool
54 #else
55 #define LibLocateHandle gBS->LocateHandleBuffer
56 #define DevicePathProtocol gEfiDevicePathProtocolGuid
57 #define BlockIoProtocol gEfiBlockIoProtocolGuid
58 #define LibFileSystemInfo EfiLibFileSystemInfo
59 #define LibOpenRoot EfiLibOpenRoot
60 EFI_DEVICE_PATH EndDevicePath[] = {
61 {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
62 };
63
64 //#define EndDevicePath DevicePath
65 #endif
66
67 // variables
68
69 EFI_HANDLE SelfImageHandle;
70 EFI_LOADED_IMAGE *SelfLoadedImage;
71 EFI_FILE *SelfRootDir;
72 EFI_FILE *SelfDir;
73 CHAR16 *SelfDirPath;
74
75 REFIT_VOLUME *SelfVolume = NULL;
76 REFIT_VOLUME **Volumes = NULL;
77 UINTN VolumesCount = 0;
78
79 // Maximum size for disk sectors
80 #define SECTOR_SIZE 4096
81
82 // Default names for volume badges (mini-icon to define disk type) and icons
83 #define VOLUME_BADGE_NAME L".VolumeBadge.icns"
84 #define VOLUME_ICON_NAME L".VolumeIcon.icns"
85
86 // functions
87
88 static EFI_STATUS FinishInitRefitLib(VOID);
89
90 static VOID UninitVolumes(VOID);
91
92 //
93 // self recognition stuff
94 //
95
96 // Converts forward slashes to backslashes, removes duplicate slashes, and
97 // removes slashes from the end of the pathname.
98 // Necessary because some (buggy?) EFI implementations produce "\/" strings
99 // in pathnames, because some user inputs can produce duplicate directory
100 // separators, and because we want consistent start and end slashes for
101 // directory comparisons. A special case: If the PathName refers to root,
102 // return "/", since some firmware implementations flake out if this
103 // isn't present.
104 VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
105 CHAR16 *NewName;
106 UINTN i, FinalChar = 0;
107 BOOLEAN LastWasSlash = FALSE;
108
109 NewName = AllocateZeroPool(sizeof(CHAR16) * (StrLen(PathName) + 4));
110 if (NewName != NULL) {
111 for (i = 0; i < StrLen(PathName); i++) {
112 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
113 if ((!LastWasSlash) /* && (FinalChar != 0) */)
114 NewName[FinalChar++] = L'\\';
115 LastWasSlash = TRUE;
116 } else {
117 if (FinalChar == 0) {
118 NewName[FinalChar++] = L'\\';
119 }
120 NewName[FinalChar++] = PathName[i];
121 LastWasSlash = FALSE;
122 } // if/else
123 } // for
124 NewName[FinalChar] = 0;
125 if ((FinalChar > 1) && (NewName[FinalChar - 1] == L'\\'))
126 NewName[--FinalChar] = 0;
127 if (FinalChar == 0) {
128 NewName[0] = L'\\';
129 NewName[1] = 0;
130 }
131 // Copy the transformed name back....
132 StrCpy(PathName, NewName);
133 FreePool(NewName);
134 } // if allocation OK
135 } // CleanUpPathNameSlashes()
136
137 // Splits an EFI device path into device and filename components. For instance, if InString is
138 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
139 // this function will truncate that input to
140 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
141 // and return bzImage-3.5.1.efi as its return value.
142 // It does this by searching for the last ")" character in InString, copying everything
143 // after that string (after some cleanup) as the return value, and truncating the original
144 // input value.
145 // If InString contains no ")" character, this function leaves the original input string
146 // unmodified and also returns that string.
147 static CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
148 INTN i;
149 CHAR16 *FileName = NULL;
150 BOOLEAN Found = FALSE;
151
152 i = StrLen(InString) - 1;
153 while ((i >= 0) && (!Found)) {
154 if (InString[i] == L')') {
155 Found = TRUE;
156 FileName = StrDuplicate(&InString[i + 1]);
157 CleanUpPathNameSlashes(FileName);
158 InString[i + 1] = '\0';
159 } // if
160 i--;
161 } // while
162 if (FileName == NULL)
163 FileName = StrDuplicate(InString);
164 return FileName;
165 } // static CHAR16* SplitDeviceString()
166
167 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
168 {
169 EFI_STATUS Status;
170 CHAR16 *DevicePathAsString, *Temp;
171
172 SelfImageHandle = ImageHandle;
173 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
174 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
175 return EFI_LOAD_ERROR;
176
177 // find the current directory
178 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
179 CleanUpPathNameSlashes(DevicePathAsString);
180 MyFreePool(SelfDirPath);
181 Temp = FindPath(DevicePathAsString);
182 SelfDirPath = SplitDeviceString(Temp);
183 MyFreePool(DevicePathAsString);
184 MyFreePool(Temp);
185
186 return FinishInitRefitLib();
187 }
188
189 // called before running external programs to close open file handles
190 VOID UninitRefitLib(VOID)
191 {
192 UninitVolumes();
193
194 if (SelfDir != NULL) {
195 refit_call1_wrapper(SelfDir->Close, SelfDir);
196 SelfDir = NULL;
197 }
198
199 if (SelfRootDir != NULL) {
200 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
201 SelfRootDir = NULL;
202 }
203 }
204
205 // called after running external programs to re-open file handles
206 EFI_STATUS ReinitRefitLib(VOID)
207 {
208 ReinitVolumes();
209
210 if ((ST->Hdr.Revision >> 16) == 1) {
211 // Below two lines were in rEFIt, but seem to cause system crashes or
212 // reboots when launching OSes after returning from programs on most
213 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
214 // installation volume" (see the next function) when returning from
215 // programs when these two lines are removed, and it often crashes
216 // when returning from a program or when launching a second program
217 // with these lines removed. Therefore, the preceding if() statement
218 // executes these lines only on EFIs with a major version number of 1
219 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
220 // of hardware on which to test is limited, though, so this may be the
221 // wrong test, or there may be a better way to fix this problem.
222 // TODO: Figure out cause of above weirdness and fix it more
223 // reliably!
224 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
225 SelfRootDir = SelfVolume->RootDir;
226 } // if
227
228 return FinishInitRefitLib();
229 }
230
231 static EFI_STATUS FinishInitRefitLib(VOID)
232 {
233 EFI_STATUS Status;
234
235 if (SelfRootDir == NULL) {
236 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
237 if (SelfRootDir == NULL) {
238 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
239 return EFI_LOAD_ERROR;
240 }
241 }
242
243 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
244 if (CheckFatalError(Status, L"while opening our installation directory"))
245 return EFI_LOAD_ERROR;
246
247 return EFI_SUCCESS;
248 }
249
250 //
251 // list functions
252 //
253
254 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
255 {
256 UINTN AllocateCount;
257
258 *ElementCount = InitialElementCount;
259 if (*ElementCount > 0) {
260 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
261 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
262 } else {
263 *ListPtr = NULL;
264 }
265 }
266
267 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
268 {
269 UINTN AllocateCount;
270
271 if ((*ElementCount & 7) == 0) {
272 AllocateCount = *ElementCount + 8;
273 if (*ElementCount == 0)
274 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
275 else
276 *ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
277 }
278 (*ListPtr)[*ElementCount] = NewElement;
279 (*ElementCount)++;
280 } /* VOID AddListElement() */
281
282 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
283 {
284 UINTN i;
285
286 if ((*ElementCount > 0) && (**ListPtr != NULL)) {
287 for (i = 0; i < *ElementCount; i++) {
288 // TODO: call a user-provided routine for each element here
289 MyFreePool((*ListPtr)[i]);
290 }
291 MyFreePool(*ListPtr);
292 }
293 } // VOID FreeList()
294
295 //
296 // firmware device path discovery
297 //
298
299 static UINT8 LegacyLoaderMediaPathData[] = {
300 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
301 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
302 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
303 };
304 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
305
306 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
307 {
308 EFI_STATUS Status;
309 UINTN HandleCount = 0;
310 UINTN HandleIndex, HardcodedIndex;
311 EFI_HANDLE *Handles;
312 EFI_HANDLE Handle;
313 UINTN PathCount = 0;
314 UINTN PathIndex;
315 EFI_LOADED_IMAGE *LoadedImage;
316 EFI_DEVICE_PATH *DevicePath;
317 BOOLEAN Seen;
318
319 MaxPaths--; // leave space for the terminating NULL pointer
320
321 // get all LoadedImage handles
322 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL, &HandleCount, &Handles);
323 if (CheckError(Status, L"while listing LoadedImage handles")) {
324 if (HardcodedPathList) {
325 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
326 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
327 }
328 PathList[PathCount] = NULL;
329 return;
330 }
331 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
332 Handle = Handles[HandleIndex];
333
334 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
335 if (EFI_ERROR(Status))
336 continue; // This can only happen if the firmware scewed up, ignore it.
337
338 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
339 if (EFI_ERROR(Status))
340 continue; // This happens, ignore it.
341
342 // Only grab memory range nodes
343 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
344 continue;
345
346 // Check if we have this device path in the list already
347 // WARNING: This assumes the first node in the device path is unique!
348 Seen = FALSE;
349 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
350 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
351 continue;
352 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
353 Seen = TRUE;
354 break;
355 }
356 }
357 if (Seen)
358 continue;
359
360 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
361 }
362 MyFreePool(Handles);
363
364 if (HardcodedPathList) {
365 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
366 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
367 }
368 PathList[PathCount] = NULL;
369 }
370
371 //
372 // volume functions
373 //
374
375 static VOID ScanVolumeBootcode(IN OUT REFIT_VOLUME *Volume, OUT BOOLEAN *Bootable)
376 {
377 EFI_STATUS Status;
378 UINT8 SectorBuffer[SECTOR_SIZE];
379 UINTN i;
380 MBR_PARTITION_INFO *MbrTable;
381 BOOLEAN MbrTableFound;
382
383 Volume->HasBootCode = FALSE;
384 Volume->OSIconName = NULL;
385 Volume->OSName = NULL;
386 *Bootable = FALSE;
387
388 if (Volume->BlockIO == NULL)
389 return;
390 if (Volume->BlockIO->Media->BlockSize > SECTOR_SIZE)
391 return; // our buffer is too small...
392
393 // look at the boot sector (this is used for both hard disks and El Torito images!)
394 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
395 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
396 Volume->BlockIOOffset, SECTOR_SIZE, SectorBuffer);
397 if (!EFI_ERROR(Status)) {
398
399 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55 && SectorBuffer[0] != 0) {
400 *Bootable = TRUE;
401 Volume->HasBootCode = TRUE;
402 }
403
404 // detect specific boot codes
405 if (CompareMem(SectorBuffer + 2, "LILO", 4) == 0 ||
406 CompareMem(SectorBuffer + 6, "LILO", 4) == 0 ||
407 CompareMem(SectorBuffer + 3, "SYSLINUX", 8) == 0 ||
408 FindMem(SectorBuffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
409 Volume->HasBootCode = TRUE;
410 Volume->OSIconName = L"linux";
411 Volume->OSName = L"Linux";
412
413 } else if (FindMem(SectorBuffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
414 Volume->HasBootCode = TRUE;
415 Volume->OSIconName = L"grub,linux";
416 Volume->OSName = L"Linux";
417
418 // // Below doesn't produce a bootable entry, so commented out for the moment....
419 // // GRUB in BIOS boot partition:
420 // } else if (FindMem(SectorBuffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
421 // Volume->HasBootCode = TRUE;
422 // Volume->OSIconName = L"grub,linux";
423 // Volume->OSName = L"Linux";
424 // Volume->VolName = L"BIOS Boot Partition";
425 // *Bootable = TRUE;
426
427 } else if ((*((UINT32 *)(SectorBuffer + 502)) == 0 &&
428 *((UINT32 *)(SectorBuffer + 506)) == 50000 &&
429 *((UINT16 *)(SectorBuffer + 510)) == 0xaa55) ||
430 FindMem(SectorBuffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
431 Volume->HasBootCode = TRUE;
432 Volume->OSIconName = L"freebsd";
433 Volume->OSName = L"FreeBSD";
434
435 } else if (FindMem(SectorBuffer, 512, "!Loading", 8) >= 0 ||
436 FindMem(SectorBuffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
437 Volume->HasBootCode = TRUE;
438 Volume->OSIconName = L"openbsd";
439 Volume->OSName = L"OpenBSD";
440
441 } else if (FindMem(SectorBuffer, 512, "Not a bootxx image", 18) >= 0 ||
442 *((UINT32 *)(SectorBuffer + 1028)) == 0x7886b6d1) {
443 Volume->HasBootCode = TRUE;
444 Volume->OSIconName = L"netbsd";
445 Volume->OSName = L"NetBSD";
446
447 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
448 Volume->HasBootCode = TRUE;
449 Volume->OSIconName = L"win";
450 Volume->OSName = L"Windows";
451
452 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
453 Volume->HasBootCode = TRUE;
454 Volume->OSIconName = L"winvista,win";
455 Volume->OSName = L"Windows";
456
457 } else if (FindMem(SectorBuffer, 512, "CPUBOOT SYS", 11) >= 0 ||
458 FindMem(SectorBuffer, 512, "KERNEL SYS", 11) >= 0) {
459 Volume->HasBootCode = TRUE;
460 Volume->OSIconName = L"freedos";
461 Volume->OSName = L"FreeDOS";
462
463 } else if (FindMem(SectorBuffer, 512, "OS2LDR", 6) >= 0 ||
464 FindMem(SectorBuffer, 512, "OS2BOOT", 7) >= 0) {
465 Volume->HasBootCode = TRUE;
466 Volume->OSIconName = L"ecomstation";
467 Volume->OSName = L"eComStation";
468
469 } else if (FindMem(SectorBuffer, 512, "Be Boot Loader", 14) >= 0) {
470 Volume->HasBootCode = TRUE;
471 Volume->OSIconName = L"beos";
472 Volume->OSName = L"BeOS";
473
474 } else if (FindMem(SectorBuffer, 512, "yT Boot Loader", 14) >= 0) {
475 Volume->HasBootCode = TRUE;
476 Volume->OSIconName = L"zeta,beos";
477 Volume->OSName = L"ZETA";
478
479 } else if (FindMem(SectorBuffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
480 FindMem(SectorBuffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
481 Volume->HasBootCode = TRUE;
482 Volume->OSIconName = L"haiku,beos";
483 Volume->OSName = L"Haiku";
484
485 }
486
487 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
488 // need to fix AddLegacyEntry in main.c.
489
490 #if REFIT_DEBUG > 0
491 Print(L" Result of bootcode detection: %s %s (%s)\n",
492 Volume->HasBootCode ? L"bootable" : L"non-bootable",
493 Volume->OSName, Volume->OSIconName);
494 #endif
495
496 // dummy FAT boot sector (created by OS X's newfs_msdos)
497 if (FindMem(SectorBuffer, 512, "Non-system disk", 15) >= 0)
498 Volume->HasBootCode = FALSE;
499
500 // dummy FAT boot sector (created by Linux's mkdosfs)
501 if (FindMem(SectorBuffer, 512, "This is not a bootable disk", 27) >= 0)
502 Volume->HasBootCode = FALSE;
503
504 // dummy FAT boot sector (created by Windows)
505 if (FindMem(SectorBuffer, 512, "Press any key to restart", 24) >= 0)
506 Volume->HasBootCode = FALSE;
507
508 // check for MBR partition table
509 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55) {
510 MbrTableFound = FALSE;
511 MbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
512 for (i = 0; i < 4; i++)
513 if (MbrTable[i].StartLBA && MbrTable[i].Size)
514 MbrTableFound = TRUE;
515 for (i = 0; i < 4; i++)
516 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
517 MbrTableFound = FALSE;
518 if (MbrTableFound) {
519 Volume->MbrPartitionTable = AllocatePool(4 * 16);
520 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
521 }
522 }
523
524 } else {
525 #if REFIT_DEBUG > 0
526 CheckError(Status, L"while reading boot sector");
527 #endif
528 }
529 }
530
531 // default volume badge icon based on disk kind
532 static VOID ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME *Volume)
533 {
534 switch (Volume->DiskKind) {
535 case DISK_KIND_INTERNAL:
536 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
537 break;
538 case DISK_KIND_EXTERNAL:
539 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
540 break;
541 case DISK_KIND_OPTICAL:
542 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
543 break;
544 } // switch()
545 }
546
547 VOID ScanVolume(IN OUT REFIT_VOLUME *Volume)
548 {
549 EFI_STATUS Status;
550 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
551 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
552 EFI_HANDLE WholeDiskHandle;
553 UINTN PartialLength;
554 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
555 BOOLEAN Bootable;
556
557 // get device path
558 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
559 #if REFIT_DEBUG > 0
560 if (Volume->DevicePath != NULL) {
561 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
562 #if REFIT_DEBUG >= 2
563 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
564 #endif
565 }
566 #endif
567
568 Volume->DiskKind = DISK_KIND_INTERNAL; // default
569
570 // get block i/o
571 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
572 if (EFI_ERROR(Status)) {
573 Volume->BlockIO = NULL;
574 Print(L"Warning: Can't get BlockIO protocol.\n");
575 } else {
576 if (Volume->BlockIO->Media->BlockSize == 2048)
577 Volume->DiskKind = DISK_KIND_OPTICAL;
578 }
579
580 // scan for bootcode and MBR table
581 Bootable = FALSE;
582 ScanVolumeBootcode(Volume, &Bootable);
583
584 // detect device type
585 DevicePath = Volume->DevicePath;
586 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
587 NextDevicePath = NextDevicePathNode(DevicePath);
588
589 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
590 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
591 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
592 DevicePathSubType(DevicePath) == MSG_1394_DP ||
593 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
594 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
595 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
596 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
597 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
598 Bootable = TRUE;
599 }
600
601 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
602 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
603 // TODO: also check for Boot Camp GUID
604 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
605 }
606
607 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
608 // make a device path for the whole device
609 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
610 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
611 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
612 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
613
614 // get the handle for that path
615 RemainingDevicePath = DiskDevicePath;
616 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
617 FreePool(DiskDevicePath);
618
619 if (!EFI_ERROR(Status)) {
620 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
621
622 // get the device path for later
623 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
624 if (!EFI_ERROR(Status)) {
625 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
626 }
627
628 // look at the BlockIO protocol
629 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
630 if (!EFI_ERROR(Status)) {
631
632 // check the media block size
633 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
634 Volume->DiskKind = DISK_KIND_OPTICAL;
635
636 } else {
637 Volume->WholeDiskBlockIO = NULL;
638 //CheckError(Status, L"from HandleProtocol");
639 }
640 } //else
641 // CheckError(Status, L"from LocateDevicePath");
642 }
643
644 DevicePath = NextDevicePath;
645 } // while
646
647 if (!Bootable) {
648 #if REFIT_DEBUG > 0
649 if (Volume->HasBootCode)
650 Print(L" Volume considered non-bootable, but boot code is present\n");
651 #endif
652 Volume->HasBootCode = FALSE;
653 }
654
655 // default volume icon based on disk kind
656 ScanVolumeDefaultIcon(Volume);
657
658 // open the root directory of the volume
659 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
660 if (Volume->RootDir == NULL) {
661 Volume->IsReadable = FALSE;
662 return;
663 } else {
664 Volume->IsReadable = TRUE;
665 }
666
667 // get volume name
668 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
669 if (FileSystemInfoPtr != NULL) {
670 Volume->VolName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
671 FreePool(FileSystemInfoPtr);
672 }
673
674 if (Volume->VolName == NULL) {
675 Volume->VolName = StrDuplicate(L"Unknown");
676 }
677 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
678 // - name from bytes 3 to 10 of the boot sector
679 // - partition number
680 // - name derived from file system type or partition type
681
682 // get custom volume icon if present
683 if (FileExists(Volume->RootDir, VOLUME_BADGE_NAME))
684 Volume->VolBadgeImage = LoadIcns(Volume->RootDir, VOLUME_BADGE_NAME, 32);
685 if (FileExists(Volume->RootDir, VOLUME_ICON_NAME)) {
686 Volume->VolIconImage = LoadIcns(Volume->RootDir, VOLUME_ICON_NAME, 128);
687 }
688 } // ScanVolume()
689
690 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
691 {
692 EFI_STATUS Status;
693 REFIT_VOLUME *Volume;
694 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
695 UINTN i;
696 UINTN LogicalPartitionIndex = 4;
697 UINT8 SectorBuffer[512];
698 BOOLEAN Bootable;
699 MBR_PARTITION_INFO *EMbrTable;
700
701 ExtBase = MbrEntry->StartLBA;
702
703 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
704 // read current EMBR
705 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
706 WholeDiskVolume->BlockIO,
707 WholeDiskVolume->BlockIO->Media->MediaId,
708 ExtCurrent, 512, SectorBuffer);
709 if (EFI_ERROR(Status))
710 break;
711 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
712 break;
713 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
714
715 // scan logical partitions in this EMBR
716 NextExtCurrent = 0;
717 for (i = 0; i < 4; i++) {
718 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
719 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
720 break;
721 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
722 // set next ExtCurrent
723 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
724 break;
725 } else {
726
727 // found a logical partition
728 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
729 Volume->DiskKind = WholeDiskVolume->DiskKind;
730 Volume->IsMbrPartition = TRUE;
731 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
732 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
733 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
734 Volume->BlockIO = WholeDiskVolume->BlockIO;
735 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
736 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
737
738 Bootable = FALSE;
739 ScanVolumeBootcode(Volume, &Bootable);
740 if (!Bootable)
741 Volume->HasBootCode = FALSE;
742
743 ScanVolumeDefaultIcon(Volume);
744
745 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
746
747 }
748 }
749 }
750 }
751
752 VOID ScanVolumes(VOID)
753 {
754 EFI_STATUS Status;
755 UINTN HandleCount = 0;
756 UINTN HandleIndex;
757 EFI_HANDLE *Handles;
758 REFIT_VOLUME *Volume, *WholeDiskVolume;
759 UINTN VolumeIndex, VolumeIndex2;
760 MBR_PARTITION_INFO *MbrTable;
761 UINTN PartitionIndex;
762 UINT8 *SectorBuffer1, *SectorBuffer2;
763 UINTN SectorSum, i;
764
765 MyFreePool(Volumes);
766 Volumes = NULL;
767 VolumesCount = 0;
768
769 // get all filesystem handles
770 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
771 // was: &FileSystemProtocol
772 if (Status == EFI_NOT_FOUND) {
773 return; // no filesystems. strange, but true...
774 }
775 if (CheckError(Status, L"while listing all file systems"))
776 return;
777
778 // first pass: collect information about all handles
779 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
780 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
781 Volume->DeviceHandle = Handles[HandleIndex];
782 ScanVolume(Volume);
783
784 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
785
786 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
787 SelfVolume = Volume;
788 }
789 MyFreePool(Handles);
790
791 if (SelfVolume == NULL)
792 Print(L"WARNING: SelfVolume not found");
793
794 // second pass: relate partitions and whole disk devices
795 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
796 Volume = Volumes[VolumeIndex];
797 // check MBR partition table for extended partitions
798 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
799 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
800 Volume->MbrPartitionTable != NULL) {
801 MbrTable = Volume->MbrPartitionTable;
802 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
803 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
804 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
805 }
806 }
807 }
808
809 // search for corresponding whole disk volume entry
810 WholeDiskVolume = NULL;
811 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
812 Volume->BlockIO != Volume->WholeDiskBlockIO) {
813 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
814 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
815 Volumes[VolumeIndex2]->BlockIOOffset == 0)
816 WholeDiskVolume = Volumes[VolumeIndex2];
817 }
818 }
819
820 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
821 // check if this volume is one of the partitions in the table
822 MbrTable = WholeDiskVolume->MbrPartitionTable;
823 SectorBuffer1 = AllocatePool(512);
824 SectorBuffer2 = AllocatePool(512);
825 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
826 // check size
827 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
828 continue;
829
830 // compare boot sector read through offset vs. directly
831 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
832 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
833 Volume->BlockIOOffset, 512, SectorBuffer1);
834 if (EFI_ERROR(Status))
835 break;
836 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
837 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
838 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
839 if (EFI_ERROR(Status))
840 break;
841 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
842 continue;
843 SectorSum = 0;
844 for (i = 0; i < 512; i++)
845 SectorSum += SectorBuffer1[i];
846 if (SectorSum < 1000)
847 continue;
848
849 // TODO: mark entry as non-bootable if it is an extended partition
850
851 // now we're reasonably sure the association is correct...
852 Volume->IsMbrPartition = TRUE;
853 Volume->MbrPartitionIndex = PartitionIndex;
854 if (Volume->VolName == NULL) {
855 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
856 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
857 }
858 break;
859 }
860
861 MyFreePool(SectorBuffer1);
862 MyFreePool(SectorBuffer2);
863 }
864
865 }
866 } /* VOID ScanVolumes() */
867
868 static VOID UninitVolumes(VOID)
869 {
870 REFIT_VOLUME *Volume;
871 UINTN VolumeIndex;
872
873 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
874 Volume = Volumes[VolumeIndex];
875
876 if (Volume->RootDir != NULL) {
877 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
878 Volume->RootDir = NULL;
879 }
880
881 Volume->DeviceHandle = NULL;
882 Volume->BlockIO = NULL;
883 Volume->WholeDiskBlockIO = NULL;
884 }
885 }
886
887 VOID ReinitVolumes(VOID)
888 {
889 EFI_STATUS Status;
890 REFIT_VOLUME *Volume;
891 UINTN VolumeIndex;
892 EFI_DEVICE_PATH *RemainingDevicePath;
893 EFI_HANDLE DeviceHandle, WholeDiskHandle;
894
895 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
896 Volume = Volumes[VolumeIndex];
897
898 if (Volume->DevicePath != NULL) {
899 // get the handle for that path
900 RemainingDevicePath = Volume->DevicePath;
901 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
902
903 if (!EFI_ERROR(Status)) {
904 Volume->DeviceHandle = DeviceHandle;
905
906 // get the root directory
907 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
908
909 } else
910 CheckError(Status, L"from LocateDevicePath");
911 }
912
913 if (Volume->WholeDiskDevicePath != NULL) {
914 // get the handle for that path
915 RemainingDevicePath = Volume->WholeDiskDevicePath;
916 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
917
918 if (!EFI_ERROR(Status)) {
919 // get the BlockIO protocol
920 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
921 if (EFI_ERROR(Status)) {
922 Volume->WholeDiskBlockIO = NULL;
923 CheckError(Status, L"from HandleProtocol");
924 }
925 } else
926 CheckError(Status, L"from LocateDevicePath");
927 }
928 }
929 }
930
931 //
932 // file and dir functions
933 //
934
935 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
936 {
937 EFI_STATUS Status;
938 EFI_FILE_HANDLE TestFile;
939
940 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
941 if (Status == EFI_SUCCESS) {
942 refit_call1_wrapper(TestFile->Close, TestFile);
943 return TRUE;
944 }
945 return FALSE;
946 }
947
948 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
949 {
950 EFI_STATUS Status;
951 VOID *Buffer;
952 UINTN LastBufferSize, BufferSize;
953 INTN IterCount;
954
955 for (;;) {
956
957 // free pointer from last call
958 if (*DirEntry != NULL) {
959 FreePool(*DirEntry);
960 *DirEntry = NULL;
961 }
962
963 // read next directory entry
964 LastBufferSize = BufferSize = 256;
965 Buffer = AllocatePool(BufferSize);
966 for (IterCount = 0; ; IterCount++) {
967 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
968 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
969 break;
970 if (BufferSize <= LastBufferSize) {
971 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
972 BufferSize = LastBufferSize * 2;
973 #if REFIT_DEBUG > 0
974 } else {
975 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
976 #endif
977 }
978 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
979 LastBufferSize = BufferSize;
980 }
981 if (EFI_ERROR(Status)) {
982 FreePool(Buffer);
983 break;
984 }
985
986 // check for end of listing
987 if (BufferSize == 0) { // end of directory listing
988 FreePool(Buffer);
989 break;
990 }
991
992 // entry is ready to be returned
993 *DirEntry = (EFI_FILE_INFO *)Buffer;
994
995 // filter results
996 if (FilterMode == 1) { // only return directories
997 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
998 break;
999 } else if (FilterMode == 2) { // only return files
1000 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1001 break;
1002 } else // no filter or unknown filter -> return everything
1003 break;
1004
1005 }
1006 return Status;
1007 }
1008
1009 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1010 {
1011 if (RelativePath == NULL) {
1012 DirIter->LastStatus = EFI_SUCCESS;
1013 DirIter->DirHandle = BaseDir;
1014 DirIter->CloseDirHandle = FALSE;
1015 } else {
1016 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1017 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1018 }
1019 DirIter->LastFileInfo = NULL;
1020 }
1021
1022 #ifndef __MAKEWITH_GNUEFI
1023 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1024
1025 static EFI_STATUS
1026 InitializeUnicodeCollationProtocol (VOID)
1027 {
1028 EFI_STATUS Status;
1029
1030 if (mUnicodeCollation != NULL) {
1031 return EFI_SUCCESS;
1032 }
1033
1034 //
1035 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1036 // instances first and then select one which support English language.
1037 // Current implementation just pick the first instance.
1038 //
1039 Status = gBS->LocateProtocol (
1040 &gEfiUnicodeCollation2ProtocolGuid,
1041 NULL,
1042 (VOID **) &mUnicodeCollation
1043 );
1044 if (EFI_ERROR(Status)) {
1045 Status = gBS->LocateProtocol (
1046 &gEfiUnicodeCollationProtocolGuid,
1047 NULL,
1048 (VOID **) &mUnicodeCollation
1049 );
1050
1051 }
1052 return Status;
1053 }
1054
1055 static BOOLEAN
1056 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1057 {
1058 if (!mUnicodeCollation) {
1059 InitializeUnicodeCollationProtocol();
1060 }
1061 if (mUnicodeCollation)
1062 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1063 return FALSE; // Shouldn't happen
1064 }
1065
1066 static VOID StrLwr (IN OUT CHAR16 *Str) {
1067 if (!mUnicodeCollation) {
1068 InitializeUnicodeCollationProtocol();
1069 }
1070 if (mUnicodeCollation)
1071 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1072 }
1073
1074 #endif
1075
1076 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1077 OUT EFI_FILE_INFO **DirEntry)
1078 {
1079 BOOLEAN KeepGoing = TRUE;
1080 UINTN i;
1081 CHAR16 *OnePattern;
1082
1083 if (DirIter->LastFileInfo != NULL) {
1084 FreePool(DirIter->LastFileInfo);
1085 DirIter->LastFileInfo = NULL;
1086 }
1087
1088 if (EFI_ERROR(DirIter->LastStatus))
1089 return FALSE; // stop iteration
1090
1091 do {
1092 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1093 if (EFI_ERROR(DirIter->LastStatus))
1094 return FALSE;
1095 if (DirIter->LastFileInfo == NULL) // end of listing
1096 return FALSE;
1097 if (FilePattern != NULL) {
1098 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1099 KeepGoing = FALSE;
1100 i = 0;
1101 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1102 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1103 KeepGoing = FALSE;
1104 } // while
1105 // else continue loop
1106 } else
1107 break;
1108 } while (KeepGoing);
1109
1110 *DirEntry = DirIter->LastFileInfo;
1111 return TRUE;
1112 }
1113
1114 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1115 {
1116 if (DirIter->LastFileInfo != NULL) {
1117 FreePool(DirIter->LastFileInfo);
1118 DirIter->LastFileInfo = NULL;
1119 }
1120 if (DirIter->CloseDirHandle)
1121 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1122 return DirIter->LastStatus;
1123 }
1124
1125 //
1126 // file name manipulation
1127 //
1128
1129 // Returns the filename portion (minus path name) of the
1130 // specified file
1131 CHAR16 * Basename(IN CHAR16 *Path)
1132 {
1133 CHAR16 *FileName;
1134 UINTN i;
1135
1136 FileName = Path;
1137
1138 if (Path != NULL) {
1139 for (i = StrLen(Path); i > 0; i--) {
1140 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1141 FileName = Path + i;
1142 break;
1143 }
1144 }
1145 }
1146
1147 return FileName;
1148 }
1149
1150 // Replaces a filename extension of ".efi" with the specified string
1151 // (Extension). If the input Path doesn't end in ".efi", Extension
1152 // is added to the existing filename.
1153 VOID ReplaceEfiExtension(IN OUT CHAR16 *Path, IN CHAR16 *Extension)
1154 {
1155 UINTN PathLen;
1156
1157 PathLen = StrLen(Path);
1158 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1159 if ((PathLen >= 4) && ((StriCmp(&Path[PathLen - 4], L".efi") == 0) || (StriCmp(&Path[PathLen - 4], L".EFI") == 0))) {
1160 Path[PathLen - 4] = 0;
1161 } // if
1162 StrCat(Path, Extension);
1163 } // VOID ReplaceEfiExtension()
1164
1165 //
1166 // memory string search
1167 //
1168
1169 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1170 {
1171 UINT8 *BufferPtr;
1172 UINTN Offset;
1173
1174 BufferPtr = Buffer;
1175 BufferLength -= SearchStringLength;
1176 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1177 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1178 return (INTN)Offset;
1179 }
1180
1181 return -1;
1182 }
1183
1184 // Performs a case-insensitive search of BigStr for SmallStr.
1185 // Returns TRUE if found, FALSE if not.
1186 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1187 CHAR16 *SmallCopy, *BigCopy;
1188 BOOLEAN Found = FALSE;
1189 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1190
1191 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1192 SmallCopy = StrDuplicate(SmallStr);
1193 BigCopy = StrDuplicate(BigStr);
1194 StrLwr(SmallCopy);
1195 StrLwr(BigCopy);
1196 SmallLen = StrLen(SmallCopy);
1197 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1198 while ((!Found) && (StartPoint < NumCompares)) {
1199 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1200 } // while
1201 MyFreePool(SmallCopy);
1202 MyFreePool(BigCopy);
1203 } // if
1204
1205 return (Found);
1206 } // BOOLEAN StriSubCmp()
1207
1208 // Merges two strings, creating a new one and returning a pointer to it.
1209 // If AddChar != 0, the specified character is placed between the two original
1210 // strings (unless the first string is NULL). The original input string
1211 // *First is de-allocated and replaced by the new merged string.
1212 // This is similar to StrCat, but safer and more flexible because
1213 // MergeStrings allocates memory that's the correct size for the
1214 // new merged string, so it can take a NULL *First and it cleans
1215 // up the old memory. It should *NOT* be used with a constant
1216 // *First, though....
1217 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1218 UINTN Length1 = 0, Length2 = 0;
1219 CHAR16* NewString;
1220
1221 if (*First != NULL)
1222 Length1 = StrLen(*First);
1223 if (Second != NULL)
1224 Length2 = StrLen(Second);
1225 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1226 if (NewString != NULL) {
1227 NewString[0] = L'\0';
1228 if (*First != NULL) {
1229 StrCat(NewString, *First);
1230 if (AddChar) {
1231 NewString[Length1] = AddChar;
1232 NewString[Length1 + 1] = 0;
1233 } // if (AddChar)
1234 } // if (*First != NULL)
1235 if (Second != NULL)
1236 StrCat(NewString, Second);
1237 MyFreePool(*First);
1238 *First = NewString;
1239 } else {
1240 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1241 } // if/else
1242 } // static CHAR16* MergeStrings()
1243
1244 // Takes an input pathname (*Path) and returns the part of the filename from
1245 // the final dot onwards, converted to lowercase. If the filename includes
1246 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1247 // The calling function is responsible for freeing the memory associated with
1248 // the return value.
1249 CHAR16 *FindExtension(IN CHAR16 *Path) {
1250 CHAR16 *Extension;
1251 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1252 UINTN i;
1253
1254 Extension = AllocateZeroPool(sizeof(CHAR16));
1255 if (Path) {
1256 i = StrLen(Path);
1257 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1258 if (Path[i] == L'.')
1259 Found = TRUE;
1260 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1261 FoundSlash = TRUE;
1262 if (!Found)
1263 i--;
1264 } // while
1265 if (Found) {
1266 MergeStrings(&Extension, &Path[i], 0);
1267 StrLwr(Extension);
1268 } // if (Found)
1269 } // if
1270 return (Extension);
1271 } // CHAR16 *FindExtension
1272
1273 // Takes an input pathname (*Path) and locates the final directory component
1274 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1275 // function returns the string 'foo'.
1276 // Assumes the pathname is separated with backslashes.
1277 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1278 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1279 CHAR16 *Found = NULL;
1280
1281 PathLength = StrLen(Path);
1282 // Find start & end of target element
1283 for (i = 0; i < PathLength; i++) {
1284 if (Path[i] == '\\') {
1285 StartOfElement = EndOfElement;
1286 EndOfElement = i;
1287 } // if
1288 } // for
1289 // Extract the target element
1290 if (EndOfElement > 0) {
1291 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1292 StartOfElement++;
1293 } // while
1294 EndOfElement--;
1295 if (EndOfElement >= StartOfElement) {
1296 CopyLength = EndOfElement - StartOfElement + 1;
1297 Found = StrDuplicate(&Path[StartOfElement]);
1298 if (Found != NULL)
1299 Found[CopyLength] = 0;
1300 } // if (EndOfElement >= StartOfElement)
1301 } // if (EndOfElement > 0)
1302 return (Found);
1303 } // CHAR16 *FindLastDirName
1304
1305 // Returns the directory portion of a pathname. For instance,
1306 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1307 // string 'EFI\foo'. The calling function is responsible for
1308 // freeing the returned string's memory.
1309 CHAR16 *FindPath(IN CHAR16* FullPath) {
1310 UINTN i, LastBackslash = 0;
1311 CHAR16 *PathOnly;
1312
1313 for (i = 0; i < StrLen(FullPath); i++) {
1314 if (FullPath[i] == '\\')
1315 LastBackslash = i;
1316 } // for
1317 PathOnly = StrDuplicate(FullPath);
1318 PathOnly[LastBackslash] = 0;
1319 return (PathOnly);
1320 }
1321
1322 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1323 // DeviceVolume, and returns that and the filename (*loader).
1324 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1325 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1326 UINTN i = 0;
1327 BOOLEAN Found = FALSE;
1328
1329 MyFreePool(*loader);
1330 MyFreePool(*DeviceVolume);
1331 *DeviceVolume = NULL;
1332 DeviceString = DevicePathToStr(loadpath);
1333 *loader = SplitDeviceString(DeviceString);
1334
1335 while ((i < VolumesCount) && (!Found)) {
1336 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1337 Temp = SplitDeviceString(VolumeDeviceString);
1338 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1339 Found = TRUE;
1340 *DeviceVolume = Volumes[i];
1341 }
1342 MyFreePool(Temp);
1343 MyFreePool(VolumeDeviceString);
1344 i++;
1345 } // while
1346
1347 MyFreePool(DeviceString);
1348 } // VOID FindVolumeAndFilename()
1349
1350 // Returns all the digits in the input string, including intervening
1351 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1352 // this function returns "3.3.4-7". If InString contains no digits,
1353 // the return value is NULL.
1354 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1355 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1356 CHAR16 *Found = NULL;
1357
1358 InLength = StartOfElement = StrLen(InString);
1359 // Find start & end of target element
1360 for (i = 0; i < InLength; i++) {
1361 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1362 if (StartOfElement > i)
1363 StartOfElement = i;
1364 if (EndOfElement < i)
1365 EndOfElement = i;
1366 } // if
1367 } // for
1368 // Extract the target element
1369 if (EndOfElement > 0) {
1370 if (EndOfElement >= StartOfElement) {
1371 CopyLength = EndOfElement - StartOfElement + 1;
1372 Found = StrDuplicate(&InString[StartOfElement]);
1373 if (Found != NULL)
1374 Found[CopyLength] = 0;
1375 } // if (EndOfElement >= StartOfElement)
1376 } // if (EndOfElement > 0)
1377 return (Found);
1378 } // CHAR16 *FindNumbers()
1379
1380 // Find the #Index element (numbered from 0) in a comma-delimited string
1381 // of elements.
1382 // Returns the found element, or NULL if Index is out of range or InString
1383 // is NULL. Note that the calling function is responsible for freeing the
1384 // memory associated with the returned string pointer.
1385 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1386 UINTN StartPos = 0, CurPos = 0;
1387 BOOLEAN Found = FALSE;
1388 CHAR16 *FoundString = NULL;
1389
1390 if (InString != NULL) {
1391 // After while() loop, StartPos marks start of item #Index
1392 while ((Index > 0) && (CurPos < StrLen(InString))) {
1393 if (InString[CurPos] == L',') {
1394 Index--;
1395 StartPos = CurPos + 1;
1396 } // if
1397 CurPos++;
1398 } // while
1399 // After while() loop, CurPos is one past the end of the element
1400 while ((CurPos < StrLen(InString)) && (!Found)) {
1401 if (InString[CurPos] == L',')
1402 Found = TRUE;
1403 else
1404 CurPos++;
1405 } // while
1406 if (Index == 0)
1407 FoundString = StrDuplicate(&InString[StartPos]);
1408 if (FoundString != NULL)
1409 FoundString[CurPos - StartPos] = 0;
1410 } // if
1411 return (FoundString);
1412 } // CHAR16 *FindCommaDelimited()
1413
1414 // Returns TRUE if SmallString is an element in the comma-delimited List,
1415 // FALSE otherwise. Performs comparison case-insensitively (except on
1416 // buggy EFIs with case-sensitive StriCmp() functions).
1417 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1418 UINTN i = 0;
1419 BOOLEAN Found = FALSE;
1420 CHAR16 *OneElement;
1421
1422 if (SmallString && List) {
1423 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1424 if (StriCmp(OneElement, SmallString) == 0)
1425 Found = TRUE;
1426 } // while
1427 } // if
1428 return Found;
1429 } // BOOLEAN IsIn()
1430
1431 // Implement FreePool the way it should have been done to begin with, so that
1432 // it doesn't throw an ASSERT message if fed a NULL pointer....
1433 VOID MyFreePool(IN OUT VOID *Pointer) {
1434 if (Pointer != NULL)
1435 FreePool(Pointer);
1436 }
1437
1438 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1439
1440 // Eject all removable media.
1441 // Returns TRUE if any media were ejected, FALSE otherwise.
1442 BOOLEAN EjectMedia(VOID) {
1443 EFI_STATUS Status;
1444 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1445 EFI_HANDLE *Handles, Handle;
1446 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1447
1448 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1449 if (EFI_ERROR(Status) || HandleCount == 0)
1450 return (FALSE); // probably not an Apple system
1451
1452 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1453 Handle = Handles[HandleIndex];
1454 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1455 if (EFI_ERROR(Status))
1456 continue;
1457 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1458 if (!EFI_ERROR(Status))
1459 Ejected++;
1460 }
1461 MyFreePool(Handles);
1462 return (Ejected > 0);
1463 } // VOID EjectMedia()
1464
1465
1466 // Return the GUID as a string, suitable for display to the user. Note that the calling
1467 // function is responsible for freeing the allocated memory.
1468 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1469 CHAR16 *TheString;
1470
1471 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1472 if (TheString != 0) {
1473 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1474 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1475 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1476 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1477 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1478 }
1479 return TheString;
1480 } // GuidAsString(EFI_GUID *GuidData)