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