3 * General library functions
5 * Copyright (c) 2006-2009 Christoph Pfisterer
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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.
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.
37 * Modifications copyright (c) 2012 Roderick W. Smith
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.
49 #include "refit_call_wrapper.h"
53 EFI_HANDLE SelfImageHandle
;
54 EFI_LOADED_IMAGE
*SelfLoadedImage
;
55 EFI_FILE
*SelfRootDir
;
59 REFIT_VOLUME
*SelfVolume
= NULL
;
60 REFIT_VOLUME
**Volumes
= NULL
;
61 UINTN VolumesCount
= 0;
63 // Maximum size for disk sectors
64 #define SECTOR_SIZE 4096
68 static EFI_STATUS
FinishInitRefitLib(VOID
);
70 static VOID
UninitVolumes(VOID
);
73 // self recognition stuff
76 // Converts forward slashes to backslashes and removes duplicate slashes.
77 // Necessary because some (buggy?) EFI implementations produce "\/" strings
79 static VOID
CleanUpPathNameSlashes(IN OUT CHAR16
*PathName
) {
82 BOOLEAN LastWasSlash
= FALSE
;
84 NewName
= AllocateZeroPool(sizeof(CHAR16
) * (StrLen(PathName
) + 1));
85 if (NewName
!= NULL
) {
86 for (i
= 0; i
< StrLen(PathName
); i
++) {
87 if ((PathName
[i
] == L
'/') || (PathName
[i
] == L
'\\')) {
92 NewName
[j
++] = PathName
[i
];
97 // Copy the transformed name back....
98 StrCpy(PathName
, NewName
);
100 } // if allocation OK
101 } // CleanUpPathNameSlashes()
103 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
106 CHAR16
*DevicePathAsString
;
109 SelfImageHandle
= ImageHandle
;
110 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
111 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
112 return EFI_LOAD_ERROR
;
114 // find the current directory
115 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
116 CleanUpPathNameSlashes(DevicePathAsString
);
117 if (DevicePathAsString
!= NULL
) {
118 for (i
= StrLen(DevicePathAsString
); (i
> 0) && (DevicePathAsString
[i
] != '\\'); i
--) ;
119 DevicePathAsString
[i
] = 0;
121 DevicePathAsString
[0] = 0;
122 SelfDirPath
= StrDuplicate(DevicePathAsString
);
123 FreePool(DevicePathAsString
);
125 return FinishInitRefitLib();
128 // called before running external programs to close open file handles
129 VOID
UninitRefitLib(VOID
)
133 if (SelfDir
!= NULL
) {
134 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
138 if (SelfRootDir
!= NULL
) {
139 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
144 // called after running external programs to re-open file handles
145 EFI_STATUS
ReinitRefitLib(VOID
)
149 // Below two lines were in rEFIt, but seem to cause problems on
150 // most systems. OTOH, my Mac Mini produces (apparently harmless)
151 // errors about "(re)opening our installation volume" (see the
152 // next function) when returning from programs when these two lines
153 // are removed. On the gripping hand, the Mac SOMETIMES crashes
154 // when launching a second program even with these lines removed.
155 // TODO: Figure out cause of above weirdness and fix it more
157 /* if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
158 SelfRootDir = SelfVolume->RootDir; */
160 return FinishInitRefitLib();
163 static EFI_STATUS
FinishInitRefitLib(VOID
)
167 if (SelfRootDir
== NULL
) {
168 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
169 if (SelfRootDir
== NULL
) {
170 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
171 return EFI_LOAD_ERROR
;
175 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
176 if (CheckFatalError(Status
, L
"while opening our installation directory"))
177 return EFI_LOAD_ERROR
;
186 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
190 *ElementCount
= InitialElementCount
;
191 if (*ElementCount
> 0) {
192 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
193 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
199 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
203 if ((*ElementCount
& 7) == 0) {
204 AllocateCount
= *ElementCount
+ 8;
205 if (*ElementCount
== 0)
206 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
208 *ListPtr
= ReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
210 (*ListPtr
)[*ElementCount
] = NewElement
;
212 } /* VOID AddListElement() */
214 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
218 if (*ElementCount
> 0) {
219 for (i
= 0; i
< *ElementCount
; i
++) {
220 // TODO: call a user-provided routine for each element here
221 FreePool((*ListPtr
)[i
]);
228 // firmware device path discovery
231 static UINT8 LegacyLoaderMediaPathData
[] = {
232 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
233 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
234 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
236 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
238 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
241 UINTN HandleCount
= 0;
242 UINTN HandleIndex
, HardcodedIndex
;
247 EFI_LOADED_IMAGE
*LoadedImage
;
248 EFI_DEVICE_PATH
*DevicePath
;
251 MaxPaths
--; // leave space for the terminating NULL pointer
253 // get all LoadedImage handles
254 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
,
255 &HandleCount
, &Handles
);
256 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
257 if (HardcodedPathList
) {
258 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
259 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
261 PathList
[PathCount
] = NULL
;
264 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
265 Handle
= Handles
[HandleIndex
];
267 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
268 if (EFI_ERROR(Status
))
269 continue; // This can only happen if the firmware scewed up, ignore it.
271 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
272 if (EFI_ERROR(Status
))
273 continue; // This happens, ignore it.
275 // Only grab memory range nodes
276 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
279 // Check if we have this device path in the list already
280 // WARNING: This assumes the first node in the device path is unique!
282 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
283 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
285 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
293 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
297 if (HardcodedPathList
) {
298 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
299 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
301 PathList
[PathCount
] = NULL
;
308 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
311 UINT8 SectorBuffer
[SECTOR_SIZE
];
313 MBR_PARTITION_INFO
*MbrTable
;
314 BOOLEAN MbrTableFound
;
316 Volume
->HasBootCode
= FALSE
;
317 Volume
->OSIconName
= NULL
;
318 Volume
->OSName
= NULL
;
321 if (Volume
->BlockIO
== NULL
)
323 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
324 return; // our buffer is too small...
326 // look at the boot sector (this is used for both hard disks and El Torito images!)
327 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
328 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
329 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
330 if (!EFI_ERROR(Status
)) {
332 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
334 Volume
->HasBootCode
= TRUE
;
337 // detect specific boot codes
338 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
339 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
340 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
341 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
342 Volume
->HasBootCode
= TRUE
;
343 Volume
->OSIconName
= L
"linux";
344 Volume
->OSName
= L
"Linux";
346 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
347 Volume
->HasBootCode
= TRUE
;
348 Volume
->OSIconName
= L
"grub,linux";
349 Volume
->OSName
= L
"Linux";
351 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
352 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
353 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
354 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
355 Volume
->HasBootCode
= TRUE
;
356 Volume
->OSIconName
= L
"freebsd";
357 Volume
->OSName
= L
"FreeBSD";
359 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
360 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
361 Volume
->HasBootCode
= TRUE
;
362 Volume
->OSIconName
= L
"openbsd";
363 Volume
->OSName
= L
"OpenBSD";
365 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
366 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
367 Volume
->HasBootCode
= TRUE
;
368 Volume
->OSIconName
= L
"netbsd";
369 Volume
->OSName
= L
"NetBSD";
371 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
372 Volume
->HasBootCode
= TRUE
;
373 Volume
->OSIconName
= L
"win";
374 Volume
->OSName
= L
"Windows";
376 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
377 Volume
->HasBootCode
= TRUE
;
378 Volume
->OSIconName
= L
"winvista,win";
379 Volume
->OSName
= L
"Windows";
381 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
382 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
383 Volume
->HasBootCode
= TRUE
;
384 Volume
->OSIconName
= L
"freedos";
385 Volume
->OSName
= L
"FreeDOS";
387 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
388 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
389 Volume
->HasBootCode
= TRUE
;
390 Volume
->OSIconName
= L
"ecomstation";
391 Volume
->OSName
= L
"eComStation";
393 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
394 Volume
->HasBootCode
= TRUE
;
395 Volume
->OSIconName
= L
"beos";
396 Volume
->OSName
= L
"BeOS";
398 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
399 Volume
->HasBootCode
= TRUE
;
400 Volume
->OSIconName
= L
"zeta,beos";
401 Volume
->OSName
= L
"ZETA";
403 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
404 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
405 Volume
->HasBootCode
= TRUE
;
406 Volume
->OSIconName
= L
"haiku,beos";
407 Volume
->OSName
= L
"Haiku";
411 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
412 // need to fix AddLegacyEntry in main.c.
415 Print(L
" Result of bootcode detection: %s %s (%s)\n",
416 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
417 Volume
->OSName
, Volume
->OSIconName
);
420 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0) // dummy FAT boot sector
421 Volume
->HasBootCode
= FALSE
;
423 // check for MBR partition table
424 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
425 MbrTableFound
= FALSE
;
426 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
427 for (i
= 0; i
< 4; i
++)
428 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
429 MbrTableFound
= TRUE
;
430 for (i
= 0; i
< 4; i
++)
431 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
432 MbrTableFound
= FALSE
;
434 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
435 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
441 CheckError(Status
, L
"while reading boot sector");
446 // default volume icon based on disk kind
447 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
449 switch (Volume
->DiskKind
) {
450 case DISK_KIND_INTERNAL
:
451 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
453 case DISK_KIND_EXTERNAL
:
454 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
456 case DISK_KIND_OPTICAL
:
457 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
462 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
465 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
466 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
467 EFI_HANDLE WholeDiskHandle
;
469 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
473 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
475 if (Volume
->DevicePath
!= NULL
) {
476 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
478 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
483 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
486 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
487 if (EFI_ERROR(Status
)) {
488 Volume
->BlockIO
= NULL
;
489 Print(L
"Warning: Can't get BlockIO protocol.\n");
491 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
492 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
495 // scan for bootcode and MBR table
497 ScanVolumeBootcode(Volume
, &Bootable
);
499 // detect device type
500 DevicePath
= Volume
->DevicePath
;
501 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
502 NextDevicePath
= NextDevicePathNode(DevicePath
);
504 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
505 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
506 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
507 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
508 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
509 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
510 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
511 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
512 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
516 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
517 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
518 // TODO: also check for Boot Camp GUID
519 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
522 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
523 // make a device path for the whole device
524 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
525 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
526 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
527 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
529 // get the handle for that path
530 RemainingDevicePath
= DiskDevicePath
;
531 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
532 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
533 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
534 FreePool(DiskDevicePath
);
536 if (!EFI_ERROR(Status
)) {
537 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
539 // get the device path for later
540 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
541 if (!EFI_ERROR(Status
)) {
542 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
545 // look at the BlockIO protocol
546 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
547 if (!EFI_ERROR(Status
)) {
549 // check the media block size
550 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
551 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
554 Volume
->WholeDiskBlockIO
= NULL
;
555 //CheckError(Status, L"from HandleProtocol");
558 // CheckError(Status, L"from LocateDevicePath");
561 DevicePath
= NextDevicePath
;
566 if (Volume
->HasBootCode
)
567 Print(L
" Volume considered non-bootable, but boot code is present\n");
569 Volume
->HasBootCode
= FALSE
;
572 // default volume icon based on disk kind
573 ScanVolumeDefaultIcon(Volume
);
575 // open the root directory of the volume
576 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
577 if (Volume
->RootDir
== NULL
) {
582 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
583 if (FileSystemInfoPtr
!= NULL
) {
584 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
585 FreePool(FileSystemInfoPtr
);
588 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
589 // - name from bytes 3 to 10 of the boot sector
590 // - partition number
591 // - name derived from file system type or partition type
593 // get custom volume icon if present
594 if (FileExists(Volume
->RootDir
, L
".VolumeIcon.icns"))
595 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, L
".VolumeIcon.icns", 32);
598 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
601 REFIT_VOLUME
*Volume
;
602 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
604 UINTN LogicalPartitionIndex
= 4;
605 UINT8 SectorBuffer
[512];
607 MBR_PARTITION_INFO
*EMbrTable
;
609 ExtBase
= MbrEntry
->StartLBA
;
611 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
613 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
614 WholeDiskVolume
->BlockIO
,
615 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
616 ExtCurrent
, 512, SectorBuffer
);
617 if (EFI_ERROR(Status
))
619 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
621 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
623 // scan logical partitions in this EMBR
625 for (i
= 0; i
< 4; i
++) {
626 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
627 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
629 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
630 // set next ExtCurrent
631 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
635 // found a logical partition
636 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
637 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
638 Volume
->IsMbrPartition
= TRUE
;
639 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
640 Volume
->VolName
= PoolPrint(L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
641 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
642 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
643 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
646 ScanVolumeBootcode(Volume
, &Bootable
);
648 Volume
->HasBootCode
= FALSE
;
650 ScanVolumeDefaultIcon(Volume
);
652 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
659 VOID
ScanVolumes(VOID
)
662 UINTN HandleCount
= 0;
665 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
666 UINTN VolumeIndex
, VolumeIndex2
;
667 MBR_PARTITION_INFO
*MbrTable
;
668 UINTN PartitionIndex
;
669 UINT8
*SectorBuffer1
, *SectorBuffer2
;
676 // get all filesystem handles
677 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
678 // was: &FileSystemProtocol
679 if (Status
== EFI_NOT_FOUND
)
680 return; // no filesystems. strange, but true...
681 if (CheckError(Status
, L
"while listing all file systems"))
684 // first pass: collect information about all handles
685 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
686 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
687 Volume
->DeviceHandle
= Handles
[HandleIndex
];
690 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
692 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
697 if (SelfVolume
== NULL
)
698 Print(L
"WARNING: SelfVolume not found");
700 // second pass: relate partitions and whole disk devices
701 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
702 Volume
= Volumes
[VolumeIndex
];
703 // check MBR partition table for extended partitions
704 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
705 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
706 Volume
->MbrPartitionTable
!= NULL
) {
707 MbrTable
= Volume
->MbrPartitionTable
;
708 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
709 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
710 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
715 // search for corresponding whole disk volume entry
716 WholeDiskVolume
= NULL
;
717 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
718 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
719 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
720 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
721 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
722 WholeDiskVolume
= Volumes
[VolumeIndex2
];
726 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
727 // check if this volume is one of the partitions in the table
728 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
729 SectorBuffer1
= AllocatePool(512);
730 SectorBuffer2
= AllocatePool(512);
731 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
733 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
736 // compare boot sector read through offset vs. directly
737 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
738 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
739 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
740 if (EFI_ERROR(Status
))
742 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
743 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
744 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
745 if (EFI_ERROR(Status
))
747 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
750 for (i
= 0; i
< 512; i
++)
751 SectorSum
+= SectorBuffer1
[i
];
752 if (SectorSum
< 1000)
755 // TODO: mark entry as non-bootable if it is an extended partition
757 // now we're reasonably sure the association is correct...
758 Volume
->IsMbrPartition
= TRUE
;
759 Volume
->MbrPartitionIndex
= PartitionIndex
;
760 if (Volume
->VolName
== NULL
)
761 Volume
->VolName
= PoolPrint(L
"Partition %d", PartitionIndex
+ 1);
765 FreePool(SectorBuffer1
);
766 FreePool(SectorBuffer2
);
770 } /* VOID ScanVolumes() */
772 static VOID
UninitVolumes(VOID
)
774 REFIT_VOLUME
*Volume
;
777 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
778 Volume
= Volumes
[VolumeIndex
];
780 if (Volume
->RootDir
!= NULL
) {
781 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
782 Volume
->RootDir
= NULL
;
785 Volume
->DeviceHandle
= NULL
;
786 Volume
->BlockIO
= NULL
;
787 Volume
->WholeDiskBlockIO
= NULL
;
791 VOID
ReinitVolumes(VOID
)
794 REFIT_VOLUME
*Volume
;
796 EFI_DEVICE_PATH
*RemainingDevicePath
;
797 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
799 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
800 Volume
= Volumes
[VolumeIndex
];
802 if (Volume
->DevicePath
!= NULL
) {
803 // get the handle for that path
804 RemainingDevicePath
= Volume
->DevicePath
;
805 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
807 if (!EFI_ERROR(Status
)) {
808 Volume
->DeviceHandle
= DeviceHandle
;
810 // get the root directory
811 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
814 CheckError(Status
, L
"from LocateDevicePath");
817 if (Volume
->WholeDiskDevicePath
!= NULL
) {
818 // get the handle for that path
819 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
820 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
822 if (!EFI_ERROR(Status
)) {
823 // get the BlockIO protocol
824 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
825 if (EFI_ERROR(Status
)) {
826 Volume
->WholeDiskBlockIO
= NULL
;
827 CheckError(Status
, L
"from HandleProtocol");
830 CheckError(Status
, L
"from LocateDevicePath");
836 // file and dir functions
839 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
842 EFI_FILE_HANDLE TestFile
;
844 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
845 if (Status
== EFI_SUCCESS
) {
846 refit_call1_wrapper(TestFile
->Close
, TestFile
);
852 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
856 UINTN LastBufferSize
, BufferSize
;
861 // free pointer from last call
862 if (*DirEntry
!= NULL
) {
867 // read next directory entry
868 LastBufferSize
= BufferSize
= 256;
869 Buffer
= AllocatePool(BufferSize
);
870 for (IterCount
= 0; ; IterCount
++) {
871 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
872 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
874 if (BufferSize
<= LastBufferSize
) {
875 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
876 BufferSize
= LastBufferSize
* 2;
879 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
882 Buffer
= ReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
883 LastBufferSize
= BufferSize
;
885 if (EFI_ERROR(Status
)) {
890 // check for end of listing
891 if (BufferSize
== 0) { // end of directory listing
896 // entry is ready to be returned
897 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
900 if (FilterMode
== 1) { // only return directories
901 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
903 } else if (FilterMode
== 2) { // only return files
904 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
906 } else // no filter or unknown filter -> return everything
913 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
915 if (RelativePath
== NULL
) {
916 DirIter
->LastStatus
= EFI_SUCCESS
;
917 DirIter
->DirHandle
= BaseDir
;
918 DirIter
->CloseDirHandle
= FALSE
;
920 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
921 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
923 DirIter
->LastFileInfo
= NULL
;
926 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
927 OUT EFI_FILE_INFO
**DirEntry
)
929 if (DirIter
->LastFileInfo
!= NULL
) {
930 FreePool(DirIter
->LastFileInfo
);
931 DirIter
->LastFileInfo
= NULL
;
934 if (EFI_ERROR(DirIter
->LastStatus
))
935 return FALSE
; // stop iteration
938 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
939 if (EFI_ERROR(DirIter
->LastStatus
))
941 if (DirIter
->LastFileInfo
== NULL
) // end of listing
943 if (FilePattern
!= NULL
) {
944 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
946 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, FilePattern
))
948 // else continue loop
953 *DirEntry
= DirIter
->LastFileInfo
;
957 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
959 if (DirIter
->LastFileInfo
!= NULL
) {
960 FreePool(DirIter
->LastFileInfo
);
961 DirIter
->LastFileInfo
= NULL
;
963 if (DirIter
->CloseDirHandle
)
964 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
965 return DirIter
->LastStatus
;
969 // file name manipulation
972 // Returns the filename portion (minus path name) of the
974 CHAR16
* Basename(IN CHAR16
*Path
)
982 for (i
= StrLen(Path
); i
> 0; i
--) {
983 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
993 VOID
ReplaceExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
997 for (i
= StrLen(Path
); i
>= 0; i
--) {
998 if (Path
[i
] == '.') {
1002 if (Path
[i
] == '\\' || Path
[i
] == '/')
1005 StrCat(Path
, Extension
);
1009 // memory string search
1012 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
1018 BufferLength
-= SearchStringLength
;
1019 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
1020 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1021 return (INTN
)Offset
;
1027 // Performs a case-insensitive search of BigStr for SmallStr.
1028 // Returns TRUE if found, FALSE if not.
1029 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1030 CHAR16
*SmallCopy
, *BigCopy
;
1031 BOOLEAN Found
= FALSE
;
1032 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1034 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1035 SmallCopy
= StrDuplicate(SmallStr
);
1036 BigCopy
= StrDuplicate(BigStr
);
1039 SmallLen
= StrLen(SmallCopy
);
1040 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1041 while ((!Found
) && (StartPoint
< NumCompares
)) {
1042 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1044 FreePool(SmallCopy
);
1049 } // BOOLEAN StriSubCmp()
1051 // Merges two strings, creating a new one and returning a pointer to it.
1052 // If AddChar != 0, the specified character is placed between the two original
1053 // strings (unless the first string is NULL). The original input string
1054 // *First is de-allocated and replaced by the new merged string.
1055 // This is similar to StrCat, but safer and more flexible because
1056 // MergeStrings allocates memory that's the correct size for the
1057 // new merged string, so it can take a NULL *First and it cleans
1058 // up the old memory. It should *NOT* be used with a constant
1059 // *First, though....
1060 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1061 UINTN Length1
= 0, Length2
= 0;
1065 Length1
= StrLen(*First
);
1067 Length2
= StrLen(Second
);
1068 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1070 if (NewString
!= NULL
) {
1071 if (*First
!= NULL
) {
1072 StrCat(NewString
, *First
);
1074 NewString
[Length1
] = AddChar
;
1075 NewString
[Length1
+ 1] = 0;
1077 } // if (*First != NULL)
1079 StrCat(NewString
, Second
);
1083 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1085 } // static CHAR16* MergeStrings()
1087 // Takes an input pathname (*Path) and locates the final directory component
1088 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1089 // function returns the string 'foo'.
1090 // Assumes the pathname is separated with backslashes.
1091 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1092 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1093 CHAR16
*Found
= NULL
;
1095 PathLength
= StrLen(Path
);
1096 // Find start & end of target element
1097 for (i
= 0; i
< PathLength
; i
++) {
1098 if (Path
[i
] == '\\') {
1099 StartOfElement
= EndOfElement
;
1103 // Extract the target element
1104 if (EndOfElement
> 0) {
1105 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1109 if (EndOfElement
>= StartOfElement
) {
1110 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1111 Found
= StrDuplicate(&Path
[StartOfElement
]);
1113 Found
[CopyLength
] = 0;
1114 } // if (EndOfElement >= StartOfElement)
1115 } // if (EndOfElement > 0)
1117 } // CHAR16 *FindLastDirName
1119 // Returns the directory portion of a pathname. For instance,
1120 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1121 // string 'EFI\foo'.
1122 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1123 UINTN i
, LastBackslash
= 0;
1126 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1127 if (FullPath
[i
] == '\\')
1130 PathOnly
= StrDuplicate(FullPath
);
1131 PathOnly
[LastBackslash
] = 0;
1135 // Returns all the digits in the input string, including intervening
1136 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1137 // this function returns "3.3.4-7". If InString contains no digits,
1138 // the return value is NULL.
1139 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1140 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1141 CHAR16
*Found
= NULL
;
1143 InLength
= StartOfElement
= StrLen(InString
);
1144 // Find start & end of target element
1145 for (i
= 0; i
< InLength
; i
++) {
1146 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1147 if (StartOfElement
> i
)
1149 if (EndOfElement
< i
)
1153 // Extract the target element
1154 if (EndOfElement
> 0) {
1155 if (EndOfElement
>= StartOfElement
) {
1156 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1157 Found
= StrDuplicate(&InString
[StartOfElement
]);
1159 Found
[CopyLength
] = 0;
1160 } // if (EndOfElement >= StartOfElement)
1161 } // if (EndOfElement > 0)
1163 } // CHAR16 *FindNumbers()
1165 // Find the #Index element (numbered from 0) in a comma-delimited string
1167 // Returns the found element, or NULL if Index is out of range of InString
1169 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1170 UINTN StartPos
= 0, CurPos
= 0;
1171 BOOLEAN Found
= FALSE
;
1172 CHAR16
*FoundString
= NULL
;
1174 if (InString
!= NULL
) {
1175 // After while() loop, StartPos marks start of item #Index
1176 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1177 if (InString
[CurPos
] == L
',') {
1179 StartPos
= CurPos
+ 1;
1183 // After while() loop, CurPos is one past the end of the element
1184 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1185 if (InString
[CurPos
] == L
',')
1192 FoundString
= StrDuplicate(&InString
[StartPos
]);
1193 if (FoundString
!= NULL
)
1194 FoundString
[CurPos
- StartPos
] = 0;
1195 return (FoundString
);
1196 } // CHAR16 *FindCommaDelimited()