-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpt.cc
2471 lines (2207 loc) · 94.4 KB
/
gpt.cc
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
/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
data. */
/* By Rod Smith, initial coding January to February, 2009 */
/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
#define __STDC_LIMIT_MACROS
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <fcntl.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/stat.h>
#include <errno.h>
#include <iostream>
#include <algorithm>
#include "crc32.h"
#include "gpt.h"
#include "bsd.h"
#include "support.h"
#include "parttypes.h"
#include "attributes.h"
#include "diskio.h"
using namespace std;
#ifdef __FreeBSD__
#define log2(x) (log(x) / M_LN2)
#endif // __FreeBSD__
#ifdef _MSC_VER
#define log2(x) (log((double) x) / log(2.0))
#endif // Microsoft Visual C++
#ifdef EFI
// in UEFI mode MMX registers are not yet available so using the
// x86_64 ABI to move "double" values around is not an option.
#ifdef log2
#undef log2
#endif
#define log2(x) log2_32( x )
static inline uint32_t log2_32(uint32_t v) {
int r = -1;
while (v >= 1) {
r++;
v >>= 1;
}
return r;
}
#endif
/****************************************
* *
* GPTData class and related structures *
* *
****************************************/
// Default constructor
GPTData::GPTData(void) {
blockSize = SECTOR_SIZE; // set a default
diskSize = 0;
partitions = NULL;
state = gpt_valid;
device = "";
justLooking = 0;
syncing = 1;
mainCrcOk = 0;
secondCrcOk = 0;
mainPartsCrcOk = 0;
secondPartsCrcOk = 0;
apmFound = 0;
bsdFound = 0;
sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
beQuiet = 0;
whichWasUsed = use_new;
mainHeader.numParts = 0;
numParts = 0;
SetGPTSize(NUM_GPT_ENTRIES);
// Initialize CRC functions...
chksum_crc32gentab();
} // GPTData default constructor
// The following constructor loads GPT data from a device file
GPTData::GPTData(string filename) {
blockSize = SECTOR_SIZE; // set a default
diskSize = 0;
partitions = NULL;
state = gpt_invalid;
device = "";
justLooking = 0;
syncing = 1;
mainCrcOk = 0;
secondCrcOk = 0;
mainPartsCrcOk = 0;
secondPartsCrcOk = 0;
apmFound = 0;
bsdFound = 0;
sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
beQuiet = 0;
whichWasUsed = use_new;
mainHeader.numParts = 0;
numParts = 0;
// Initialize CRC functions...
chksum_crc32gentab();
if (!LoadPartitions(filename))
exit(2);
} // GPTData(string filename) constructor
// Destructor
GPTData::~GPTData(void) {
delete[] partitions;
} // GPTData destructor
// Assignment operator
GPTData & GPTData::operator=(const GPTData & orig) {
uint32_t i;
mainHeader = orig.mainHeader;
numParts = orig.numParts;
secondHeader = orig.secondHeader;
protectiveMBR = orig.protectiveMBR;
device = orig.device;
blockSize = orig.blockSize;
diskSize = orig.diskSize;
state = orig.state;
justLooking = orig.justLooking;
syncing = orig.syncing;
mainCrcOk = orig.mainCrcOk;
secondCrcOk = orig.secondCrcOk;
mainPartsCrcOk = orig.mainPartsCrcOk;
secondPartsCrcOk = orig.secondPartsCrcOk;
apmFound = orig.apmFound;
bsdFound = orig.bsdFound;
sectorAlignment = orig.sectorAlignment;
beQuiet = orig.beQuiet;
whichWasUsed = orig.whichWasUsed;
myDisk.OpenForRead(orig.myDisk.GetName());
delete[] partitions;
partitions = new GPTPart [numParts];
if (partitions == NULL) {
cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
<< "Terminating!\n";
exit(1);
} // if
for (i = 0; i < numParts; i++) {
partitions[i] = orig.partitions[i];
} // for
return *this;
} // GPTData::operator=()
/*********************************************************************
* *
* Begin functions that verify data, or that adjust the verification *
* information (compute CRCs, rebuild headers) *
* *
*********************************************************************/
// Perform detailed verification, reporting on any problems found, but
// do *NOT* recover from these problems. Returns the total number of
// problems identified.
int GPTData::Verify(void) {
int problems = 0, alignProbs = 0;
uint32_t i, numSegments;
uint64_t totalFree, largestSegment;
// First, check for CRC errors in the GPT data....
if (!mainCrcOk) {
problems++;
cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
<< "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
<< "header ('b' on the recovery & transformation menu). This report may be a false\n"
<< "alarm if you've already corrected other problems.\n";
} // if
if (!mainPartsCrcOk) {
problems++;
cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
<< "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
<< "transformation menu). This report may be a false alarm if you've already\n"
<< "corrected other problems.\n";
} // if
if (!secondCrcOk) {
problems++;
cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
<< "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
<< "header ('d' on the recovery & transformation menu). This report may be a false\n"
<< "alarm if you've already corrected other problems.\n";
} // if
if (!secondPartsCrcOk) {
problems++;
cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
<< "be corrupt. This program will automatically create a new backup partition\n"
<< "table when you save your partitions.\n";
} // if
// Now check that the main and backup headers both point to themselves....
if (mainHeader.currentLBA != 1) {
problems++;
cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
<< "is being automatically corrected, but it may be a symptom of more serious\n"
<< "problems. Think carefully before saving changes with 'w' or using this disk.\n";
mainHeader.currentLBA = 1;
} // if
if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
problems++;
cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
<< "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
<< "option on the experts' menu to adjust the secondary header's and partition\n"
<< "table's locations.\n";
} // if
// Now check that critical main and backup GPT entries match each other
if (mainHeader.currentLBA != secondHeader.backupLBA) {
problems++;
cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
<< ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
<< secondHeader.backupLBA << ").\n";
} // if
if (mainHeader.backupLBA != secondHeader.currentLBA) {
problems++;
cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
<< ") doesn't\nmatch the backup GPT header's current LBA pointer ("
<< secondHeader.currentLBA << ").\n"
<< "The 'e' option on the experts' menu may fix this problem.\n";
} // if
if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
problems++;
cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
<< ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
<< secondHeader.firstUsableLBA << ")\n";
} // if
if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
problems++;
cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
<< ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
<< secondHeader.lastUsableLBA << ")\n"
<< "The 'e' option on the experts' menu can probably fix this problem.\n";
} // if
if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
problems++;
cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
<< ") doesn't\nmatch the backup GPT header's disk GUID ("
<< secondHeader.diskGUID << ")\n"
<< "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
<< "select one or the other header.\n";
} // if
if (mainHeader.numParts != secondHeader.numParts) {
problems++;
cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
<< ") doesn't\nmatch the backup GPT header's number of partitions ("
<< secondHeader.numParts << ")\n"
<< "Resizing the partition table ('s' on the experts' menu) may help.\n";
} // if
if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
problems++;
cout << "\nProblem: main GPT header's size of partition entries ("
<< mainHeader.sizeOfPartitionEntries << ") doesn't\n"
<< "match the backup GPT header's size of partition entries ("
<< secondHeader.sizeOfPartitionEntries << ")\n"
<< "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
<< "select one or the other header.\n";
} // if
// Now check for a few other miscellaneous problems...
// Check that the disk size will hold the data...
if (mainHeader.backupLBA >= diskSize) {
problems++;
cout << "\nProblem: Disk is too small to hold all the data!\n"
<< "(Disk size is " << diskSize << " sectors, needs to be "
<< mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
<< "The 'e' option on the experts' menu may fix this problem.\n";
} // if
if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
problems++;
cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
<< "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
<< mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
<< "The 'e' option on the experts' menu will probably fix this problem\n";
}
// Check for overlapping partitions....
problems += FindOverlaps();
// Check for insane partitions (start after end, hugely big, etc.)
problems += FindInsanePartitions();
// Check for mismatched MBR and GPT partitions...
problems += FindHybridMismatches();
// Check for MBR-specific problems....
problems += VerifyMBR();
// Check for a 0xEE protective partition that's marked as active....
if (protectiveMBR.IsEEActive()) {
cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
<< "technically a violation of the GPT specification, and can cause some EFIs to\n"
<< "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
<< "computers. You can clear this flag by creating a fresh protective MBR using\n"
<< "the 'n' option on the experts' menu.\n";
}
// Verify that partitions don't run into GPT data areas....
problems += CheckGPTSize();
if (!protectiveMBR.DoTheyFit()) {
cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
<< "fresh protective or hybrid MBR is recommended.\n";
problems++;
}
// Check that partitions are aligned on proper boundaries (for WD Advanced
// Format and similar disks)....
for (i = 0; i < numParts; i++) {
if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
<< sectorAlignment << "-sector boundary. This may\nresult "
<< "in degraded performance on some modern (2009 and later) hard disks.\n";
alignProbs++;
} // if
} // for
if (alignProbs > 0)
cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
<< "for information on disk alignment.\n";
// Now compute available space, but only if no problems found, since
// problems could affect the results
if (problems == 0) {
totalFree = FindFreeBlocks(&numSegments, &largestSegment);
cout << "\nNo problems found. " << totalFree << " free sectors ("
<< BytesToIeee(totalFree, blockSize) << ") available in "
<< numSegments << "\nsegments, the largest of which is "
<< largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
<< ") in size.\n";
} else {
cout << "\nIdentified " << problems << " problems!\n";
} // if/else
return (problems);
} // GPTData::Verify()
// Checks to see if the GPT tables overrun existing partitions; if they
// do, issues a warning but takes no action. Returns number of problems
// detected (0 if OK, 1 to 2 if problems).
int GPTData::CheckGPTSize(void) {
uint64_t overlap, firstUsedBlock, lastUsedBlock;
uint32_t i;
int numProbs = 0;
// first, locate the first & last used blocks
firstUsedBlock = UINT64_MAX;
lastUsedBlock = 0;
for (i = 0; i < numParts; i++) {
if (partitions[i].IsUsed()) {
if (partitions[i].GetFirstLBA() < firstUsedBlock)
firstUsedBlock = partitions[i].GetFirstLBA();
if (partitions[i].GetLastLBA() > lastUsedBlock) {
lastUsedBlock = partitions[i].GetLastLBA();
} // if
} // if
} // for
// If the disk size is 0 (the default), then it means that various
// variables aren't yet set, so the below tests will be useless;
// therefore we should skip everything
if (diskSize != 0) {
if (mainHeader.firstUsableLBA > firstUsedBlock) {
overlap = mainHeader.firstUsableLBA - firstUsedBlock;
cout << "Warning! Main partition table overlaps the first partition by "
<< overlap << " blocks!\n";
if (firstUsedBlock > 2) {
cout << "Try reducing the partition table size by " << overlap * 4
<< " entries.\n(Use the 's' item on the experts' menu.)\n";
} else {
cout << "You will need to delete this partition or resize it in another utility.\n";
} // if/else
numProbs++;
} // Problem at start of disk
if (mainHeader.lastUsableLBA < lastUsedBlock) {
overlap = lastUsedBlock - mainHeader.lastUsableLBA;
cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
<< overlap << " blocks!\n";
if (lastUsedBlock > (diskSize - 2)) {
cout << "You will need to delete this partition or resize it in another utility.\n";
} else {
cout << "Try reducing the partition table size by " << overlap * 4
<< " entries.\n(Use the 's' item on the experts' menu.)\n";
} // if/else
numProbs++;
} // Problem at end of disk
} // if (diskSize != 0)
return numProbs;
} // GPTData::CheckGPTSize()
// Check the validity of the GPT header. Returns 1 if the main header
// is valid, 2 if the backup header is valid, 3 if both are valid, and
// 0 if neither is valid. Note that this function checks the GPT signature,
// revision value, and CRCs in both headers.
int GPTData::CheckHeaderValidity(void) {
int valid = 3;
cout.setf(ios::uppercase);
cout.fill('0');
// Note: failed GPT signature checks produce no error message because
// a message is displayed in the ReversePartitionBytes() function
if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
valid -= 1;
} else if ((mainHeader.revision != 0x00010000) && valid) {
valid -= 1;
cout << "Unsupported GPT version in main header; read 0x";
cout.width(8);
cout << hex << mainHeader.revision << ", should be\n0x";
cout.width(8);
cout << UINT32_C(0x00010000) << dec << "\n";
} // if/else/if
if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
valid -= 2;
} else if ((secondHeader.revision != 0x00010000) && valid) {
valid -= 2;
cout << "Unsupported GPT version in backup header; read 0x";
cout.width(8);
cout << hex << secondHeader.revision << ", should be\n0x";
cout.width(8);
cout << UINT32_C(0x00010000) << dec << "\n";
} // if/else/if
// Check for an Apple disk signature
if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
(mainHeader.signature << 32) == APM_SIGNATURE2) {
apmFound = 1; // Will display warning message later
} // if
cout.fill(' ');
return valid;
} // GPTData::CheckHeaderValidity()
// Check the header CRC to see if it's OK...
// Note: Must be called with header in platform-ordered byte order.
// Returns 1 if header's computed CRC matches the stored value, 0 if the
// computed and stored values don't match
int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
uint32_t oldCRC, newCRC, hSize;
uint8_t *temp;
// Back up old header CRC and then blank it, since it must be 0 for
// computation to be valid
oldCRC = header->headerCRC;
header->headerCRC = UINT32_C(0);
hSize = header->headerSize;
if (IsLittleEndian() == 0)
ReverseHeaderBytes(header);
if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
if (warn) {
cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
} // if
hSize = HEADER_SIZE;
} else if ((hSize > sizeof(GPTHeader)) && warn) {
cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
<< "which may result in a CRC false alarm.\n";
} // if/elseif
temp = new uint8_t[hSize];
if (temp != NULL) {
memset(temp, 0, hSize);
if (hSize < sizeof(GPTHeader))
memcpy(temp, header, hSize);
else
memcpy(temp, header, sizeof(GPTHeader));
newCRC = chksum_crc32((unsigned char*) temp, hSize);
delete[] temp;
} else {
cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
exit(1);
}
if (IsLittleEndian() == 0)
ReverseHeaderBytes(header);
header->headerCRC = oldCRC;
return (oldCRC == newCRC);
} // GPTData::CheckHeaderCRC()
// Recompute all the CRCs. Must be called before saving if any changes have
// been made. Must be called on platform-ordered data (this function reverses
// byte order and then undoes that reversal.)
void GPTData::RecomputeCRCs(void) {
uint32_t crc, hSize;
int littleEndian = 1;
// If the header size is bigger than the GPT header data structure, reset it;
// otherwise, set both header sizes to whatever the main one is....
if (mainHeader.headerSize > sizeof(GPTHeader))
hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
else
hSize = secondHeader.headerSize = mainHeader.headerSize;
if ((littleEndian = IsLittleEndian()) == 0) {
ReversePartitionBytes();
ReverseHeaderBytes(&mainHeader);
ReverseHeaderBytes(&secondHeader);
} // if
// Compute CRC of partition tables & store in main and secondary headers
crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
mainHeader.partitionEntriesCRC = crc;
secondHeader.partitionEntriesCRC = crc;
if (littleEndian == 0) {
ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
} // if
// Zero out GPT headers' own CRCs (required for correct computation)
mainHeader.headerCRC = 0;
secondHeader.headerCRC = 0;
crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
if (littleEndian == 0)
ReverseBytes(&crc, 4);
mainHeader.headerCRC = crc;
crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
if (littleEndian == 0)
ReverseBytes(&crc, 4);
secondHeader.headerCRC = crc;
if (littleEndian == 0) {
ReverseHeaderBytes(&mainHeader);
ReverseHeaderBytes(&secondHeader);
ReversePartitionBytes();
} // if
} // GPTData::RecomputeCRCs()
// Rebuild the main GPT header, using the secondary header as a model.
// Typically called when the main header has been found to be corrupt.
void GPTData::RebuildMainHeader(void) {
mainHeader.signature = GPT_SIGNATURE;
mainHeader.revision = secondHeader.revision;
mainHeader.headerSize = secondHeader.headerSize;
mainHeader.headerCRC = UINT32_C(0);
mainHeader.reserved = secondHeader.reserved;
mainHeader.currentLBA = secondHeader.backupLBA;
mainHeader.backupLBA = secondHeader.currentLBA;
mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
mainHeader.diskGUID = secondHeader.diskGUID;
mainHeader.partitionEntriesLBA = UINT64_C(2);
mainHeader.numParts = secondHeader.numParts;
mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
mainCrcOk = secondCrcOk;
SetGPTSize(mainHeader.numParts, 0);
} // GPTData::RebuildMainHeader()
// Rebuild the secondary GPT header, using the main header as a model.
void GPTData::RebuildSecondHeader(void) {
secondHeader.signature = GPT_SIGNATURE;
secondHeader.revision = mainHeader.revision;
secondHeader.headerSize = mainHeader.headerSize;
secondHeader.headerCRC = UINT32_C(0);
secondHeader.reserved = mainHeader.reserved;
secondHeader.currentLBA = mainHeader.backupLBA;
secondHeader.backupLBA = mainHeader.currentLBA;
secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
secondHeader.diskGUID = mainHeader.diskGUID;
secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
secondHeader.numParts = mainHeader.numParts;
secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
secondCrcOk = mainCrcOk;
SetGPTSize(secondHeader.numParts, 0);
} // GPTData::RebuildSecondHeader()
// Search for hybrid MBR entries that have no corresponding GPT partition.
// Returns number of such mismatches found
int GPTData::FindHybridMismatches(void) {
int i, found, numFound = 0;
uint32_t j;
uint64_t mbrFirst, mbrLast;
for (i = 0; i < 4; i++) {
if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
j = 0;
found = 0;
mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
do {
if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
(partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
found = 1;
j++;
} while ((!found) && (j < numParts));
if (!found) {
numFound++;
cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
<< i + 1 << ", of type 0x";
cout.fill('0');
cout.setf(ios::uppercase);
cout.width(2);
cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
<< "has no corresponding GPT partition! You may continue, but this condition\n"
<< "might cause data loss in the future!\a\n" << dec;
cout.fill(' ');
} // if
} // if
} // for
return numFound;
} // GPTData::FindHybridMismatches
// Find overlapping partitions and warn user about them. Returns number of
// overlapping partitions.
// Returns number of overlapping segments found.
int GPTData::FindOverlaps(void) {
int problems = 0;
uint32_t i, j;
for (i = 1; i < numParts; i++) {
for (j = 0; j < i; j++) {
if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
(partitions[i].DoTheyOverlap(partitions[j]))) {
problems++;
cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
<< " to " << partitions[i].GetLastLBA() << "\n";
cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
<< " to " << partitions[j].GetLastLBA() << "\n";
} // if
} // for j...
} // for i...
return problems;
} // GPTData::FindOverlaps()
// Find partitions that are insane -- they start after they end or are too
// big for the disk. (The latter should duplicate detection of overlaps
// with GPT backup data structures, but better to err on the side of
// redundant tests than to miss something....)
// Returns number of problems found.
int GPTData::FindInsanePartitions(void) {
uint32_t i;
int problems = 0;
for (i = 0; i < numParts; i++) {
if (partitions[i].IsUsed()) {
if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
problems++;
cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
} // if
if (partitions[i].GetLastLBA() >= diskSize) {
problems++;
cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
} // if
} // if
} // for
return problems;
} // GPTData::FindInsanePartitions(void)
/******************************************************************
* *
* Begin functions that load data from disk or save data to disk. *
* *
******************************************************************/
// Change the filename associated with the GPT. Used for duplicating
// the partition table to a new disk and saving backups.
// Returns 1 on success, 0 on failure.
int GPTData::SetDisk(const string & deviceFilename) {
int err, allOK = 1;
device = deviceFilename;
if (allOK && myDisk.OpenForRead(deviceFilename)) {
// store disk information....
diskSize = myDisk.DiskSize(&err);
blockSize = (uint32_t) myDisk.GetBlockSize();
} // if
protectiveMBR.SetDisk(&myDisk);
protectiveMBR.SetDiskSize(diskSize);
protectiveMBR.SetBlockSize(blockSize);
return allOK;
} // GPTData::SetDisk()
// Scan for partition data. This function loads the MBR data (regular MBR or
// protective MBR) and loads BSD disklabel data (which is probably invalid).
// It also looks for APM data, forces a load of GPT data, and summarizes
// the results.
void GPTData::PartitionScan(void) {
BSDData bsdDisklabel;
// Read the MBR & check for BSD disklabel
protectiveMBR.ReadMBRData(&myDisk);
bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
// Load the GPT data, whether or not it's valid
ForceLoadGPTData();
// Some tools create a 0xEE partition that's too big. If this is detected,
// normalize it....
if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
if (!beQuiet) {
cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
} // if
protectiveMBR.MakeProtectiveMBR();
} // if
if (!beQuiet) {
cout << "Partition table scan:\n";
protectiveMBR.ShowState();
bsdDisklabel.ShowState();
ShowAPMState(); // Show whether there's an Apple Partition Map present
ShowGPTState(); // Show GPT status
cout << "\n";
} // if
if (apmFound) {
cout << "\n*******************************************************************\n"
<< "This disk appears to contain an Apple-format (APM) partition table!\n";
if (!justLooking) {
cout << "It will be destroyed if you continue!\n";
} // if
cout << "*******************************************************************\n\n\a";
} // if
} // GPTData::PartitionScan()
// Read GPT data from a disk.
int GPTData::LoadPartitions(const string & deviceFilename) {
BSDData bsdDisklabel;
int err, allOK = 1;
MBRValidity mbrState;
if (myDisk.OpenForRead(deviceFilename)) {
err = myDisk.OpenForWrite(deviceFilename);
if ((err == 0) && (!justLooking)) {
cout << "\aNOTE: Write test failed with error number " << errno
<< ". It will be impossible to save\nchanges to this disk's partition table!\n";
#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
cout << "You may be able to enable writes by exiting this program, typing\n"
<< "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
<< "program.\n";
#endif
cout << "\n";
} // if
myDisk.Close(); // Close and re-open read-only in case of bugs
} else allOK = 0; // if
if (allOK && myDisk.OpenForRead(deviceFilename)) {
// store disk information....
diskSize = myDisk.DiskSize(&err);
blockSize = (uint32_t) myDisk.GetBlockSize();
device = deviceFilename;
PartitionScan(); // Check for partition types, load GPT, & print summary
whichWasUsed = UseWhichPartitions();
switch (whichWasUsed) {
case use_mbr:
XFormPartitions();
break;
case use_bsd:
bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
// bsdDisklabel.DisplayBSDData();
ClearGPTData();
protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
XFormDisklabel(&bsdDisklabel);
break;
case use_gpt:
mbrState = protectiveMBR.GetValidity();
if ((mbrState == invalid) || (mbrState == mbr))
protectiveMBR.MakeProtectiveMBR();
break;
case use_new:
ClearGPTData();
protectiveMBR.MakeProtectiveMBR();
break;
case use_abort:
allOK = 0;
cerr << "Invalid partition data!\n";
break;
} // switch
if (allOK)
CheckGPTSize();
myDisk.Close();
ComputeAlignment();
} else {
allOK = 0;
} // if/else
return (allOK);
} // GPTData::LoadPartitions()
// Loads the GPT, as much as possible. Returns 1 if this seems to have
// succeeded, 0 if there are obvious problems....
int GPTData::ForceLoadGPTData(void) {
int allOK, validHeaders, loadedTable = 1;
allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
} else {
allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
<< "secondary header from the last sector of the disk! You should use 'v' to\n"
<< "verify disk integrity, and perhaps options on the experts' menu to repair\n"
<< "the disk.\n";
} // if/else
if (!allOK)
state = gpt_invalid;
// Return valid headers code: 0 = both headers bad; 1 = main header
// good, backup bad; 2 = backup header good, main header bad;
// 3 = both headers good. Note these codes refer to valid GPT
// signatures, version numbers, and CRCs.
validHeaders = CheckHeaderValidity();
// Read partitions (from primary array)
if (validHeaders > 0) { // if at least one header is OK....
// GPT appears to be valid....
state = gpt_valid;
// We're calling the GPT valid, but there's a possibility that one
// of the two headers is corrupt. If so, use the one that seems to
// be in better shape to regenerate the bad one
if (validHeaders == 1) { // valid main header, invalid backup header
cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
<< "backup header from main header.\n\n";
RebuildSecondHeader();
state = gpt_corrupt;
secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
} else if (validHeaders == 2) { // valid backup header, invalid main header
cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
<< "from backup!\n\n";
RebuildMainHeader();
state = gpt_corrupt;
mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
} // if/else/if
// Figure out which partition table to load....
// Load the main partition table, since either its header's CRC is OK or the
// backup header's CRC is not OK....
if (mainCrcOk || !secondCrcOk) {
if (LoadMainTable() == 0)
allOK = 0;
} else { // bad main header CRC and backup header CRC is OK
state = gpt_corrupt;
if (LoadSecondTableAsMain()) {
loadedTable = 2;
cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
} else { // backup table bad, bad main header CRC, but try main table in desperation....
if (LoadMainTable() == 0) {
allOK = 0;
loadedTable = 0;
cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
} // if
} // if/else (LoadSecondTableAsMain())
} // if/else (load partition table)
if (loadedTable == 1)
secondPartsCrcOk = CheckTable(&secondHeader);
else if (loadedTable == 2)
mainPartsCrcOk = CheckTable(&mainHeader);
else
mainPartsCrcOk = secondPartsCrcOk = 0;
// Problem with main partition table; if backup is OK, use it instead....
if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
state = gpt_corrupt;
allOK = allOK && LoadSecondTableAsMain();
mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
<< "partition table\ninstead of main partition table!\n\n";
} // if */
// Check for valid CRCs and warn if there are problems
if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
(secondPartsCrcOk == 0)) {
cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
state = gpt_corrupt;
} // if
} else {
state = gpt_invalid;
} // if/else
return allOK;
} // GPTData::ForceLoadGPTData()
// Loads the partition table pointed to by the main GPT header. The
// main GPT header in memory MUST be valid for this call to do anything
// sensible!
// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
int GPTData::LoadMainTable(void) {
return LoadPartitionTable(mainHeader, myDisk);
} // GPTData::LoadMainTable()
// Load the second (backup) partition table as the primary partition
// table. Used in repair functions, and when starting up if the main
// partition table is damaged.
// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
int GPTData::LoadSecondTableAsMain(void) {
return LoadPartitionTable(secondHeader, myDisk);
} // GPTData::LoadSecondTableAsMain()
// Load a single GPT header (main or backup) from the specified disk device and
// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
// value appropriately.
// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
// failure.
int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
int allOK = 1;
GPTHeader tempHeader;
disk.Seek(sector);
if (disk.Read(&tempHeader, 512) != 512) {
cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
allOK = 0;
} // if
// Reverse byte order, if necessary
if (IsLittleEndian() == 0) {
ReverseHeaderBytes(&tempHeader);
} // if
*crcOk = CheckHeaderCRC(&tempHeader);
if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
allOK = SetGPTSize(tempHeader.numParts, 0);
}
*header = tempHeader;
return allOK;
} // GPTData::LoadHeader
// Load a partition table (either main or secondary) from the specified disk,
// using header as a reference for what to load. If sector != 0 (the default
// is 0), loads from the specified sector; otherwise loads from the sector
// indicated in header.
// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
uint32_t sizeOfParts, newCRC;
int retval;
if (disk.OpenForRead()) {
if (sector == 0) {
retval = disk.Seek(header.partitionEntriesLBA);
} else {
retval = disk.Seek(sector);
} // if/else
if (retval == 1)
retval = SetGPTSize(header.numParts, 0);
if (retval == 1) {
sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
retval = 0;
} // if
newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
if (IsLittleEndian() == 0)
ReversePartitionBytes();
if (!mainPartsCrcOk) {
cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
} // if
} else {
cerr << "Error! Couldn't seek to partition table!\n";
} // if/else
} else {
cerr << "Error! Couldn't open device " << device
<< " when reading partition table!\n";
retval = 0;
} // if/else
return retval;
} // GPTData::LoadPartitionsTable()
// Check the partition table pointed to by header, but don't keep it
// around.
// Returns 1 if the CRC is OK & this table matches the one already in memory,
// 0 if not or if there was a read error.
int GPTData::CheckTable(struct GPTHeader *header) {
uint32_t sizeOfParts, newCRC;
GPTPart *partsToCheck;
GPTHeader *otherHeader;
int allOK = 0;
// Load partition table into temporary storage to check
// its CRC and store the results, then discard this temporary
// storage, since we don't use it in any but recovery operations
if (myDisk.Seek(header->partitionEntriesLBA)) {