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