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 EFI_STATUS
InitRefitLib(IN EFI_HANDLE ImageHandle
)
79 CHAR16
*DevicePathAsString
;
80 CHAR16 BaseDirectory
[256];
83 SelfImageHandle
= ImageHandle
;
84 Status
= refit_call3_wrapper(BS
->HandleProtocol
, SelfImageHandle
, &LoadedImageProtocol
, (VOID
**) &SelfLoadedImage
);
85 if (CheckFatalError(Status
, L
"while getting a LoadedImageProtocol handle"))
86 return EFI_LOAD_ERROR
;
88 // find the current directory
89 DevicePathAsString
= DevicePathToStr(SelfLoadedImage
->FilePath
);
90 if (DevicePathAsString
!= NULL
) {
91 StrCpy(BaseDirectory
, DevicePathAsString
);
92 FreePool(DevicePathAsString
);
93 for (i
= StrLen(BaseDirectory
); i
> 0 && BaseDirectory
[i
] != '\\'; i
--) ;
97 SelfDirPath
= StrDuplicate(BaseDirectory
);
99 return FinishInitRefitLib();
102 // called before running external programs to close open file handles
103 VOID
UninitRefitLib(VOID
)
107 if (SelfDir
!= NULL
) {
108 refit_call1_wrapper(SelfDir
->Close
, SelfDir
);
112 if (SelfRootDir
!= NULL
) {
113 refit_call1_wrapper(SelfRootDir
->Close
, SelfRootDir
);
118 // called after running external programs to re-open file handles
119 EFI_STATUS
ReinitRefitLib(VOID
)
123 // Below two lines were in rEFIt, but seem to cause problems on
124 // most systems. OTOH, my Mac Mini produces (apparently harmless)
125 // errors about "(re)opening our installation volume" (see the
126 // next function) when returning from programs when these two lines
127 // are removed. On the gripping hand, the Mac SOMETIMES crashes
128 // when launching a second program even with these lines removed.
129 // TODO: Figure out cause of above weirdness and fix it more
131 /* if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
132 SelfRootDir = SelfVolume->RootDir; */
134 return FinishInitRefitLib();
137 static EFI_STATUS
FinishInitRefitLib(VOID
)
141 if (SelfRootDir
== NULL
) {
142 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
143 if (SelfRootDir
== NULL
) {
144 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
145 return EFI_LOAD_ERROR
;
149 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
150 if (CheckFatalError(Status
, L
"while opening our installation directory"))
151 return EFI_LOAD_ERROR
;
160 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
164 *ElementCount
= InitialElementCount
;
165 if (*ElementCount
> 0) {
166 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
167 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
173 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
177 if ((*ElementCount
& 7) == 0) {
178 AllocateCount
= *ElementCount
+ 8;
179 if (*ElementCount
== 0)
180 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
182 *ListPtr
= ReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
184 (*ListPtr
)[*ElementCount
] = NewElement
;
186 } /* VOID AddListElement() */
188 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
192 if (*ElementCount
> 0) {
193 for (i
= 0; i
< *ElementCount
; i
++) {
194 // TODO: call a user-provided routine for each element here
195 FreePool((*ListPtr
)[i
]);
202 // firmware device path discovery
205 static UINT8 LegacyLoaderMediaPathData
[] = {
206 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
207 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
208 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
210 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
212 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
215 UINTN HandleCount
= 0;
216 UINTN HandleIndex
, HardcodedIndex
;
221 EFI_LOADED_IMAGE
*LoadedImage
;
222 EFI_DEVICE_PATH
*DevicePath
;
225 MaxPaths
--; // leave space for the terminating NULL pointer
227 // get all LoadedImage handles
228 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
,
229 &HandleCount
, &Handles
);
230 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
231 if (HardcodedPathList
) {
232 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
233 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
235 PathList
[PathCount
] = NULL
;
238 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
239 Handle
= Handles
[HandleIndex
];
241 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
242 if (EFI_ERROR(Status
))
243 continue; // This can only happen if the firmware scewed up, ignore it.
245 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
246 if (EFI_ERROR(Status
))
247 continue; // This happens, ignore it.
249 // Only grab memory range nodes
250 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
253 // Check if we have this device path in the list already
254 // WARNING: This assumes the first node in the device path is unique!
256 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
257 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
259 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
267 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
271 if (HardcodedPathList
) {
272 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
273 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
275 PathList
[PathCount
] = NULL
;
282 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
285 UINT8 SectorBuffer
[SECTOR_SIZE
];
287 MBR_PARTITION_INFO
*MbrTable
;
288 BOOLEAN MbrTableFound
;
290 Volume
->HasBootCode
= FALSE
;
291 Volume
->OSIconName
= NULL
;
292 Volume
->OSName
= NULL
;
295 if (Volume
->BlockIO
== NULL
)
297 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
298 return; // our buffer is too small...
300 // look at the boot sector (this is used for both hard disks and El Torito images!)
301 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
302 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
303 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
304 if (!EFI_ERROR(Status
)) {
306 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
308 Volume
->HasBootCode
= TRUE
;
311 // detect specific boot codes
312 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
313 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
314 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
315 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
316 Volume
->HasBootCode
= TRUE
;
317 Volume
->OSIconName
= L
"linux";
318 Volume
->OSName
= L
"Linux";
320 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
321 Volume
->HasBootCode
= TRUE
;
322 Volume
->OSIconName
= L
"grub,linux";
323 Volume
->OSName
= L
"Linux";
325 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
326 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
327 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
328 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
329 Volume
->HasBootCode
= TRUE
;
330 Volume
->OSIconName
= L
"freebsd";
331 Volume
->OSName
= L
"FreeBSD";
333 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
334 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
335 Volume
->HasBootCode
= TRUE
;
336 Volume
->OSIconName
= L
"openbsd";
337 Volume
->OSName
= L
"OpenBSD";
339 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
340 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
341 Volume
->HasBootCode
= TRUE
;
342 Volume
->OSIconName
= L
"netbsd";
343 Volume
->OSName
= L
"NetBSD";
345 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
346 Volume
->HasBootCode
= TRUE
;
347 Volume
->OSIconName
= L
"win";
348 Volume
->OSName
= L
"Windows";
350 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
351 Volume
->HasBootCode
= TRUE
;
352 Volume
->OSIconName
= L
"winvista,win";
353 Volume
->OSName
= L
"Windows";
355 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
356 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
357 Volume
->HasBootCode
= TRUE
;
358 Volume
->OSIconName
= L
"freedos";
359 Volume
->OSName
= L
"FreeDOS";
361 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
362 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
363 Volume
->HasBootCode
= TRUE
;
364 Volume
->OSIconName
= L
"ecomstation";
365 Volume
->OSName
= L
"eComStation";
367 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
368 Volume
->HasBootCode
= TRUE
;
369 Volume
->OSIconName
= L
"beos";
370 Volume
->OSName
= L
"BeOS";
372 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
373 Volume
->HasBootCode
= TRUE
;
374 Volume
->OSIconName
= L
"zeta,beos";
375 Volume
->OSName
= L
"ZETA";
377 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
378 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
379 Volume
->HasBootCode
= TRUE
;
380 Volume
->OSIconName
= L
"haiku,beos";
381 Volume
->OSName
= L
"Haiku";
385 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
386 // need to fix AddLegacyEntry in main.c.
389 Print(L
" Result of bootcode detection: %s %s (%s)\n",
390 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
391 Volume
->OSName
, Volume
->OSIconName
);
394 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0) // dummy FAT boot sector
395 Volume
->HasBootCode
= FALSE
;
397 // check for MBR partition table
398 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
399 MbrTableFound
= FALSE
;
400 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
401 for (i
= 0; i
< 4; i
++)
402 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
403 MbrTableFound
= TRUE
;
404 for (i
= 0; i
< 4; i
++)
405 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
406 MbrTableFound
= FALSE
;
408 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
409 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
415 CheckError(Status
, L
"while reading boot sector");
420 // default volume icon based on disk kind
421 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
423 switch (Volume
->DiskKind
) {
424 case DISK_KIND_INTERNAL
:
425 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
427 case DISK_KIND_EXTERNAL
:
428 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
430 case DISK_KIND_OPTICAL
:
431 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
436 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
439 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
440 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
441 EFI_HANDLE WholeDiskHandle
;
443 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
447 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
449 if (Volume
->DevicePath
!= NULL
) {
450 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
452 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
457 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
460 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
461 if (EFI_ERROR(Status
)) {
462 Volume
->BlockIO
= NULL
;
463 Print(L
"Warning: Can't get BlockIO protocol.\n");
465 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
466 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
469 // scan for bootcode and MBR table
471 ScanVolumeBootcode(Volume
, &Bootable
);
473 // detect device type
474 DevicePath
= Volume
->DevicePath
;
475 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
476 NextDevicePath
= NextDevicePathNode(DevicePath
);
478 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
479 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
480 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
481 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
482 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
483 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
484 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
485 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
486 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
490 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
491 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
492 // TODO: also check for Boot Camp GUID
493 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
496 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
497 // make a device path for the whole device
498 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
499 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
500 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
501 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
503 // get the handle for that path
504 RemainingDevicePath
= DiskDevicePath
;
505 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
506 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
507 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
508 FreePool(DiskDevicePath
);
510 if (!EFI_ERROR(Status
)) {
511 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
513 // get the device path for later
514 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
515 if (!EFI_ERROR(Status
)) {
516 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
519 // look at the BlockIO protocol
520 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
521 if (!EFI_ERROR(Status
)) {
523 // check the media block size
524 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
525 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
528 Volume
->WholeDiskBlockIO
= NULL
;
529 //CheckError(Status, L"from HandleProtocol");
532 // CheckError(Status, L"from LocateDevicePath");
535 DevicePath
= NextDevicePath
;
540 if (Volume
->HasBootCode
)
541 Print(L
" Volume considered non-bootable, but boot code is present\n");
543 Volume
->HasBootCode
= FALSE
;
546 // default volume icon based on disk kind
547 ScanVolumeDefaultIcon(Volume
);
549 // open the root directory of the volume
550 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
551 if (Volume
->RootDir
== NULL
) {
556 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
557 if (FileSystemInfoPtr
!= NULL
) {
558 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
559 FreePool(FileSystemInfoPtr
);
562 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
563 // - name from bytes 3 to 10 of the boot sector
564 // - partition number
565 // - name derived from file system type or partition type
567 // get custom volume icon if present
568 if (FileExists(Volume
->RootDir
, L
".VolumeIcon.icns"))
569 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, L
".VolumeIcon.icns", 32);
572 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
575 REFIT_VOLUME
*Volume
;
576 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
578 UINTN LogicalPartitionIndex
= 4;
579 UINT8 SectorBuffer
[512];
581 MBR_PARTITION_INFO
*EMbrTable
;
583 ExtBase
= MbrEntry
->StartLBA
;
585 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
587 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
588 WholeDiskVolume
->BlockIO
,
589 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
590 ExtCurrent
, 512, SectorBuffer
);
591 if (EFI_ERROR(Status
))
593 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
595 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
597 // scan logical partitions in this EMBR
599 for (i
= 0; i
< 4; i
++) {
600 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
601 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
603 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
604 // set next ExtCurrent
605 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
609 // found a logical partition
610 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
611 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
612 Volume
->IsMbrPartition
= TRUE
;
613 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
614 Volume
->VolName
= PoolPrint(L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
615 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
616 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
617 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
620 ScanVolumeBootcode(Volume
, &Bootable
);
622 Volume
->HasBootCode
= FALSE
;
624 ScanVolumeDefaultIcon(Volume
);
626 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
633 VOID
ScanVolumes(VOID
)
636 UINTN HandleCount
= 0;
639 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
640 UINTN VolumeIndex
, VolumeIndex2
;
641 MBR_PARTITION_INFO
*MbrTable
;
642 UINTN PartitionIndex
;
643 UINT8
*SectorBuffer1
, *SectorBuffer2
;
650 // get all filesystem handles
651 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
652 // was: &FileSystemProtocol
653 if (Status
== EFI_NOT_FOUND
)
654 return; // no filesystems. strange, but true...
655 if (CheckError(Status
, L
"while listing all file systems"))
658 // first pass: collect information about all handles
659 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
660 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
661 Volume
->DeviceHandle
= Handles
[HandleIndex
];
664 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
666 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
671 if (SelfVolume
== NULL
)
672 Print(L
"WARNING: SelfVolume not found");
674 // second pass: relate partitions and whole disk devices
675 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
676 Volume
= Volumes
[VolumeIndex
];
677 // check MBR partition table for extended partitions
678 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
679 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
680 Volume
->MbrPartitionTable
!= NULL
) {
681 MbrTable
= Volume
->MbrPartitionTable
;
682 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
683 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
684 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
689 // search for corresponding whole disk volume entry
690 WholeDiskVolume
= NULL
;
691 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
692 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
693 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
694 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
695 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
696 WholeDiskVolume
= Volumes
[VolumeIndex2
];
700 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
701 // check if this volume is one of the partitions in the table
702 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
703 SectorBuffer1
= AllocatePool(512);
704 SectorBuffer2
= AllocatePool(512);
705 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
707 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
710 // compare boot sector read through offset vs. directly
711 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
712 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
713 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
714 if (EFI_ERROR(Status
))
716 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
717 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
718 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
719 if (EFI_ERROR(Status
))
721 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
724 for (i
= 0; i
< 512; i
++)
725 SectorSum
+= SectorBuffer1
[i
];
726 if (SectorSum
< 1000)
729 // TODO: mark entry as non-bootable if it is an extended partition
731 // now we're reasonably sure the association is correct...
732 Volume
->IsMbrPartition
= TRUE
;
733 Volume
->MbrPartitionIndex
= PartitionIndex
;
734 if (Volume
->VolName
== NULL
)
735 Volume
->VolName
= PoolPrint(L
"Partition %d", PartitionIndex
+ 1);
739 FreePool(SectorBuffer1
);
740 FreePool(SectorBuffer2
);
744 } /* VOID ScanVolumes() */
746 static VOID
UninitVolumes(VOID
)
748 REFIT_VOLUME
*Volume
;
751 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
752 Volume
= Volumes
[VolumeIndex
];
754 if (Volume
->RootDir
!= NULL
) {
755 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
756 Volume
->RootDir
= NULL
;
759 Volume
->DeviceHandle
= NULL
;
760 Volume
->BlockIO
= NULL
;
761 Volume
->WholeDiskBlockIO
= NULL
;
765 VOID
ReinitVolumes(VOID
)
768 REFIT_VOLUME
*Volume
;
770 EFI_DEVICE_PATH
*RemainingDevicePath
;
771 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
773 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
774 Volume
= Volumes
[VolumeIndex
];
776 if (Volume
->DevicePath
!= NULL
) {
777 // get the handle for that path
778 RemainingDevicePath
= Volume
->DevicePath
;
779 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
781 if (!EFI_ERROR(Status
)) {
782 Volume
->DeviceHandle
= DeviceHandle
;
784 // get the root directory
785 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
788 CheckError(Status
, L
"from LocateDevicePath");
791 if (Volume
->WholeDiskDevicePath
!= NULL
) {
792 // get the handle for that path
793 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
794 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
796 if (!EFI_ERROR(Status
)) {
797 // get the BlockIO protocol
798 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
799 if (EFI_ERROR(Status
)) {
800 Volume
->WholeDiskBlockIO
= NULL
;
801 CheckError(Status
, L
"from HandleProtocol");
804 CheckError(Status
, L
"from LocateDevicePath");
810 // file and dir functions
813 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
816 EFI_FILE_HANDLE TestFile
;
818 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
819 if (Status
== EFI_SUCCESS
) {
820 refit_call1_wrapper(TestFile
->Close
, TestFile
);
826 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
830 UINTN LastBufferSize
, BufferSize
;
835 // free pointer from last call
836 if (*DirEntry
!= NULL
) {
841 // read next directory entry
842 LastBufferSize
= BufferSize
= 256;
843 Buffer
= AllocatePool(BufferSize
);
844 for (IterCount
= 0; ; IterCount
++) {
845 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
846 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
848 if (BufferSize
<= LastBufferSize
) {
849 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
850 BufferSize
= LastBufferSize
* 2;
853 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
856 Buffer
= ReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
857 LastBufferSize
= BufferSize
;
859 if (EFI_ERROR(Status
)) {
864 // check for end of listing
865 if (BufferSize
== 0) { // end of directory listing
870 // entry is ready to be returned
871 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
874 if (FilterMode
== 1) { // only return directories
875 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
877 } else if (FilterMode
== 2) { // only return files
878 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
880 } else // no filter or unknown filter -> return everything
887 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
889 if (RelativePath
== NULL
) {
890 DirIter
->LastStatus
= EFI_SUCCESS
;
891 DirIter
->DirHandle
= BaseDir
;
892 DirIter
->CloseDirHandle
= FALSE
;
894 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
895 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
897 DirIter
->LastFileInfo
= NULL
;
900 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
901 OUT EFI_FILE_INFO
**DirEntry
)
903 if (DirIter
->LastFileInfo
!= NULL
) {
904 FreePool(DirIter
->LastFileInfo
);
905 DirIter
->LastFileInfo
= NULL
;
908 if (EFI_ERROR(DirIter
->LastStatus
))
909 return FALSE
; // stop iteration
912 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
913 if (EFI_ERROR(DirIter
->LastStatus
))
915 if (DirIter
->LastFileInfo
== NULL
) // end of listing
917 if (FilePattern
!= NULL
) {
918 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
920 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, FilePattern
))
922 // else continue loop
927 *DirEntry
= DirIter
->LastFileInfo
;
931 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
933 if (DirIter
->LastFileInfo
!= NULL
) {
934 FreePool(DirIter
->LastFileInfo
);
935 DirIter
->LastFileInfo
= NULL
;
937 if (DirIter
->CloseDirHandle
)
938 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
939 return DirIter
->LastStatus
;
943 // file name manipulation
946 // Returns the filename portion (minus path name) of the
948 CHAR16
* Basename(IN CHAR16
*Path
)
956 for (i
= StrLen(Path
); i
> 0; i
--) {
957 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
967 VOID
ReplaceExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
971 for (i
= StrLen(Path
); i
>= 0; i
--) {
972 if (Path
[i
] == '.') {
976 if (Path
[i
] == '\\' || Path
[i
] == '/')
979 StrCat(Path
, Extension
);
983 // memory string search
986 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
992 BufferLength
-= SearchStringLength
;
993 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
994 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
1001 // Performs a case-insensitive search of BigStr for SmallStr.
1002 // Returns TRUE if found, FALSE if not.
1003 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
1004 CHAR16
*SmallCopy
, *BigCopy
;
1005 BOOLEAN Found
= FALSE
;
1006 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1008 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1009 SmallCopy
= StrDuplicate(SmallStr
);
1010 BigCopy
= StrDuplicate(BigStr
);
1013 SmallLen
= StrLen(SmallCopy
);
1014 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1015 while ((!Found
) && (StartPoint
< NumCompares
)) {
1016 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1018 FreePool(SmallCopy
);
1023 } // BOOLEAN StriSubCmp()
1025 // Merges two strings, creating a new one and returning a pointer to it.
1026 // If AddChar != 0, the specified character is placed between the two original
1027 // strings (unless the first string is NULL). The original input string
1028 // *First is de-allocated and replaced by the new merged string.
1029 // This is similar to StrCat, but safer and more flexible because
1030 // MergeStrings allocates memory that's the correct size for the
1031 // new merged string, so it can take a NULL *First and it cleans
1032 // up the old memory. It should *NOT* be used with a constant
1033 // *First, though....
1034 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1035 UINTN Length1
= 0, Length2
= 0;
1039 Length1
= StrLen(*First
);
1041 Length2
= StrLen(Second
);
1042 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1044 if (NewString
!= NULL
) {
1045 if (*First
!= NULL
) {
1046 StrCat(NewString
, *First
);
1048 NewString
[Length1
] = AddChar
;
1049 NewString
[Length1
+ 1] = 0;
1051 } // if (*First != NULL)
1053 StrCat(NewString
, Second
);
1057 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1059 } // static CHAR16* MergeStrings()
1061 // Takes an input pathname (*Path) and locates the final directory component
1062 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1063 // function returns the string 'foo'.
1064 // Assumes the pathname is separated with backslashes.
1065 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1066 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1067 CHAR16
*Found
= NULL
;
1069 PathLength
= StrLen(Path
);
1070 // Find start & end of target element
1071 for (i
= 0; i
< PathLength
; i
++) {
1072 if (Path
[i
] == '\\') {
1073 StartOfElement
= EndOfElement
;
1077 // Extract the target element
1078 if (EndOfElement
> 0) {
1079 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1083 if (EndOfElement
>= StartOfElement
) {
1084 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1085 Found
= StrDuplicate(&Path
[StartOfElement
]);
1087 Found
[CopyLength
] = 0;
1088 } // if (EndOfElement >= StartOfElement)
1089 } // if (EndOfElement > 0)
1091 } // CHAR16 *FindLastDirName
1093 // Returns the directory portion of a pathname. For instance,
1094 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1095 // string 'EFI\foo'.
1096 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1097 UINTN i
, LastBackslash
= 0;
1100 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1101 if (FullPath
[i
] == '\\')
1104 PathOnly
= StrDuplicate(FullPath
);
1105 PathOnly
[LastBackslash
] = 0;
1109 // Returns all the digits in the input string, including intervening
1110 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1111 // this function returns "3.3.4-7". If InString contains no digits,
1112 // the return value is NULL.
1113 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1114 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1115 CHAR16
*Found
= NULL
;
1117 InLength
= StartOfElement
= StrLen(InString
);
1118 // Find start & end of target element
1119 for (i
= 0; i
< InLength
; i
++) {
1120 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1121 if (StartOfElement
> i
)
1123 if (EndOfElement
< i
)
1127 // Extract the target element
1128 if (EndOfElement
> 0) {
1129 if (EndOfElement
>= StartOfElement
) {
1130 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1131 Found
= StrDuplicate(&InString
[StartOfElement
]);
1133 Found
[CopyLength
] = 0;
1134 } // if (EndOfElement >= StartOfElement)
1135 } // if (EndOfElement > 0)
1137 } // CHAR16 *FindNumbers()
1139 // Find the #Index element (numbered from 0) in a comma-delimited string
1141 // Returns the found element, or NULL if Index is out of range of InString
1143 CHAR16
*FindCommaDelimited(IN CHAR16
*InString
, IN UINTN Index
) {
1144 UINTN StartPos
= 0, CurPos
= 0;
1145 BOOLEAN Found
= FALSE
;
1146 CHAR16
*FoundString
= NULL
;
1148 if (InString
!= NULL
) {
1149 // After while() loop, StartPos marks start of item #Index
1150 while ((Index
> 0) && (CurPos
< StrLen(InString
))) {
1151 if (InString
[CurPos
] == L
',') {
1153 StartPos
= CurPos
+ 1;
1157 // After while() loop, CurPos is one past the end of the element
1158 while ((CurPos
< StrLen(InString
)) && (!Found
)) {
1159 if (InString
[CurPos
] == L
',')
1166 FoundString
= StrDuplicate(&InString
[StartPos
]);
1167 if (FoundString
!= NULL
)
1168 FoundString
[CurPos
- StartPos
] = 0;
1169 return (FoundString
);
1170 } // CHAR16 *FindCommaDelimited()