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 if (SelfVolume
!= NULL
&& SelfVolume
->RootDir
!= NULL
)
124 SelfRootDir
= SelfVolume
->RootDir
;
126 return FinishInitRefitLib();
129 static EFI_STATUS
FinishInitRefitLib(VOID
)
133 if (SelfRootDir
== NULL
) {
134 SelfRootDir
= LibOpenRoot(SelfLoadedImage
->DeviceHandle
);
135 if (SelfRootDir
== NULL
) {
136 CheckError(EFI_LOAD_ERROR
, L
"while (re)opening our installation volume");
137 return EFI_LOAD_ERROR
;
141 Status
= refit_call5_wrapper(SelfRootDir
->Open
, SelfRootDir
, &SelfDir
, SelfDirPath
, EFI_FILE_MODE_READ
, 0);
142 if (CheckFatalError(Status
, L
"while opening our installation directory"))
143 return EFI_LOAD_ERROR
;
152 VOID
CreateList(OUT VOID
***ListPtr
, OUT UINTN
*ElementCount
, IN UINTN InitialElementCount
)
156 *ElementCount
= InitialElementCount
;
157 if (*ElementCount
> 0) {
158 AllocateCount
= (*ElementCount
+ 7) & ~7; // next multiple of 8
159 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
165 VOID
AddListElement(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
, IN VOID
*NewElement
)
169 if ((*ElementCount
& 7) == 0) {
170 AllocateCount
= *ElementCount
+ 8;
171 if (*ElementCount
== 0)
172 *ListPtr
= AllocatePool(sizeof(VOID
*) * AllocateCount
);
174 *ListPtr
= ReallocatePool(*ListPtr
, sizeof(VOID
*) * (*ElementCount
), sizeof(VOID
*) * AllocateCount
);
176 (*ListPtr
)[*ElementCount
] = NewElement
;
178 } /* VOID AddListElement() */
180 VOID
FreeList(IN OUT VOID
***ListPtr
, IN OUT UINTN
*ElementCount
)
184 if (*ElementCount
> 0) {
185 for (i
= 0; i
< *ElementCount
; i
++) {
186 // TODO: call a user-provided routine for each element here
187 FreePool((*ListPtr
)[i
]);
194 // firmware device path discovery
197 static UINT8 LegacyLoaderMediaPathData
[] = {
198 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
199 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
200 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
202 static EFI_DEVICE_PATH
*LegacyLoaderMediaPath
= (EFI_DEVICE_PATH
*)LegacyLoaderMediaPathData
;
204 VOID
ExtractLegacyLoaderPaths(EFI_DEVICE_PATH
**PathList
, UINTN MaxPaths
, EFI_DEVICE_PATH
**HardcodedPathList
)
207 UINTN HandleCount
= 0;
208 UINTN HandleIndex
, HardcodedIndex
;
213 EFI_LOADED_IMAGE
*LoadedImage
;
214 EFI_DEVICE_PATH
*DevicePath
;
217 MaxPaths
--; // leave space for the terminating NULL pointer
219 // get all LoadedImage handles
220 Status
= LibLocateHandle(ByProtocol
, &LoadedImageProtocol
, NULL
,
221 &HandleCount
, &Handles
);
222 if (CheckError(Status
, L
"while listing LoadedImage handles")) {
223 if (HardcodedPathList
) {
224 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
225 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
227 PathList
[PathCount
] = NULL
;
230 for (HandleIndex
= 0; HandleIndex
< HandleCount
&& PathCount
< MaxPaths
; HandleIndex
++) {
231 Handle
= Handles
[HandleIndex
];
233 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Handle
, &LoadedImageProtocol
, (VOID
**) &LoadedImage
);
234 if (EFI_ERROR(Status
))
235 continue; // This can only happen if the firmware scewed up, ignore it.
237 Status
= refit_call3_wrapper(BS
->HandleProtocol
, LoadedImage
->DeviceHandle
, &DevicePathProtocol
, (VOID
**) &DevicePath
);
238 if (EFI_ERROR(Status
))
239 continue; // This happens, ignore it.
241 // Only grab memory range nodes
242 if (DevicePathType(DevicePath
) != HARDWARE_DEVICE_PATH
|| DevicePathSubType(DevicePath
) != HW_MEMMAP_DP
)
245 // Check if we have this device path in the list already
246 // WARNING: This assumes the first node in the device path is unique!
248 for (PathIndex
= 0; PathIndex
< PathCount
; PathIndex
++) {
249 if (DevicePathNodeLength(DevicePath
) != DevicePathNodeLength(PathList
[PathIndex
]))
251 if (CompareMem(DevicePath
, PathList
[PathIndex
], DevicePathNodeLength(DevicePath
)) == 0) {
259 PathList
[PathCount
++] = AppendDevicePath(DevicePath
, LegacyLoaderMediaPath
);
263 if (HardcodedPathList
) {
264 for (HardcodedIndex
= 0; HardcodedPathList
[HardcodedIndex
] && PathCount
< MaxPaths
; HardcodedIndex
++)
265 PathList
[PathCount
++] = HardcodedPathList
[HardcodedIndex
];
267 PathList
[PathCount
] = NULL
;
274 static VOID
ScanVolumeBootcode(IN OUT REFIT_VOLUME
*Volume
, OUT BOOLEAN
*Bootable
)
277 UINT8 SectorBuffer
[SECTOR_SIZE
];
279 MBR_PARTITION_INFO
*MbrTable
;
280 BOOLEAN MbrTableFound
;
282 Volume
->HasBootCode
= FALSE
;
283 Volume
->OSIconName
= NULL
;
284 Volume
->OSName
= NULL
;
287 if (Volume
->BlockIO
== NULL
)
289 if (Volume
->BlockIO
->Media
->BlockSize
> SECTOR_SIZE
)
290 return; // our buffer is too small...
292 // look at the boot sector (this is used for both hard disks and El Torito images!)
293 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
294 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
295 Volume
->BlockIOOffset
, SECTOR_SIZE
, SectorBuffer
);
296 if (!EFI_ERROR(Status
)) {
298 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55 && SectorBuffer
[0] != 0) {
300 Volume
->HasBootCode
= TRUE
;
303 // detect specific boot codes
304 if (CompareMem(SectorBuffer
+ 2, "LILO", 4) == 0 ||
305 CompareMem(SectorBuffer
+ 6, "LILO", 4) == 0 ||
306 CompareMem(SectorBuffer
+ 3, "SYSLINUX", 8) == 0 ||
307 FindMem(SectorBuffer
, SECTOR_SIZE
, "ISOLINUX", 8) >= 0) {
308 Volume
->HasBootCode
= TRUE
;
309 Volume
->OSIconName
= L
"linux";
310 Volume
->OSName
= L
"Linux";
312 } else if (FindMem(SectorBuffer
, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
313 Volume
->HasBootCode
= TRUE
;
314 Volume
->OSIconName
= L
"grub,linux";
315 Volume
->OSName
= L
"Linux";
317 } else if ((*((UINT32
*)(SectorBuffer
+ 502)) == 0 &&
318 *((UINT32
*)(SectorBuffer
+ 506)) == 50000 &&
319 *((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) ||
320 FindMem(SectorBuffer
, SECTOR_SIZE
, "Starting the BTX loader", 23) >= 0) {
321 Volume
->HasBootCode
= TRUE
;
322 Volume
->OSIconName
= L
"freebsd";
323 Volume
->OSName
= L
"FreeBSD";
325 } else if (FindMem(SectorBuffer
, 512, "!Loading", 8) >= 0 ||
326 FindMem(SectorBuffer
, SECTOR_SIZE
, "/cdboot\0/CDBOOT\0", 16) >= 0) {
327 Volume
->HasBootCode
= TRUE
;
328 Volume
->OSIconName
= L
"openbsd";
329 Volume
->OSName
= L
"OpenBSD";
331 } else if (FindMem(SectorBuffer
, 512, "Not a bootxx image", 18) >= 0 ||
332 *((UINT32
*)(SectorBuffer
+ 1028)) == 0x7886b6d1) {
333 Volume
->HasBootCode
= TRUE
;
334 Volume
->OSIconName
= L
"netbsd";
335 Volume
->OSName
= L
"NetBSD";
337 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "NTLDR", 5) >= 0) {
338 Volume
->HasBootCode
= TRUE
;
339 Volume
->OSIconName
= L
"win";
340 Volume
->OSName
= L
"Windows";
342 } else if (FindMem(SectorBuffer
, SECTOR_SIZE
, "BOOTMGR", 7) >= 0) {
343 Volume
->HasBootCode
= TRUE
;
344 Volume
->OSIconName
= L
"winvista,win";
345 Volume
->OSName
= L
"Windows";
347 } else if (FindMem(SectorBuffer
, 512, "CPUBOOT SYS", 11) >= 0 ||
348 FindMem(SectorBuffer
, 512, "KERNEL SYS", 11) >= 0) {
349 Volume
->HasBootCode
= TRUE
;
350 Volume
->OSIconName
= L
"freedos";
351 Volume
->OSName
= L
"FreeDOS";
353 } else if (FindMem(SectorBuffer
, 512, "OS2LDR", 6) >= 0 ||
354 FindMem(SectorBuffer
, 512, "OS2BOOT", 7) >= 0) {
355 Volume
->HasBootCode
= TRUE
;
356 Volume
->OSIconName
= L
"ecomstation";
357 Volume
->OSName
= L
"eComStation";
359 } else if (FindMem(SectorBuffer
, 512, "Be Boot Loader", 14) >= 0) {
360 Volume
->HasBootCode
= TRUE
;
361 Volume
->OSIconName
= L
"beos";
362 Volume
->OSName
= L
"BeOS";
364 } else if (FindMem(SectorBuffer
, 512, "yT Boot Loader", 14) >= 0) {
365 Volume
->HasBootCode
= TRUE
;
366 Volume
->OSIconName
= L
"zeta,beos";
367 Volume
->OSName
= L
"ZETA";
369 } else if (FindMem(SectorBuffer
, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
370 FindMem(SectorBuffer
, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
371 Volume
->HasBootCode
= TRUE
;
372 Volume
->OSIconName
= L
"haiku,beos";
373 Volume
->OSName
= L
"Haiku";
377 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
378 // need to fix AddLegacyEntry in main.c.
381 Print(L
" Result of bootcode detection: %s %s (%s)\n",
382 Volume
->HasBootCode
? L
"bootable" : L
"non-bootable",
383 Volume
->OSName
, Volume
->OSIconName
);
386 if (FindMem(SectorBuffer
, 512, "Non-system disk", 15) >= 0) // dummy FAT boot sector
387 Volume
->HasBootCode
= FALSE
;
389 // check for MBR partition table
390 if (*((UINT16
*)(SectorBuffer
+ 510)) == 0xaa55) {
391 MbrTableFound
= FALSE
;
392 MbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
393 for (i
= 0; i
< 4; i
++)
394 if (MbrTable
[i
].StartLBA
&& MbrTable
[i
].Size
)
395 MbrTableFound
= TRUE
;
396 for (i
= 0; i
< 4; i
++)
397 if (MbrTable
[i
].Flags
!= 0x00 && MbrTable
[i
].Flags
!= 0x80)
398 MbrTableFound
= FALSE
;
400 Volume
->MbrPartitionTable
= AllocatePool(4 * 16);
401 CopyMem(Volume
->MbrPartitionTable
, MbrTable
, 4 * 16);
407 CheckError(Status
, L
"while reading boot sector");
412 // default volume icon based on disk kind
413 static VOID
ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME
*Volume
)
415 switch (Volume
->DiskKind
) {
416 case DISK_KIND_INTERNAL
:
417 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
419 case DISK_KIND_EXTERNAL
:
420 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
422 case DISK_KIND_OPTICAL
:
423 Volume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
428 static VOID
ScanVolume(IN OUT REFIT_VOLUME
*Volume
)
431 EFI_DEVICE_PATH
*DevicePath
, *NextDevicePath
;
432 EFI_DEVICE_PATH
*DiskDevicePath
, *RemainingDevicePath
;
433 EFI_HANDLE WholeDiskHandle
;
435 EFI_FILE_SYSTEM_INFO
*FileSystemInfoPtr
;
439 Volume
->DevicePath
= DuplicateDevicePath(DevicePathFromHandle(Volume
->DeviceHandle
));
441 if (Volume
->DevicePath
!= NULL
) {
442 Print(L
"* %s\n", DevicePathToStr(Volume
->DevicePath
));
444 DumpHex(1, 0, DevicePathSize(Volume
->DevicePath
), Volume
->DevicePath
);
449 Volume
->DiskKind
= DISK_KIND_INTERNAL
; // default
452 Status
= refit_call3_wrapper(BS
->HandleProtocol
, Volume
->DeviceHandle
, &BlockIoProtocol
, (VOID
**) &(Volume
->BlockIO
));
453 if (EFI_ERROR(Status
)) {
454 Volume
->BlockIO
= NULL
;
455 Print(L
"Warning: Can't get BlockIO protocol.\n");
457 if (Volume
->BlockIO
->Media
->BlockSize
== 2048)
458 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
461 // scan for bootcode and MBR table
463 ScanVolumeBootcode(Volume
, &Bootable
);
465 // detect device type
466 DevicePath
= Volume
->DevicePath
;
467 while (DevicePath
!= NULL
&& !IsDevicePathEndType(DevicePath
)) {
468 NextDevicePath
= NextDevicePathNode(DevicePath
);
470 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
&&
471 (DevicePathSubType(DevicePath
) == MSG_USB_DP
||
472 DevicePathSubType(DevicePath
) == MSG_USB_CLASS_DP
||
473 DevicePathSubType(DevicePath
) == MSG_1394_DP
||
474 DevicePathSubType(DevicePath
) == MSG_FIBRECHANNEL_DP
))
475 Volume
->DiskKind
= DISK_KIND_EXTERNAL
; // USB/FireWire/FC device -> external
476 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&&
477 DevicePathSubType(DevicePath
) == MEDIA_CDROM_DP
) {
478 Volume
->DiskKind
= DISK_KIND_OPTICAL
; // El Torito entry -> optical disk
482 if (DevicePathType(DevicePath
) == MEDIA_DEVICE_PATH
&& DevicePathSubType(DevicePath
) == MEDIA_VENDOR_DP
) {
483 Volume
->IsAppleLegacy
= TRUE
; // legacy BIOS device entry
484 // TODO: also check for Boot Camp GUID
485 Bootable
= FALSE
; // this handle's BlockIO is just an alias for the whole device
488 if (DevicePathType(DevicePath
) == MESSAGING_DEVICE_PATH
) {
489 // make a device path for the whole device
490 PartialLength
= (UINT8
*)NextDevicePath
- (UINT8
*)(Volume
->DevicePath
);
491 DiskDevicePath
= (EFI_DEVICE_PATH
*)AllocatePool(PartialLength
+ sizeof(EFI_DEVICE_PATH
));
492 CopyMem(DiskDevicePath
, Volume
->DevicePath
, PartialLength
);
493 CopyMem((UINT8
*)DiskDevicePath
+ PartialLength
, EndDevicePath
, sizeof(EFI_DEVICE_PATH
));
495 // get the handle for that path
496 RemainingDevicePath
= DiskDevicePath
;
497 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
498 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
499 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
500 FreePool(DiskDevicePath
);
502 if (!EFI_ERROR(Status
)) {
503 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
505 // get the device path for later
506 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &DevicePathProtocol
, (VOID
**) &DiskDevicePath
);
507 if (!EFI_ERROR(Status
)) {
508 Volume
->WholeDiskDevicePath
= DuplicateDevicePath(DiskDevicePath
);
511 // look at the BlockIO protocol
512 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
513 if (!EFI_ERROR(Status
)) {
515 // check the media block size
516 if (Volume
->WholeDiskBlockIO
->Media
->BlockSize
== 2048)
517 Volume
->DiskKind
= DISK_KIND_OPTICAL
;
520 Volume
->WholeDiskBlockIO
= NULL
;
521 //CheckError(Status, L"from HandleProtocol");
524 // CheckError(Status, L"from LocateDevicePath");
527 DevicePath
= NextDevicePath
;
532 if (Volume
->HasBootCode
)
533 Print(L
" Volume considered non-bootable, but boot code is present\n");
535 Volume
->HasBootCode
= FALSE
;
538 // default volume icon based on disk kind
539 ScanVolumeDefaultIcon(Volume
);
541 // open the root directory of the volume
542 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
543 if (Volume
->RootDir
== NULL
) {
548 FileSystemInfoPtr
= LibFileSystemInfo(Volume
->RootDir
);
549 if (FileSystemInfoPtr
!= NULL
) {
550 Volume
->VolName
= StrDuplicate(FileSystemInfoPtr
->VolumeLabel
);
551 FreePool(FileSystemInfoPtr
);
554 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
555 // - name from bytes 3 to 10 of the boot sector
556 // - partition number
557 // - name derived from file system type or partition type
559 // get custom volume icon if present
560 if (FileExists(Volume
->RootDir
, L
".VolumeIcon.icns"))
561 Volume
->VolBadgeImage
= LoadIcns(Volume
->RootDir
, L
".VolumeIcon.icns", 32);
564 static VOID
ScanExtendedPartition(REFIT_VOLUME
*WholeDiskVolume
, MBR_PARTITION_INFO
*MbrEntry
)
567 REFIT_VOLUME
*Volume
;
568 UINT32 ExtBase
, ExtCurrent
, NextExtCurrent
;
570 UINTN LogicalPartitionIndex
= 4;
571 UINT8 SectorBuffer
[512];
573 MBR_PARTITION_INFO
*EMbrTable
;
575 ExtBase
= MbrEntry
->StartLBA
;
577 for (ExtCurrent
= ExtBase
; ExtCurrent
; ExtCurrent
= NextExtCurrent
) {
579 Status
= refit_call5_wrapper(WholeDiskVolume
->BlockIO
->ReadBlocks
,
580 WholeDiskVolume
->BlockIO
,
581 WholeDiskVolume
->BlockIO
->Media
->MediaId
,
582 ExtCurrent
, 512, SectorBuffer
);
583 if (EFI_ERROR(Status
))
585 if (*((UINT16
*)(SectorBuffer
+ 510)) != 0xaa55)
587 EMbrTable
= (MBR_PARTITION_INFO
*)(SectorBuffer
+ 446);
589 // scan logical partitions in this EMBR
591 for (i
= 0; i
< 4; i
++) {
592 if ((EMbrTable
[i
].Flags
!= 0x00 && EMbrTable
[i
].Flags
!= 0x80) ||
593 EMbrTable
[i
].StartLBA
== 0 || EMbrTable
[i
].Size
== 0)
595 if (IS_EXTENDED_PART_TYPE(EMbrTable
[i
].Type
)) {
596 // set next ExtCurrent
597 NextExtCurrent
= ExtBase
+ EMbrTable
[i
].StartLBA
;
601 // found a logical partition
602 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
603 Volume
->DiskKind
= WholeDiskVolume
->DiskKind
;
604 Volume
->IsMbrPartition
= TRUE
;
605 Volume
->MbrPartitionIndex
= LogicalPartitionIndex
++;
606 Volume
->VolName
= PoolPrint(L
"Partition %d", Volume
->MbrPartitionIndex
+ 1);
607 Volume
->BlockIO
= WholeDiskVolume
->BlockIO
;
608 Volume
->BlockIOOffset
= ExtCurrent
+ EMbrTable
[i
].StartLBA
;
609 Volume
->WholeDiskBlockIO
= WholeDiskVolume
->BlockIO
;
612 ScanVolumeBootcode(Volume
, &Bootable
);
614 Volume
->HasBootCode
= FALSE
;
616 ScanVolumeDefaultIcon(Volume
);
618 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
625 VOID
ScanVolumes(VOID
)
628 UINTN HandleCount
= 0;
631 REFIT_VOLUME
*Volume
, *WholeDiskVolume
;
632 UINTN VolumeIndex
, VolumeIndex2
;
633 MBR_PARTITION_INFO
*MbrTable
;
634 UINTN PartitionIndex
;
635 UINT8
*SectorBuffer1
, *SectorBuffer2
;
642 // get all filesystem handles
643 Status
= LibLocateHandle(ByProtocol
, &BlockIoProtocol
, NULL
, &HandleCount
, &Handles
);
644 // was: &FileSystemProtocol
645 if (Status
== EFI_NOT_FOUND
)
646 return; // no filesystems. strange, but true...
647 if (CheckError(Status
, L
"while listing all file systems"))
650 // first pass: collect information about all handles
651 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
652 Volume
= AllocateZeroPool(sizeof(REFIT_VOLUME
));
653 Volume
->DeviceHandle
= Handles
[HandleIndex
];
656 AddListElement((VOID
***) &Volumes
, &VolumesCount
, Volume
);
658 if (Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
)
663 if (SelfVolume
== NULL
)
664 Print(L
"WARNING: SelfVolume not found");
666 // second pass: relate partitions and whole disk devices
667 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
668 Volume
= Volumes
[VolumeIndex
];
669 // check MBR partition table for extended partitions
670 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
671 Volume
->BlockIO
== Volume
->WholeDiskBlockIO
&& Volume
->BlockIOOffset
== 0 &&
672 Volume
->MbrPartitionTable
!= NULL
) {
673 MbrTable
= Volume
->MbrPartitionTable
;
674 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
675 if (IS_EXTENDED_PART_TYPE(MbrTable
[PartitionIndex
].Type
)) {
676 ScanExtendedPartition(Volume
, MbrTable
+ PartitionIndex
);
681 // search for corresponding whole disk volume entry
682 WholeDiskVolume
= NULL
;
683 if (Volume
->BlockIO
!= NULL
&& Volume
->WholeDiskBlockIO
!= NULL
&&
684 Volume
->BlockIO
!= Volume
->WholeDiskBlockIO
) {
685 for (VolumeIndex2
= 0; VolumeIndex2
< VolumesCount
; VolumeIndex2
++) {
686 if (Volumes
[VolumeIndex2
]->BlockIO
== Volume
->WholeDiskBlockIO
&&
687 Volumes
[VolumeIndex2
]->BlockIOOffset
== 0)
688 WholeDiskVolume
= Volumes
[VolumeIndex2
];
692 if (WholeDiskVolume
!= NULL
&& WholeDiskVolume
->MbrPartitionTable
!= NULL
) {
693 // check if this volume is one of the partitions in the table
694 MbrTable
= WholeDiskVolume
->MbrPartitionTable
;
695 SectorBuffer1
= AllocatePool(512);
696 SectorBuffer2
= AllocatePool(512);
697 for (PartitionIndex
= 0; PartitionIndex
< 4; PartitionIndex
++) {
699 if ((UINT64
)(MbrTable
[PartitionIndex
].Size
) != Volume
->BlockIO
->Media
->LastBlock
+ 1)
702 // compare boot sector read through offset vs. directly
703 Status
= refit_call5_wrapper(Volume
->BlockIO
->ReadBlocks
,
704 Volume
->BlockIO
, Volume
->BlockIO
->Media
->MediaId
,
705 Volume
->BlockIOOffset
, 512, SectorBuffer1
);
706 if (EFI_ERROR(Status
))
708 Status
= refit_call5_wrapper(Volume
->WholeDiskBlockIO
->ReadBlocks
,
709 Volume
->WholeDiskBlockIO
, Volume
->WholeDiskBlockIO
->Media
->MediaId
,
710 MbrTable
[PartitionIndex
].StartLBA
, 512, SectorBuffer2
);
711 if (EFI_ERROR(Status
))
713 if (CompareMem(SectorBuffer1
, SectorBuffer2
, 512) != 0)
716 for (i
= 0; i
< 512; i
++)
717 SectorSum
+= SectorBuffer1
[i
];
718 if (SectorSum
< 1000)
721 // TODO: mark entry as non-bootable if it is an extended partition
723 // now we're reasonably sure the association is correct...
724 Volume
->IsMbrPartition
= TRUE
;
725 Volume
->MbrPartitionIndex
= PartitionIndex
;
726 if (Volume
->VolName
== NULL
)
727 Volume
->VolName
= PoolPrint(L
"Partition %d", PartitionIndex
+ 1);
731 FreePool(SectorBuffer1
);
732 FreePool(SectorBuffer2
);
736 } /* VOID ScanVolumes() */
738 static VOID
UninitVolumes(VOID
)
740 REFIT_VOLUME
*Volume
;
743 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
744 Volume
= Volumes
[VolumeIndex
];
746 if (Volume
->RootDir
!= NULL
) {
747 refit_call1_wrapper(Volume
->RootDir
->Close
, Volume
->RootDir
);
748 Volume
->RootDir
= NULL
;
751 Volume
->DeviceHandle
= NULL
;
752 Volume
->BlockIO
= NULL
;
753 Volume
->WholeDiskBlockIO
= NULL
;
757 VOID
ReinitVolumes(VOID
)
760 REFIT_VOLUME
*Volume
;
762 EFI_DEVICE_PATH
*RemainingDevicePath
;
763 EFI_HANDLE DeviceHandle
, WholeDiskHandle
;
765 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
766 Volume
= Volumes
[VolumeIndex
];
768 if (Volume
->DevicePath
!= NULL
) {
769 // get the handle for that path
770 RemainingDevicePath
= Volume
->DevicePath
;
771 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &DeviceHandle
);
773 if (!EFI_ERROR(Status
)) {
774 Volume
->DeviceHandle
= DeviceHandle
;
776 // get the root directory
777 Volume
->RootDir
= LibOpenRoot(Volume
->DeviceHandle
);
780 CheckError(Status
, L
"from LocateDevicePath");
783 if (Volume
->WholeDiskDevicePath
!= NULL
) {
784 // get the handle for that path
785 RemainingDevicePath
= Volume
->WholeDiskDevicePath
;
786 Status
= refit_call3_wrapper(BS
->LocateDevicePath
, &BlockIoProtocol
, &RemainingDevicePath
, &WholeDiskHandle
);
788 if (!EFI_ERROR(Status
)) {
789 // get the BlockIO protocol
790 Status
= refit_call3_wrapper(BS
->HandleProtocol
, WholeDiskHandle
, &BlockIoProtocol
, (VOID
**) &Volume
->WholeDiskBlockIO
);
791 if (EFI_ERROR(Status
)) {
792 Volume
->WholeDiskBlockIO
= NULL
;
793 CheckError(Status
, L
"from HandleProtocol");
796 CheckError(Status
, L
"from LocateDevicePath");
802 // file and dir functions
805 BOOLEAN
FileExists(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath
)
808 EFI_FILE_HANDLE TestFile
;
810 Status
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &TestFile
, RelativePath
, EFI_FILE_MODE_READ
, 0);
811 if (Status
== EFI_SUCCESS
) {
812 refit_call1_wrapper(TestFile
->Close
, TestFile
);
818 EFI_STATUS
DirNextEntry(IN EFI_FILE
*Directory
, IN OUT EFI_FILE_INFO
**DirEntry
, IN UINTN FilterMode
)
822 UINTN LastBufferSize
, BufferSize
;
827 // free pointer from last call
828 if (*DirEntry
!= NULL
) {
833 // read next directory entry
834 LastBufferSize
= BufferSize
= 256;
835 Buffer
= AllocatePool(BufferSize
);
836 for (IterCount
= 0; ; IterCount
++) {
837 Status
= refit_call3_wrapper(Directory
->Read
, Directory
, &BufferSize
, Buffer
);
838 if (Status
!= EFI_BUFFER_TOO_SMALL
|| IterCount
>= 4)
840 if (BufferSize
<= LastBufferSize
) {
841 Print(L
"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize
, LastBufferSize
, LastBufferSize
* 2);
842 BufferSize
= LastBufferSize
* 2;
845 Print(L
"Reallocating buffer from %d to %d\n", LastBufferSize
, BufferSize
);
848 Buffer
= ReallocatePool(Buffer
, LastBufferSize
, BufferSize
);
849 LastBufferSize
= BufferSize
;
851 if (EFI_ERROR(Status
)) {
856 // check for end of listing
857 if (BufferSize
== 0) { // end of directory listing
862 // entry is ready to be returned
863 *DirEntry
= (EFI_FILE_INFO
*)Buffer
;
866 if (FilterMode
== 1) { // only return directories
867 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
))
869 } else if (FilterMode
== 2) { // only return files
870 if (((*DirEntry
)->Attribute
& EFI_FILE_DIRECTORY
) == 0)
872 } else // no filter or unknown filter -> return everything
879 VOID
DirIterOpen(IN EFI_FILE
*BaseDir
, IN CHAR16
*RelativePath OPTIONAL
, OUT REFIT_DIR_ITER
*DirIter
)
881 if (RelativePath
== NULL
) {
882 DirIter
->LastStatus
= EFI_SUCCESS
;
883 DirIter
->DirHandle
= BaseDir
;
884 DirIter
->CloseDirHandle
= FALSE
;
886 DirIter
->LastStatus
= refit_call5_wrapper(BaseDir
->Open
, BaseDir
, &(DirIter
->DirHandle
), RelativePath
, EFI_FILE_MODE_READ
, 0);
887 DirIter
->CloseDirHandle
= EFI_ERROR(DirIter
->LastStatus
) ? FALSE
: TRUE
;
889 DirIter
->LastFileInfo
= NULL
;
892 BOOLEAN
DirIterNext(IN OUT REFIT_DIR_ITER
*DirIter
, IN UINTN FilterMode
, IN CHAR16
*FilePattern OPTIONAL
,
893 OUT EFI_FILE_INFO
**DirEntry
)
895 if (DirIter
->LastFileInfo
!= NULL
) {
896 FreePool(DirIter
->LastFileInfo
);
897 DirIter
->LastFileInfo
= NULL
;
900 if (EFI_ERROR(DirIter
->LastStatus
))
901 return FALSE
; // stop iteration
904 DirIter
->LastStatus
= DirNextEntry(DirIter
->DirHandle
, &(DirIter
->LastFileInfo
), FilterMode
);
905 if (EFI_ERROR(DirIter
->LastStatus
))
907 if (DirIter
->LastFileInfo
== NULL
) // end of listing
909 if (FilePattern
!= NULL
) {
910 if ((DirIter
->LastFileInfo
->Attribute
& EFI_FILE_DIRECTORY
))
912 if (MetaiMatch(DirIter
->LastFileInfo
->FileName
, FilePattern
))
914 // else continue loop
919 *DirEntry
= DirIter
->LastFileInfo
;
923 EFI_STATUS
DirIterClose(IN OUT REFIT_DIR_ITER
*DirIter
)
925 if (DirIter
->LastFileInfo
!= NULL
) {
926 FreePool(DirIter
->LastFileInfo
);
927 DirIter
->LastFileInfo
= NULL
;
929 if (DirIter
->CloseDirHandle
)
930 refit_call1_wrapper(DirIter
->DirHandle
->Close
, DirIter
->DirHandle
);
931 return DirIter
->LastStatus
;
935 // file name manipulation
938 // Returns the filename portion (minus path name) of the
940 CHAR16
* Basename(IN CHAR16
*Path
)
948 for (i
= StrLen(Path
); i
> 0; i
--) {
949 if (Path
[i
-1] == '\\' || Path
[i
-1] == '/') {
959 VOID
ReplaceExtension(IN OUT CHAR16
*Path
, IN CHAR16
*Extension
)
963 for (i
= StrLen(Path
); i
>= 0; i
--) {
964 if (Path
[i
] == '.') {
968 if (Path
[i
] == '\\' || Path
[i
] == '/')
971 StrCat(Path
, Extension
);
975 // memory string search
978 INTN
FindMem(IN VOID
*Buffer
, IN UINTN BufferLength
, IN VOID
*SearchString
, IN UINTN SearchStringLength
)
984 BufferLength
-= SearchStringLength
;
985 for (Offset
= 0; Offset
< BufferLength
; Offset
++, BufferPtr
++) {
986 if (CompareMem(BufferPtr
, SearchString
, SearchStringLength
) == 0)
993 // Performs a case-insensitive search of BigStr for SmallStr.
994 // Returns TRUE if found, FALSE if not.
995 BOOLEAN
StriSubCmp(IN CHAR16
*SmallStr
, IN CHAR16
*BigStr
) {
996 CHAR16
*SmallCopy
, *BigCopy
;
997 BOOLEAN Found
= FALSE
;
998 UINTN StartPoint
= 0, NumCompares
= 0, SmallLen
= 0;
1000 if ((SmallStr
!= NULL
) && (BigStr
!= NULL
) && (StrLen(BigStr
) >= StrLen(SmallStr
))) {
1001 SmallCopy
= StrDuplicate(SmallStr
);
1002 BigCopy
= StrDuplicate(BigStr
);
1005 SmallLen
= StrLen(SmallCopy
);
1006 NumCompares
= StrLen(BigCopy
) - SmallLen
+ 1;
1007 while ((!Found
) && (StartPoint
< NumCompares
)) {
1008 Found
= (StrnCmp(SmallCopy
, &BigCopy
[StartPoint
++], SmallLen
) == 0);
1010 FreePool(SmallCopy
);
1015 } // BOOLEAN StriSubCmp()
1017 // Merges two strings, creating a new one and returning a pointer to it.
1018 // If AddChar != 0, the specified character is placed between the two original
1019 // strings (unless the first string is NULL). The original input string
1020 // *First is de-allocated and replaced by the new merged string.
1021 // This is similar to StrCat, but safer and more flexible because
1022 // MergeStrings allocates memory that's the correct size for the
1023 // new merged string, so it can take a NULL *First and it cleans
1024 // up the old memory. It should *NOT* be used with a constant
1025 // *First, though....
1026 VOID
MergeStrings(IN OUT CHAR16
**First
, IN CHAR16
*Second
, CHAR16 AddChar
) {
1027 UINTN Length1
= 0, Length2
= 0;
1031 Length1
= StrLen(*First
);
1033 Length2
= StrLen(Second
);
1034 NewString
= AllocatePool(sizeof(CHAR16
) * (Length1
+ Length2
+ 2));
1036 if (NewString
!= NULL
) {
1037 if (*First
!= NULL
) {
1038 StrCat(NewString
, *First
);
1040 NewString
[Length1
] = AddChar
;
1041 NewString
[Length1
+ 1] = 0;
1043 } // if (First != NULL)
1045 StrCat(NewString
, Second
);
1049 Print(L
"Error! Unable to allocate memory in MergeStrings()!\n");
1051 } // static CHAR16* MergeStrings()
1053 // Takes an input pathname (*Path) and locates the final directory component
1054 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1055 // function returns the string 'foo'.
1056 // Assumes the pathname is separated with backslashes.
1057 CHAR16
*FindLastDirName(IN CHAR16
*Path
) {
1058 UINTN i
, StartOfElement
= 0, EndOfElement
= 0, PathLength
, CopyLength
;
1059 CHAR16
*Found
= NULL
;
1061 PathLength
= StrLen(Path
);
1062 // Find start & end of target element
1063 for (i
= 0; i
< PathLength
; i
++) {
1064 if (Path
[i
] == '\\') {
1065 StartOfElement
= EndOfElement
;
1069 // Extract the target element
1070 if (EndOfElement
> 0) {
1071 while ((StartOfElement
< PathLength
) && (Path
[StartOfElement
] == '\\')) {
1075 if (EndOfElement
>= StartOfElement
) {
1076 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1077 Found
= StrDuplicate(&Path
[StartOfElement
]);
1079 Found
[CopyLength
] = 0;
1080 } // if (EndOfElement >= StartOfElement)
1081 } // if (EndOfElement > 0)
1083 } // CHAR16 *FindLastDirName
1085 // Returns the directory portion of a pathname. For instance,
1086 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1087 // string 'EFI\foo'.
1088 CHAR16
*FindPath(IN CHAR16
* FullPath
) {
1089 UINTN i
, LastBackslash
= 0;
1092 for (i
= 0; i
< StrLen(FullPath
); i
++) {
1093 if (FullPath
[i
] == '\\')
1096 PathOnly
= StrDuplicate(FullPath
);
1097 PathOnly
[LastBackslash
] = 0;
1101 // Returns all the digits in the input string, including intervening
1102 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1103 // this function returns "3.3.4-7". If InString contains no digits,
1104 // the return value is NULL.
1105 CHAR16
*FindNumbers(IN CHAR16
*InString
) {
1106 UINTN i
, StartOfElement
, EndOfElement
= 0, InLength
, CopyLength
;
1107 CHAR16
*Found
= NULL
;
1109 InLength
= StartOfElement
= StrLen(InString
);
1110 // Find start & end of target element
1111 for (i
= 0; i
< InLength
; i
++) {
1112 if ((InString
[i
] >= '0') && (InString
[i
] <= '9')) {
1113 if (StartOfElement
> i
)
1115 if (EndOfElement
< i
)
1119 // Extract the target element
1120 if (EndOfElement
> 0) {
1121 if (EndOfElement
>= StartOfElement
) {
1122 CopyLength
= EndOfElement
- StartOfElement
+ 1;
1123 Found
= StrDuplicate(&InString
[StartOfElement
]);
1125 Found
[CopyLength
] = 0;
1126 } // if (EndOfElement >= StartOfElement)
1127 } // if (EndOfElement > 0)
1129 } // CHAR16 *FindNumbers()