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