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