-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.c
1974 lines (1743 loc) · 75.9 KB
/
lib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* refind/lib.c
* General library functions
*
* Copyright (c) 2006-2009 Christoph Pfisterer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Christoph Pfisterer nor the names of the
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Modifications copyright (c) 2012-2024 Roderick W. Smith
*
* Modifications distributed under the terms of the GNU General Public
* License (GPL) version 3 (GPLv3), or (at your option) any later version.
*
*/
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma pack(0)
#include "global.h"
#include "lib.h"
#include "icns.h"
#include "screen.h"
#include "../include/refit_call_wrapper.h"
#include "../include/RemovableMedia.h"
#include "gpt.h"
#include "config.h"
#include "driver_support.h"
#include "log.h"
#include "mystrings.h"
#ifdef __MAKEWITH_GNUEFI
#define EfiReallocatePool ReallocatePool
#else
#define LibLocateHandle gBS->LocateHandleBuffer
#define DevicePathProtocol gEfiDevicePathProtocolGuid
#define BlockIoProtocol gEfiBlockIoProtocolGuid
#define LibFileSystemInfo EfiLibFileSystemInfo
#define LibOpenRoot EfiLibOpenRoot
EFI_DEVICE_PATH EndDevicePath[] = {
{END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
};
#endif
// "Magic" signatures for various filesystems
#define FAT_MAGIC 0xAA55
#define EXT2_SUPER_MAGIC 0xEF53
#define HFSPLUS_MAGIC1 0x2B48
#define HFSPLUS_MAGIC2 0x5848
#define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
#define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
#define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
#define BTRFS_SIGNATURE "_BHRfS_M"
#define XFS_SIGNATURE "XFSB"
#define JFS_SIGNATURE "JFS1"
#define NTFS_SIGNATURE "NTFS "
#define FAT12_SIGNATURE "FAT12 "
#define FAT16_SIGNATURE "FAT16 "
#define FAT32_SIGNATURE "FAT32 "
#if defined (EFIX64)
EFI_GUID gFreedesktopRootGuid = { 0x4f68bce3, 0xe8cd, 0x4db1, { 0x96, 0xe7, 0xfb, 0xca, 0xf9, 0x84, 0xb7, 0x09 }};
#elif defined (EFI32)
EFI_GUID gFreedesktopRootGuid = { 0x44479540, 0xf297, 0x41b2, { 0x9a, 0xf7, 0xd1, 0x31, 0xd5, 0xf0, 0x45, 0x8a }};
#elif defined (EFIAARCH64)
EFI_GUID gFreedesktopRootGuid = { 0xb921b045, 0x1df0, 0x41c3, { 0xaf, 0x44, 0x4c, 0x6f, 0x28, 0x0d, 0x3f, 0xae }};
#else
// Below is GUID for ARM32
EFI_GUID gFreedesktopRootGuid = { 0x69dad710, 0x2ce4, 0x4e3c, { 0xb1, 0x6c, 0x21, 0xa1, 0xd4, 0x9a, 0xbe, 0xd3 }};
#endif
// variables
EFI_HANDLE SelfImageHandle;
EFI_LOADED_IMAGE *SelfLoadedImage;
EFI_FILE_PROTOCOL *SelfRootDir;
EFI_FILE_PROTOCOL *SelfDir;
CHAR16 *SelfDirPath;
REFIT_VOLUME *SelfVolume = NULL;
REFIT_VOLUME **Volumes = NULL;
UINTN VolumesCount = 0;
extern EFI_GUID RefindGuid;
EFI_FILE_PROTOCOL *gVarsDir = NULL;
// Maximum size for disk sectors
#define SECTOR_SIZE 4096
// Number of bytes to read from a partition to determine its filesystem type
// and identify its boot loader, and hence probable BIOS-mode OS installation
#define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
//
// Pathname manipulations
//
// Converts forward slashes to backslashes, removes duplicate slashes, and
// removes slashes from both the start and end of the pathname.
// Necessary because some (buggy?) EFI implementations produce "\/" strings
// in pathnames, because some user inputs can produce duplicate directory
// separators, and because we want consistent start and end slashes for
// directory comparisons. A special case: If the PathName refers to root,
// but is non-empty, return "\", since some firmware implementations flake
// out if this isn't present.
VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
UINTN Source = 0, Dest = 0;
if ((PathName == NULL) || (PathName[0] == '\0'))
return;
while (PathName[Source] != '\0') {
if ((PathName[Source] == L'/') || (PathName[Source] == L'\\')) {
if (Dest == 0) { // Skip slash if to first position
Source++;
} else {
PathName[Dest] = L'\\';
do { // Skip subsequent slashes
Source++;
} while ((PathName[Source] == L'/') || (PathName[Source] == L'\\'));
Dest++;
} // if/else
} else { // Regular character; copy it straight....
PathName[Dest] = PathName[Source];
Source++;
Dest++;
} // if/else
} // while()
if ((Dest > 0) && (PathName[Dest - 1] == L'\\'))
Dest--;
PathName[Dest] = L'\0';
if (PathName[0] == L'\0') {
PathName[0] = L'\\';
PathName[1] = L'\0';
}
} // CleanUpPathNameSlashes()
// Splits an EFI device path into device and filename components. For instance, if InString is
// PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
// this function will truncate that input to
// PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
// and return bzImage-3.5.1.efi as its return value.
// It does this by searching for the last ")" character in InString, copying everything
// after that string (after some cleanup) as the return value, and truncating the original
// input value.
// If InString contains no ")" character, this function leaves the original input string
// unmodified and also returns that string. If InString is NULL, this function returns NULL.
CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
INTN i;
CHAR16 *FileName = NULL;
BOOLEAN Found = FALSE;
if (InString != NULL) {
i = StrLen(InString) - 1;
while ((i >= 0) && (!Found)) {
if (InString[i] == L')') {
Found = TRUE;
FileName = StrDuplicate(&InString[i + 1]);
CleanUpPathNameSlashes(FileName);
InString[i + 1] = '\0';
} // if
i--;
} // while
if (FileName == NULL)
FileName = StrDuplicate(InString);
} // if
return FileName;
} // static CHAR16* SplitDeviceString()
//
// Library initialization and de-initialization
//
static EFI_STATUS FinishInitRefitLib(VOID)
{
EFI_STATUS Status;
if (SelfRootDir == NULL) {
SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
if (SelfRootDir == NULL) {
CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
return EFI_LOAD_ERROR;
}
}
Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
if (CheckFatalError(Status, L"while opening our installation directory"))
return EFI_LOAD_ERROR;
return EFI_SUCCESS;
}
EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
{
EFI_STATUS Status;
CHAR16 *DevicePathAsString, *Temp = NULL;
SelfImageHandle = ImageHandle;
Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
return EFI_LOAD_ERROR;
// find the current directory
DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
GlobalConfig.SelfDevicePath = FileDevicePath(SelfLoadedImage->DeviceHandle, DevicePathAsString);
CleanUpPathNameSlashes(DevicePathAsString);
MyFreePool(SelfDirPath);
Temp = FindPath(DevicePathAsString);
SelfDirPath = SplitDeviceString(Temp);
MyFreePool(DevicePathAsString);
MyFreePool(Temp);
return FinishInitRefitLib();
}
static VOID UninitVolumes(VOID)
{
REFIT_VOLUME *Volume;
UINTN VolumeIndex;
for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
Volume = Volumes[VolumeIndex];
if (Volume->RootDir != NULL) {
refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
Volume->RootDir = NULL;
}
Volume->DeviceHandle = NULL;
Volume->BlockIO = NULL;
Volume->WholeDiskBlockIO = NULL;
}
} /* VOID UninitVolumes() */
VOID ReinitVolumes(VOID)
{
EFI_STATUS Status;
REFIT_VOLUME *Volume;
UINTN VolumeIndex;
EFI_DEVICE_PATH *RemainingDevicePath;
EFI_HANDLE DeviceHandle, WholeDiskHandle;
for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
Volume = Volumes[VolumeIndex];
if (Volume->DevicePath != NULL) {
// get the handle for that path
RemainingDevicePath = Volume->DevicePath;
Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
if (EFI_ERROR(Status)) {
CheckError(Status, L"from LocateDevicePath");
} else {
Volume->DeviceHandle = DeviceHandle;
// get the root directory
Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
}
}
if (Volume->WholeDiskDevicePath != NULL) {
// get the handle for that path
RemainingDevicePath = Volume->WholeDiskDevicePath;
Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
if (!EFI_ERROR(Status)) {
// get the BlockIO protocol
Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol,
(VOID **) &Volume->WholeDiskBlockIO);
if (EFI_ERROR(Status)) {
Volume->WholeDiskBlockIO = NULL;
CheckError(Status, L"from HandleProtocol");
}
} else
CheckError(Status, L"from LocateDevicePath");
}
}
} /* VOID ReinitVolumes(VOID) */
// called before running external programs to close open file handles
VOID UninitRefitLib(VOID)
{
// Closing the log file is unnecessary on most systems; however, at
// least one I own (with an ASRock FM2A88M Extreme 4+ motherboard)
// produces 0-length log files if the file is not closed prior to
// launching a follow-on program. Thus, take care of this here....
// EXCEPT on Tow-Boot, where stopping logging can cause the system
// to crash!
if (StrCmp(ST->FirmwareVendor, L"Das U-Boot") != 0) {
StopLogging();
}
// This piece of code was made to correspond to weirdness in ReinitRefitLib().
// See the comment on it there.
if(SelfRootDir == SelfVolume->RootDir)
SelfRootDir=0;
UninitVolumes();
if (SelfDir != NULL) {
refit_call1_wrapper(SelfDir->Close, SelfDir);
SelfDir = NULL;
}
if (SelfRootDir != NULL) {
refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
SelfRootDir = NULL;
}
} /* VOID UninitRefitLib() */
// called after running external programs to re-open file handles
EFI_STATUS ReinitRefitLib(VOID)
{
EFI_STATUS Status;
ReinitVolumes();
if ((ST->Hdr.Revision >> 16) == 1) {
// Below two lines were in rEFIt, but seem to cause system crashes or
// reboots when launching OSes after returning from programs on most
// systems. OTOH, my Mac Mini produces errors about "(re)opening our
// installation volume" (see the next function) when returning from
// programs when these two lines are removed, and it often crashes
// when returning from a program or when launching a second program
// with these lines removed. Therefore, the preceding if() statement
// executes these lines only on EFIs with a major version number of 1
// (which Macs have) and not with 2 (which UEFI PCs have). My selection
// of hardware on which to test is limited, though, so this may be the
// wrong test, or there may be a better way to fix this problem.
// TODO: Figure out cause of above weirdness and fix it more
// reliably!
if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
SelfRootDir = SelfVolume->RootDir;
} // if
Status = FinishInitRefitLib();
if (EFI_ERROR(Status)) {
// if Status shows an error, we may not be able to re-open
// the log file, so disable logging to prevent a subsequent
// hang or other problem....
GlobalConfig.LogLevel = 0;
} else {
StartLogging(TRUE);
}
return Status;
}
//
// EFI variable read and write functions
//
// Create a directory for holding the rEFInd variables, if they're stored on
// disk. This will be in the rEFInd install directory if possible, or on the
// first ESP that rEFInd can identify if not (typically, this means rEFInd is
// on a read-only filesystem, such as HFS+ on a Mac). If neither location can
// be used, sets GlobalConfig.UseNvram to TRUE. Sets the pointer to the
// directory in the file-global gVarsDir variable and returns the success of
// the operation.
EFI_STATUS CreateVarsDir(VOID) {
EFI_STATUS Status = EFI_SUCCESS;
EFI_FILE_HANDLE EspRootDir;
if (gVarsDir == NULL) {
LOG(1, LOG_LINE_NORMAL, L"Trying to create a 'vars' directory in which to hold variables");
Status = refit_call5_wrapper(SelfDir->Open, SelfDir, &gVarsDir, L"vars",
EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE,
EFI_FILE_DIRECTORY);
if (EFI_ERROR(Status)) {
Status = egFindESP(&EspRootDir);
if (Status == EFI_SUCCESS) {
LOG(1, LOG_LINE_NORMAL,
L"Trying to create a 'refind-vars' directory on the ESP in which to hold variables");
Status = refit_call5_wrapper(EspRootDir->Open, EspRootDir, &gVarsDir, L"refind-vars",
EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE,
EFI_FILE_DIRECTORY);
}
}
}
if (EFI_ERROR(Status)) {
GlobalConfig.UseNvram = TRUE;
LOG(1, LOG_LINE_NORMAL, L"Unable to create a directory in which to hold variables; error %d", Status);
LOG(1, LOG_LINE_NORMAL, L"Falling back to NVRAM-based storage");
}
return Status;
} // EFI_STATUS FindVarsDir()
// Retrieve a raw EFI variable, either from NVRAM or from a disk file under
// rEFInd's "vars" subdirectory, depending on GlobalConfig.UseNvram.
// Returns EFI status
EFI_STATUS EfivarGetRaw(IN EFI_GUID *vendor, IN CHAR16 *name, OUT CHAR8 **buffer, OUT UINTN *size OPTIONAL) {
UINT8 *buf = NULL;
UINTN l;
EFI_STATUS Status;
BOOLEAN ReadFromNvram = TRUE;
if ((GlobalConfig.UseNvram == FALSE) && GuidsAreEqual(vendor, &RefindGuid)) {
ReadFromNvram = FALSE;
}
LOG(3, LOG_LINE_NORMAL, L"Getting EFI variable '%s' from %s", name,
ReadFromNvram ? L"NVRAM" : L"disk");
if (!ReadFromNvram) {
Status = CreateVarsDir();
if (Status == EFI_SUCCESS) {
Status = egLoadFile(gVarsDir, name, &buf, size);
} else {
ReadFromNvram = TRUE;
}
}
if (ReadFromNvram) {
l = sizeof(CHAR16 *) * EFI_MAXIMUM_VARIABLE_SIZE;
buf = AllocatePool(l);
if (!buf) {
*buffer = NULL;
return EFI_OUT_OF_RESOURCES;
}
Status = refit_call5_wrapper(RT->GetVariable, name, vendor, NULL, &l, buf);
}
if (EFI_ERROR(Status) == EFI_SUCCESS) {
*buffer = (CHAR8*) buf;
if ((size) && ReadFromNvram)
*size = l;
} else {
// Note: "Errors" here are common because of attempts to read
// non-existent variables, like Hidden* variables if they haven't
// been set. Hence, log at level 3, not 1.
LOG(3, LOG_LINE_NORMAL, L"Error retrieving EFI variable '%s'", name);
MyFreePool(buf);
*buffer = NULL;
*size = 0;
}
return Status;
} // EFI_STATUS EfivarGetRaw()
// Set an EFI variable. This is normally done to NVRAM; however, rEFInd-specific
// variables (as determined by the *vendor code) will be saved to a disk file IF
// GlobalConfig.UseNvram == FALSE.
// To minimize wear & tear on NVRAM, this function first reads the contents of
// the variable (if possible), and writes the variable only if its contents
// have changed (or if the variable is new).
// Returns EFI status
EFI_STATUS EfivarSetRaw(EFI_GUID *vendor, CHAR16 *name, CHAR8 *buf, UINTN size, BOOLEAN persistent) {
UINT32 flags;
EFI_STATUS Status = EFI_SUCCESS, OldStatus;
CHAR8 *OldBuf;
UINTN OldSize;
BOOLEAN WriteToNvram = TRUE;
if ((GlobalConfig.UseNvram == FALSE) && GuidsAreEqual(vendor, &RefindGuid))
WriteToNvram = FALSE;
OldStatus = EfivarGetRaw(vendor, name, &OldBuf, &OldSize);
LOG(2, LOG_LINE_NORMAL, L"Saving EFI variable '%s' to %s", name,
WriteToNvram ? L"NVRAM" : L"disk");
if ((EFI_ERROR(OldStatus)) || (size != OldSize) || (CompareMem(buf, OldBuf, size) != 0)) {
if (!WriteToNvram) {
Status = CreateVarsDir();
if (Status == EFI_SUCCESS) {
Status = egSaveFile(gVarsDir, name, (UINT8 *) buf, size);
} else {
WriteToNvram = TRUE;
}
}
if (WriteToNvram) {
flags = EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
if (persistent)
flags |= EFI_VARIABLE_NON_VOLATILE;
Status = refit_call5_wrapper(RT->SetVariable, name, vendor, flags, size, buf);
}
} else {
LOG(2, LOG_LINE_NORMAL, L"Not writing variable '%s'; it's unchanged", name);
}
if (OldStatus == EFI_SUCCESS) {
LOG(4, LOG_LINE_NORMAL, L"Freeing OldBuf");
MyFreePool(OldBuf);
LOG(4, LOG_LINE_NORMAL, L"Have freed OldBuf");
}
if (EFI_ERROR(Status))
LOG(1, LOG_LINE_NORMAL, L"Error %d when writing EFI variable '%s'", Status, name);
return Status;
} // EFI_STATUS EfivarSetRaw()
//
// list functions
//
VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
{
UINTN AllocateCount;
if ((*ElementCount & 15) == 0) {
AllocateCount = *ElementCount + 16;
if (*ElementCount == 0) {
*ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
LOG(2, LOG_LINE_NORMAL, L"Allocating memory in AddListElement()");
} else {
LOG(2, LOG_LINE_NORMAL, L"Reallocating memory in AddListElement(); *ElementCount is %ld", *ElementCount);
*ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
}
}
(*ListPtr)[*ElementCount] = NewElement;
(*ElementCount)++;
} /* VOID AddListElement() */
VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
{
UINTN i;
if ((*ElementCount > 0) && (**ListPtr != NULL)) {
for (i = 0; i < *ElementCount; i++) {
// TODO: call a user-provided routine for each element here
MyFreePool((*ListPtr)[i]);
}
MyFreePool(*ListPtr);
}
} // VOID FreeList()
//
// volume functions
//
// Return a pointer to a string containing a filesystem type name. If the
// filesystem type is unknown, a blank (but non-null) string is returned.
// The returned variable is a constant that should NOT be freed.
static CHAR16 *FSTypeName(IN UINT32 TypeCode) {
CHAR16 *retval = NULL;
switch (TypeCode) {
case FS_TYPE_WHOLEDISK:
retval = L" whole disk";
break;
case FS_TYPE_FAT:
retval = L" FAT";
break;
case FS_TYPE_HFSPLUS:
retval = L" HFS+";
break;
case FS_TYPE_EXT2:
retval = L" ext2";
break;
case FS_TYPE_EXT3:
retval = L" ext3";
break;
case FS_TYPE_EXT4:
retval = L" ext4";
break;
case FS_TYPE_REISERFS:
retval = L" ReiserFS";
break;
case FS_TYPE_BTRFS:
retval = L" Btrfs";
break;
case FS_TYPE_XFS:
retval = L" XFS";
break;
case FS_TYPE_JFS:
retval = L" JFS";
break;
case FS_TYPE_ISO9660:
retval = L" ISO-9660";
break;
case FS_TYPE_NTFS:
retval = L" NTFS";
break;
default:
retval = L"";
break;
} // switch
return retval;
} // CHAR16 *FSTypeName()
// Sets the FsName field of Volume, based on data recorded in the partition's
// filesystem. This field may remain unchanged if there's no known filesystem
// or if the name field is empty.
static VOID SetFilesystemName(REFIT_VOLUME *Volume) {
EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr = NULL;
if ((Volume) && (Volume->RootDir != NULL)) {
FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
}
if ((FileSystemInfoPtr != NULL) &&
(StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
if (Volume->FsName) {
MyFreePool(Volume->FsName);
Volume->FsName = NULL;
}
Volume->FsName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
}
MyFreePool(FileSystemInfoPtr);
} // VOID *SetFilesystemName()
// Identify the filesystem type and record the filesystem's UUID/serial number,
// if possible. Expects a Buffer containing the first few (normally at least
// 4096) bytes of the filesystem. Sets the filesystem type code in Volume->FSType
// and the UUID/serial number in Volume->VolUuid. Note that the UUID value is
// recognized differently for each filesystem, and is currently supported only
// for NTFS, FAT, ext2/3/4fs, and ReiserFS (and for NTFS and FAT it's really a
// 64-bit or 32-bit serial number not a UUID or GUID). If the UUID can't be
// determined, it's set to 0. Also, the UUID is just read directly into memory;
// it is *NOT* valid when displayed by GuidAsString() or used in other
// GUID/UUID-manipulating functions. (As I write, it's being used merely to
// detect partitions that are part of a RAID 1 array.)
static VOID SetFilesystemData(IN UINT8 *Buffer, IN UINTN BufferSize, IN OUT REFIT_VOLUME *Volume) {
UINT32 *Ext2Incompat, *Ext2Compat;
UINT16 *Magic16;
char *MagicString;
LOG(2, LOG_LINE_NORMAL, L"Identifying filesystem types....");
if ((Buffer != NULL) && (Volume != NULL)) {
SetMem(&(Volume->VolUuid), sizeof(EFI_GUID), 0);
Volume->FSType = FS_TYPE_UNKNOWN;
if (BufferSize >= (1024 + 100)) {
Magic16 = (UINT16*) (Buffer + 1024 + 56);
if (*Magic16 == EXT2_SUPER_MAGIC) { // ext2/3/4
Ext2Compat = (UINT32*) (Buffer + 1024 + 92);
Ext2Incompat = (UINT32*) (Buffer + 1024 + 96);
if ((*Ext2Incompat & 0x0040) || (*Ext2Incompat & 0x0200)) { // check for extents or flex_bg
LOG(4, LOG_LINE_NORMAL, L"Found ext4fs");
Volume->FSType = FS_TYPE_EXT4;
} else if (*Ext2Compat & 0x0004) { // check for journal
LOG(4, LOG_LINE_NORMAL, L"Found ext3fs");
Volume->FSType = FS_TYPE_EXT3;
} else { // none of these features; presume it's ext2...
LOG(4, LOG_LINE_NORMAL, L"Found ext2fs");
Volume->FSType = FS_TYPE_EXT2;
}
MyCopyMem(&(Volume->VolUuid), Buffer + 1024 + 104, sizeof(EFI_GUID));
return;
}
} // search for ext2/3/4 magic
if (BufferSize >= (65536 + 100)) {
MagicString = (char*) (Buffer + 65536 + 52);
if ((CompareMem(MagicString, REISERFS_SUPER_MAGIC_STRING, 8) == 0) ||
(CompareMem(MagicString, REISER2FS_SUPER_MAGIC_STRING, 9) == 0) ||
(CompareMem(MagicString, REISER2FS_JR_SUPER_MAGIC_STRING, 9) == 0)) {
LOG(4, LOG_LINE_NORMAL, L"Found ReiserFS");
Volume->FSType = FS_TYPE_REISERFS;
MyCopyMem(&(Volume->VolUuid), Buffer + 65536 + 84, sizeof(EFI_GUID));
return;
} // if
} // search for ReiserFS magic
if (BufferSize >= (65536 + 64 + 8)) {
MagicString = (char*) (Buffer + 65536 + 64);
if (CompareMem(MagicString, BTRFS_SIGNATURE, 8) == 0) {
LOG(4, LOG_LINE_NORMAL, L"Found Btrfs");
Volume->FSType = FS_TYPE_BTRFS;
return;
} // if
} // search for Btrfs magic
if (BufferSize >= 512) {
MagicString = (char*) Buffer;
if (CompareMem(MagicString, XFS_SIGNATURE, 4) == 0) {
LOG(4, LOG_LINE_NORMAL, L"Found XFS");
Volume->FSType = FS_TYPE_XFS;
return;
}
} // search for XFS magic
if (BufferSize >= (32768 + 4)) {
MagicString = (char*) (Buffer + 32768);
if (CompareMem(MagicString, JFS_SIGNATURE, 4) == 0) {
LOG(4, LOG_LINE_NORMAL, L"Found JFS");
Volume->FSType = FS_TYPE_JFS;
return;
}
} // search for JFS magic
if (BufferSize >= (1024 + 2)) {
Magic16 = (UINT16*) (Buffer + 1024);
if ((*Magic16 == HFSPLUS_MAGIC1) || (*Magic16 == HFSPLUS_MAGIC2)) {
LOG(4, LOG_LINE_NORMAL, L"Found HFS+");
Volume->FSType = FS_TYPE_HFSPLUS;
return;
}
} // search for HFS+ magic
if (BufferSize >= 512) {
// Search for NTFS, FAT, and MBR/EBR.
// These all have 0xAA55 at the end of the first sector, so we must
// also search for NTFS, FAT12, FAT16, and FAT32 signatures to
// figure out where to look for the filesystem serial numbers.
Magic16 = (UINT16*) (Buffer + 510);
if (*Magic16 == FAT_MAGIC) {
MagicString = (char*) Buffer;
if (CompareMem(MagicString + 3, NTFS_SIGNATURE, 8) == 0) {
LOG(4, LOG_LINE_NORMAL, L"Found NTFS");
Volume->FSType = FS_TYPE_NTFS;
MyCopyMem(&(Volume->VolUuid), Buffer + 0x48, sizeof(UINT64));
} else if ((CompareMem(MagicString + 0x36, FAT12_SIGNATURE, 8) == 0) ||
(CompareMem(MagicString + 0x36, FAT16_SIGNATURE, 8) == 0)) {
LOG(4, LOG_LINE_NORMAL, L"Found FAT12 or FAT16");
Volume->FSType = FS_TYPE_FAT;
MyCopyMem(&(Volume->VolUuid), Buffer + 0x27, sizeof(UINT32));
} else if (CompareMem(MagicString + 0x52, FAT32_SIGNATURE, 8) == 0) {
LOG(4, LOG_LINE_NORMAL, L"Found FAT32");
Volume->FSType = FS_TYPE_FAT;
MyCopyMem(&(Volume->VolUuid), Buffer + 0x43, sizeof(UINT32));
} else if (!Volume->BlockIO->Media->LogicalPartition) {
LOG(4, LOG_LINE_NORMAL, L"Found disk boot sector/MBR");
Volume->FSType = FS_TYPE_WHOLEDISK;
} // if/else
return;
} // if
} // search for FAT and NTFS magic
// If no other filesystem is identified and block size is right, assume
// it's ISO-9660....
if (Volume->BlockIO->Media->BlockSize == 2048) {
LOG(4, LOG_LINE_NORMAL, L"Found ISO-9660");
Volume->FSType = FS_TYPE_ISO9660;
return;
}
} // if ((Buffer != NULL) && (Volume != NULL))
} // UINT32 SetFilesystemData()
// Try to identify the filesystem held on Volume, as well as whether it holds
// any BIOS/CSM/legacy-mode boot code on Macs.
static VOID ScanVolumeBootcode(REFIT_VOLUME *Volume, BOOLEAN *Bootable)
{
EFI_STATUS Status;
UINT8 Buffer[SAMPLE_SIZE];
LOG(2, LOG_LINE_NORMAL, L"Entering ScanVolumeBootcode()");
Volume->HasBootCode = FALSE;
Volume->OSIconName = NULL;
Volume->OSName = NULL;
*Bootable = FALSE;
if (Volume->BlockIO == NULL)
return;
if (Volume->BlockIO->Media->BlockSize > SAMPLE_SIZE)
return; // our buffer is too small...
// look at the boot sector (this is used for both hard disks and El Torito images!)
Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
Volume->BlockIO, Volume->BlockIO->Media->MediaId,
Volume->BlockIOOffset, SAMPLE_SIZE, Buffer);
if (EFI_ERROR(Status)) {
LOG(1, LOG_LINE_NORMAL, L"Error %d reading boot sector of '%s'", Status, Volume->VolName);
} else {
SetFilesystemData(Buffer, SAMPLE_SIZE, Volume);
}
#if defined(EFI32) || defined(EFIX64)
MBR_PARTITION_INFO *MbrTable;
BOOLEAN MbrTableFound = FALSE;
UINTN i;
if ((Status == EFI_SUCCESS) && (GlobalConfig.LegacyType == LEGACY_TYPE_MAC)) {
if ((*((UINT16 *)(Buffer + 510)) == 0xaa55 && Buffer[0] != 0) &&
(FindMem(Buffer, 512, "EXFAT", 5) == -1)) {
*Bootable = TRUE;
Volume->HasBootCode = TRUE;
}
// detect specific boot codes
if (CompareMem(Buffer + 2, "LILO", 4) == 0 ||
CompareMem(Buffer + 6, "LILO", 4) == 0 ||
CompareMem(Buffer + 3, "SYSLINUX", 8) == 0 ||
FindMem(Buffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"linux";
Volume->OSName = L"Linux (Legacy)";
} else if (FindMem(Buffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"grub,linux";
Volume->OSName = L"Linux (Legacy)";
} else if ((*((UINT32 *)(Buffer + 502)) == 0 &&
*((UINT32 *)(Buffer + 506)) == 50000 &&
*((UINT16 *)(Buffer + 510)) == 0xaa55) ||
FindMem(Buffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"freebsd";
Volume->OSName = L"FreeBSD (Legacy)";
// If more differentiation needed, also search for
// "Invalid partition table" &/or "Missing boot loader".
} else if ((*((UINT16 *)(Buffer + 510)) == 0xaa55) &&
(FindMem(Buffer, SECTOR_SIZE, "Boot loader too large", 21) >= 0) &&
(FindMem(Buffer, SECTOR_SIZE, "I/O error loading boot loader", 29) >= 0)) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"freebsd";
Volume->OSName = L"FreeBSD (Legacy)";
} else if (FindMem(Buffer, 512, "!Loading", 8) >= 0 ||
FindMem(Buffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"openbsd";
Volume->OSName = L"OpenBSD (Legacy)";
} else if (FindMem(Buffer, 512, "Not a bootxx image", 18) >= 0 ||
*((UINT32 *)(Buffer + 1028)) == 0x7886b6d1) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"netbsd";
Volume->OSName = L"NetBSD (Legacy)";
// Windows NT/200x/XP
} else if (FindMem(Buffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"win";
Volume->OSName = L"Windows (Legacy)";
// Windows Vista/7/8
} else if (FindMem(Buffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"win8,win";
Volume->OSName = L"Windows (Legacy)";
} else if (FindMem(Buffer, 512, "CPUBOOT SYS", 11) >= 0 ||
FindMem(Buffer, 512, "KERNEL SYS", 11) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"freedos";
Volume->OSName = L"FreeDOS (Legacy)";
} else if (FindMem(Buffer, 512, "OS2LDR", 6) >= 0 ||
FindMem(Buffer, 512, "OS2BOOT", 7) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"ecomstation";
Volume->OSName = L"eComStation (Legacy)";
} else if (FindMem(Buffer, 512, "Be Boot Loader", 14) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"beos";
Volume->OSName = L"BeOS (Legacy)";
} else if (FindMem(Buffer, 512, "yT Boot Loader", 14) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"zeta,beos";
Volume->OSName = L"ZETA (Legacy)";
} else if (FindMem(Buffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
FindMem(Buffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
Volume->HasBootCode = TRUE;
Volume->OSIconName = L"haiku,beos";
Volume->OSName = L"Haiku (Legacy)";
}
// NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
// need to fix AddLegacyEntry in refind/legacy.c.
LOG(1, LOG_LINE_NORMAL, L"Result of bootcode detection: %s %s (%s)",
Volume->HasBootCode ? L"bootable" : L"non-bootable", Volume->OSName,
Volume->OSIconName);
// dummy FAT boot sector (created by OS X's newfs_msdos)
if (FindMem(Buffer, 512, "Non-system disk", 15) >= 0)
Volume->HasBootCode = FALSE;
// dummy FAT boot sector (created by Linux's mkdosfs)
if (FindMem(Buffer, 512, "This is not a bootable disk", 27) >= 0)
Volume->HasBootCode = FALSE;
// dummy FAT boot sector (created by Windows)
if (FindMem(Buffer, 512, "Press any key to restart", 24) >= 0)
Volume->HasBootCode = FALSE;
// check for MBR partition table
if (*((UINT16 *)(Buffer + 510)) == 0xaa55) {
MbrTable = (MBR_PARTITION_INFO *)(Buffer + 446);
for (i = 0; i < 4; i++)
if (MbrTable[i].StartLBA && MbrTable[i].Size)
MbrTableFound = TRUE;
for (i = 0; i < 4; i++)
if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
MbrTableFound = FALSE;
if (MbrTableFound) {
Volume->MbrPartitionTable = AllocatePool(4 * 16);
MyCopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
}
}
}
#endif
} /* VOID ScanVolumeBootcode() */
// Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
VOID SetVolumeBadgeIcon(REFIT_VOLUME *Volume)
{
if (Volume == NULL)
return;
if (GlobalConfig.HideUIFlags & HIDEUI_FLAG_BADGES)
return;
if (Volume->VolBadgeImage == NULL) {
Volume->VolBadgeImage = egLoadIconAnyType(Volume->RootDir, L"",
L".VolumeBadge",
GlobalConfig.IconSizes[ICON_SIZE_BADGE]);
}
if (Volume->VolBadgeImage == NULL) {
switch (Volume->DiskKind) {
case DISK_KIND_INTERNAL:
Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
break;
case DISK_KIND_EXTERNAL:
Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
break;
case DISK_KIND_OPTICAL:
Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
break;
case DISK_KIND_NET:
Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
break;
} // switch()
}
} // VOID SetVolumeBadgeIcon()
// Return a string representing the input size in IEEE-1541 units.
// The calling function is responsible for freeing the allocated memory.
static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
UINT64 SizeInIeee;
UINTN Index = 0, NumPrefixes;
CHAR16 *Units = NULL, *Prefixes = L" KMGTPEZ";
CHAR16 *TheValue;
NumPrefixes = StrLen(Prefixes);
SizeInIeee = SizeInBytes;
while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
Index++;
SizeInIeee /= 1024;
} // while
if (Prefixes[Index] == ' ') {
Units = StrDuplicate(L"-byte");
} else {
Units = StrDuplicate(L" iB");
Units[1] = Prefixes[Index];
} // if/else
TheValue = PoolPrint(L"%ld%s", SizeInIeee, Units);
MyFreePool(Units);
return TheValue;
} // CHAR16 *SizeInIEEEUnits()
// Return a name for the volume. Ideally this should be the label for the
// filesystem or partition, but this function falls back to describing the
// filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
// this information can be extracted.
// The calling function is responsible for freeing the memory allocated
// for the name string.
static CHAR16 *GetVolumeName(REFIT_VOLUME *Volume) {
EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr = NULL;
CHAR16 *FoundName = NULL;
CHAR16 *SISize, *TypeName;
if ((Volume->FsName) && (StrLen(Volume->FsName) > 0)) {
FoundName = StrDuplicate(Volume->FsName);
LOG(3, LOG_LINE_NORMAL, L"Setting volume name to filesystem name of '%s'", FoundName);
}
// If no filesystem name, try to use the partition name....