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