• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2    data. */
3 
4 /* By Rod Smith, initial coding January to February, 2009 */
5 
6 /* This program is copyright (c) 2009-2022 by Roderick W. Smith. It is distributed
7   under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8 
9 #define __STDC_LIMIT_MACROS
10 #define __STDC_CONSTANT_MACROS
11 
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdint.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <math.h>
18 #include <time.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21 #include <iostream>
22 #include <algorithm>
23 #include "crc32.h"
24 #include "gpt.h"
25 #include "bsd.h"
26 #include "support.h"
27 #include "parttypes.h"
28 #include "attributes.h"
29 #include "diskio.h"
30 
31 using namespace std;
32 
33 #ifdef __FreeBSD__
34 #define log2(x) (log(x) / M_LN2)
35 #endif // __FreeBSD__
36 
37 #ifdef _MSC_VER
38 #define log2(x) (log((double) x) / log(2.0))
39 #endif // Microsoft Visual C++
40 
41 #ifdef EFI
42 // in UEFI mode MMX registers are not yet available so using the
43 // x86_64 ABI to move "double" values around is not an option.
44 #ifdef log2
45 #undef log2
46 #endif
47 #define log2(x) log2_32( x )
log2_32(uint32_t v)48 static inline uint32_t log2_32(uint32_t v) {
49    int r = -1;
50    while (v >= 1) {
51       r++;
52       v >>= 1;
53    }
54    return r;
55 }
56 #endif
57 
58 /****************************************
59  *                                      *
60  * GPTData class and related structures *
61  *                                      *
62  ****************************************/
63 
64 // Default constructor
GPTData(void)65 GPTData::GPTData(void) {
66    blockSize = SECTOR_SIZE; // set a default
67    physBlockSize = 0; // 0 = can't be determined
68    diskSize = 0;
69    partitions = NULL;
70    state = gpt_valid;
71    device = "";
72    justLooking = 0;
73    mainCrcOk = 0;
74    secondCrcOk = 0;
75    mainPartsCrcOk = 0;
76    secondPartsCrcOk = 0;
77    apmFound = 0;
78    bsdFound = 0;
79    sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
80    beQuiet = 0;
81    whichWasUsed = use_new;
82    mainHeader.numParts = 0;
83    mainHeader.firstUsableLBA = 0;
84    mainHeader.lastUsableLBA = 0;
85    numParts = 0;
86    SetGPTSize(NUM_GPT_ENTRIES);
87    // Initialize CRC functions...
88    chksum_crc32gentab();
89 } // GPTData default constructor
90 
GPTData(const GPTData & orig)91 GPTData::GPTData(const GPTData & orig) {
92    uint32_t i;
93 
94    if (&orig != this) {
95       mainHeader = orig.mainHeader;
96       numParts = orig.numParts;
97       secondHeader = orig.secondHeader;
98       protectiveMBR = orig.protectiveMBR;
99       device = orig.device;
100       blockSize = orig.blockSize;
101       physBlockSize = orig.physBlockSize;
102       diskSize = orig.diskSize;
103       state = orig.state;
104       justLooking = orig.justLooking;
105       mainCrcOk = orig.mainCrcOk;
106       secondCrcOk = orig.secondCrcOk;
107       mainPartsCrcOk = orig.mainPartsCrcOk;
108       secondPartsCrcOk = orig.secondPartsCrcOk;
109       apmFound = orig.apmFound;
110       bsdFound = orig.bsdFound;
111       sectorAlignment = orig.sectorAlignment;
112       beQuiet = orig.beQuiet;
113       whichWasUsed = orig.whichWasUsed;
114 
115       myDisk.OpenForRead(orig.myDisk.GetName());
116 
117       delete[] partitions;
118       partitions = new GPTPart [numParts];
119       if (partitions == NULL) {
120          cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
121               << "Terminating!\n";
122          exit(1);
123       } // if
124       for (i = 0; i < numParts; i++) {
125          partitions[i] = orig.partitions[i];
126       } // for
127    } // if
128 } // GPTData copy constructor
129 
130 // The following constructor loads GPT data from a device file
GPTData(string filename)131 GPTData::GPTData(string filename) {
132    blockSize = SECTOR_SIZE; // set a default
133    diskSize = 0;
134    partitions = NULL;
135    state = gpt_invalid;
136    device = "";
137    justLooking = 0;
138    mainCrcOk = 0;
139    secondCrcOk = 0;
140    mainPartsCrcOk = 0;
141    secondPartsCrcOk = 0;
142    apmFound = 0;
143    bsdFound = 0;
144    sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
145    beQuiet = 0;
146    whichWasUsed = use_new;
147    mainHeader.numParts = 0;
148    mainHeader.lastUsableLBA = 0;
149    numParts = 0;
150    // Initialize CRC functions...
151    chksum_crc32gentab();
152    if (!LoadPartitions(filename))
153       exit(2);
154 } // GPTData(string filename) constructor
155 
156 // Destructor
~GPTData(void)157 GPTData::~GPTData(void) {
158    delete[] partitions;
159 } // GPTData destructor
160 
161 // Assignment operator
operator =(const GPTData & orig)162 GPTData & GPTData::operator=(const GPTData & orig) {
163    uint32_t i;
164 
165    if (&orig != this) {
166       mainHeader = orig.mainHeader;
167       numParts = orig.numParts;
168       secondHeader = orig.secondHeader;
169       protectiveMBR = orig.protectiveMBR;
170       device = orig.device;
171       blockSize = orig.blockSize;
172       physBlockSize = orig.physBlockSize;
173       diskSize = orig.diskSize;
174       state = orig.state;
175       justLooking = orig.justLooking;
176       mainCrcOk = orig.mainCrcOk;
177       secondCrcOk = orig.secondCrcOk;
178       mainPartsCrcOk = orig.mainPartsCrcOk;
179       secondPartsCrcOk = orig.secondPartsCrcOk;
180       apmFound = orig.apmFound;
181       bsdFound = orig.bsdFound;
182       sectorAlignment = orig.sectorAlignment;
183       beQuiet = orig.beQuiet;
184       whichWasUsed = orig.whichWasUsed;
185 
186       myDisk.OpenForRead(orig.myDisk.GetName());
187 
188       delete[] partitions;
189       partitions = new GPTPart [numParts];
190       if (partitions == NULL) {
191          cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
192               << "Terminating!\n";
193          exit(1);
194       } // if
195       for (i = 0; i < numParts; i++) {
196          partitions[i] = orig.partitions[i];
197       } // for
198    } // if
199 
200    return *this;
201 } // GPTData::operator=()
202 
203 /*********************************************************************
204  *                                                                   *
205  * Begin functions that verify data, or that adjust the verification *
206  * information (compute CRCs, rebuild headers)                       *
207  *                                                                   *
208  *********************************************************************/
209 
210 // Perform detailed verification, reporting on any problems found, but
211 // do *NOT* recover from these problems. Returns the total number of
212 // problems identified.
Verify(void)213 int GPTData::Verify(void) {
214    int problems = 0, alignProbs = 0;
215    uint32_t i, numSegments, testAlignment = sectorAlignment;
216    uint64_t totalFree, largestSegment;
217 
218    // First, check for CRC errors in the GPT data....
219    if (!mainCrcOk) {
220       problems++;
221       cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
222            << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
223            << "header ('b' on the recovery & transformation menu). This report may be a false\n"
224            << "alarm if you've already corrected other problems.\n";
225    } // if
226    if (!mainPartsCrcOk) {
227       problems++;
228       cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
229            << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
230            << "transformation menu). This report may be a false alarm if you've already\n"
231            << "corrected other problems.\n";
232    } // if
233    if (!secondCrcOk) {
234       problems++;
235       cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
236            << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
237            << "header ('d' on the recovery & transformation menu). This report may be a false\n"
238            << "alarm if you've already corrected other problems.\n";
239    } // if
240    if (!secondPartsCrcOk) {
241       problems++;
242       cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
243            << "be corrupt. This program will automatically create a new backup partition\n"
244            << "table when you save your partitions.\n";
245    } // if
246 
247    // Now check that the main and backup headers both point to themselves....
248    if (mainHeader.currentLBA != 1) {
249       problems++;
250       cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
251            << "is being automatically corrected, but it may be a symptom of more serious\n"
252            << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
253       mainHeader.currentLBA = 1;
254    } // if
255    if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
256       problems++;
257       cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
258            << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
259            << "option on the experts' menu to adjust the secondary header's and partition\n"
260            << "table's locations.\n";
261    } // if
262 
263    // Now check that critical main and backup GPT entries match each other
264    if (mainHeader.currentLBA != secondHeader.backupLBA) {
265       problems++;
266       cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
267            << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
268            << secondHeader.backupLBA << ").\n";
269    } // if
270    if (mainHeader.backupLBA != secondHeader.currentLBA) {
271       problems++;
272       cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
273            << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
274            << secondHeader.currentLBA << ").\n"
275            << "The 'e' option on the experts' menu may fix this problem.\n";
276    } // if
277    if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
278       problems++;
279       cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
280            << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
281            << secondHeader.firstUsableLBA << ")\n";
282    } // if
283    if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
284       problems++;
285       cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
286            << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
287            << secondHeader.lastUsableLBA << ")\n"
288            << "The 'e' option on the experts' menu can probably fix this problem.\n";
289    } // if
290    if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
291       problems++;
292       cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
293            << ") doesn't\nmatch the backup GPT header's disk GUID ("
294            << secondHeader.diskGUID << ")\n"
295            << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
296            << "select one or the other header.\n";
297    } // if
298    if (mainHeader.numParts != secondHeader.numParts) {
299       problems++;
300       cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
301            << ") doesn't\nmatch the backup GPT header's number of partitions ("
302            << secondHeader.numParts << ")\n"
303            << "Resizing the partition table ('s' on the experts' menu) may help.\n";
304    } // if
305    if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
306       problems++;
307       cout << "\nProblem: main GPT header's size of partition entries ("
308            << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
309            << "match the backup GPT header's size of partition entries ("
310            << secondHeader.sizeOfPartitionEntries << ")\n"
311            << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
312            << "select one or the other header.\n";
313    } // if
314 
315    // Now check for a few other miscellaneous problems...
316    // Check that the disk size will hold the data...
317    if (mainHeader.backupLBA >= diskSize) {
318       problems++;
319       cout << "\nProblem: Disk is too small to hold all the data!\n"
320            << "(Disk size is " << diskSize << " sectors, needs to be "
321            << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
322            << "The 'e' option on the experts' menu may fix this problem.\n";
323    } // if
324 
325    // Check the main and backup partition tables for overlap with things and unusual gaps
326    if (mainHeader.partitionEntriesLBA + GetTableSizeInSectors() > mainHeader.firstUsableLBA) {
327        problems++;
328        cout << "\nProblem: Main partition table extends past the first usable LBA.\n"
329             << "Using 'j' on the experts' menu may enable fixing this problem.\n";
330    } // if
331    if (mainHeader.partitionEntriesLBA < 2) {
332        problems++;
333        cout << "\nProblem: Main partition table appears impossibly early on the disk.\n"
334             << "Using 'j' on the experts' menu may enable fixing this problem.\n";
335    } // if
336    if (secondHeader.partitionEntriesLBA + GetTableSizeInSectors() > secondHeader.currentLBA) {
337        problems++;
338        cout << "\nProblem: The backup partition table overlaps the backup header.\n"
339             << "Using 'e' on the experts' menu may fix this problem.\n";
340    } // if
341    if (mainHeader.partitionEntriesLBA != 2) {
342        cout << "\nWarning: There is a gap between the main metadata (sector 1) and the main\n"
343             << "partition table (sector " << mainHeader.partitionEntriesLBA
344             << "). This is helpful in some exotic configurations,\n"
345             << "but is generally ill-advised. Using 'j' on the experts' menu can adjust this\n"
346             << "gap.\n";
347    } // if
348    if (mainHeader.partitionEntriesLBA + GetTableSizeInSectors() != mainHeader.firstUsableLBA) {
349        cout << "\nWarning: There is a gap between the main partition table (ending sector "
350             << mainHeader.partitionEntriesLBA + GetTableSizeInSectors() - 1 << ")\n"
351             << "and the first usable sector (" << mainHeader.firstUsableLBA << "). This is helpful in some exotic configurations,\n"
352             << "but is unusual. The util-linux fdisk program often creates disks like this.\n"
353             << "Using 'j' on the experts' menu can adjust this gap.\n";
354    } // if
355 
356    if (mainHeader.sizeOfPartitionEntries * mainHeader.numParts < 16384) {
357       cout << "\nWarning: The size of the partition table (" << mainHeader.sizeOfPartitionEntries * mainHeader.numParts
358            << " bytes) is less than the minimum\n"
359            << "required by the GPT specification. Most OSes and tools seem to work fine on\n"
360            << "such disks, but this is a violation of the GPT specification and so may cause\n"
361            << "problems.\n";
362    } // if
363 
364    if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
365       problems++;
366       cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
367            << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
368            << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
369            << "The 'e' option on the experts' menu will probably fix this problem\n";
370    }
371 
372    // Check for overlapping partitions....
373    problems += FindOverlaps();
374 
375    // Check for insane partitions (start after end, hugely big, etc.)
376    problems += FindInsanePartitions();
377 
378    // Check for mismatched MBR and GPT partitions...
379    problems += FindHybridMismatches();
380 
381    // Check for MBR-specific problems....
382    problems += VerifyMBR();
383 
384    // Check for a 0xEE protective partition that's marked as active....
385    if (protectiveMBR.IsEEActive()) {
386       cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
387            << "technically a violation of the GPT specification, and can cause some EFIs to\n"
388            << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
389            << "computers. You can clear this flag by creating a fresh protective MBR using\n"
390            << "the 'n' option on the experts' menu.\n";
391    }
392 
393    // Verify that partitions don't run into GPT data areas....
394    problems += CheckGPTSize();
395 
396    if (!protectiveMBR.DoTheyFit()) {
397       cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
398            << "fresh protective or hybrid MBR is recommended.\n";
399       problems++;
400    }
401 
402    // Check that partitions are aligned on proper boundaries (for WD Advanced
403    // Format and similar disks)....
404    if ((physBlockSize != 0) && (blockSize != 0))
405       testAlignment = physBlockSize / blockSize;
406    testAlignment = max(testAlignment, sectorAlignment);
407    if (testAlignment == 0) // Should not happen; just being paranoid.
408       testAlignment = sectorAlignment;
409    for (i = 0; i < numParts; i++) {
410       if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % testAlignment) != 0) {
411          cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
412               << testAlignment << "-sector boundary. This may\nresult "
413               << "in degraded performance on some modern (2009 and later) hard disks.\n";
414          alignProbs++;
415       } // if
416       if ((partitions[i].IsUsed()) && ((partitions[i].GetLastLBA() + 1) % testAlignment) != 0) {
417          cout << "\nCaution: Partition " << i + 1 << " doesn't end on a "
418               << testAlignment << "-sector boundary. This may\nresult "
419               << "in problems with some disk encryption tools.\n";
420       } // if
421    } // for
422    if (alignProbs > 0)
423       cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
424       << "for information on disk alignment.\n";
425 
426    // Now compute available space, but only if no problems found, since
427    // problems could affect the results
428    if (problems == 0) {
429       totalFree = FindFreeBlocks(&numSegments, &largestSegment);
430       cout << "\nNo problems found. " << totalFree << " free sectors ("
431            << BytesToIeee(totalFree, blockSize) << ") available in "
432            << numSegments << "\nsegments, the largest of which is "
433            << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
434            << ") in size.\n";
435    } else {
436       cout << "\nIdentified " << problems << " problems!\n";
437    } // if/else
438 
439    return (problems);
440 } // GPTData::Verify()
441 
442 // Checks to see if the GPT tables overrun existing partitions; if they
443 // do, issues a warning but takes no action. Returns number of problems
444 // detected (0 if OK, 1 to 2 if problems).
CheckGPTSize(void)445 int GPTData::CheckGPTSize(void) {
446    uint64_t overlap, firstUsedBlock, lastUsedBlock;
447    uint32_t i;
448    int numProbs = 0;
449 
450    // first, locate the first & last used blocks
451    firstUsedBlock = UINT64_MAX;
452    lastUsedBlock = 0;
453    for (i = 0; i < numParts; i++) {
454       if (partitions[i].IsUsed()) {
455          if (partitions[i].GetFirstLBA() < firstUsedBlock)
456             firstUsedBlock = partitions[i].GetFirstLBA();
457          if (partitions[i].GetLastLBA() > lastUsedBlock) {
458             lastUsedBlock = partitions[i].GetLastLBA();
459          } // if
460       } // if
461    } // for
462 
463    // If the disk size is 0 (the default), then it means that various
464    // variables aren't yet set, so the below tests will be useless;
465    // therefore we should skip everything
466    if (diskSize != 0) {
467       if (mainHeader.firstUsableLBA > firstUsedBlock) {
468          overlap = mainHeader.firstUsableLBA - firstUsedBlock;
469          cout << "Warning! Main partition table overlaps the first partition by "
470               << overlap << " blocks!\n";
471          if (firstUsedBlock > 2) {
472             cout << "Try reducing the partition table size by " << overlap * 4
473                  << " entries.\n(Use the 's' item on the experts' menu.)\n";
474          } else {
475             cout << "You will need to delete this partition or resize it in another utility.\n";
476          } // if/else
477          numProbs++;
478       } // Problem at start of disk
479       if (mainHeader.lastUsableLBA < lastUsedBlock) {
480          overlap = lastUsedBlock - mainHeader.lastUsableLBA;
481          cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
482               << overlap << " blocks!\n";
483          if (lastUsedBlock > (diskSize - 2)) {
484             cout << "You will need to delete this partition or resize it in another utility.\n";
485          } else {
486             cout << "Try reducing the partition table size by " << overlap * 4
487                  << " entries.\n(Use the 's' item on the experts' menu.)\n";
488          } // if/else
489          numProbs++;
490       } // Problem at end of disk
491    } // if (diskSize != 0)
492    return numProbs;
493 } // GPTData::CheckGPTSize()
494 
495 // Check the validity of the GPT header. Returns 1 if the main header
496 // is valid, 2 if the backup header is valid, 3 if both are valid, and
497 // 0 if neither is valid. Note that this function checks the GPT signature,
498 // revision value, and CRCs in both headers.
CheckHeaderValidity(void)499 int GPTData::CheckHeaderValidity(void) {
500    int valid = 3;
501 
502    cout.setf(ios::uppercase);
503    cout.fill('0');
504 
505    // Note: failed GPT signature checks produce no error message because
506    // a message is displayed in the ReversePartitionBytes() function
507    if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
508       valid -= 1;
509    } else if ((mainHeader.revision != 0x00010000) && valid) {
510       valid -= 1;
511       cout << "Unsupported GPT version in main header; read 0x";
512       cout.width(8);
513       cout << hex << mainHeader.revision << ", should be\n0x";
514       cout.width(8);
515       cout << UINT32_C(0x00010000) << dec << "\n";
516    } // if/else/if
517 
518    if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
519       valid -= 2;
520    } else if ((secondHeader.revision != 0x00010000) && valid) {
521       valid -= 2;
522       cout << "Unsupported GPT version in backup header; read 0x";
523       cout.width(8);
524       cout << hex << secondHeader.revision << ", should be\n0x";
525       cout.width(8);
526       cout << UINT32_C(0x00010000) << dec << "\n";
527    } // if/else/if
528 
529    // Check for an Apple disk signature
530    if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
531         (mainHeader.signature << 32) == APM_SIGNATURE2) {
532       apmFound = 1; // Will display warning message later
533    } // if
534    cout.fill(' ');
535 
536    return valid;
537 } // GPTData::CheckHeaderValidity()
538 
539 // Check the header CRC to see if it's OK...
540 // Note: Must be called with header in platform-ordered byte order.
541 // Returns 1 if header's computed CRC matches the stored value, 0 if the
542 // computed and stored values don't match
CheckHeaderCRC(struct GPTHeader * header,int warn)543 int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
544    uint32_t oldCRC, newCRC, hSize;
545    uint8_t *temp;
546 
547    // Back up old header CRC and then blank it, since it must be 0 for
548    // computation to be valid
549    oldCRC = header->headerCRC;
550    header->headerCRC = UINT32_C(0);
551 
552    hSize = header->headerSize;
553 
554    if (IsLittleEndian() == 0)
555       ReverseHeaderBytes(header);
556 
557    if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
558       if (warn) {
559          cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
560          cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
561       } // if
562       hSize = HEADER_SIZE;
563    } else if ((hSize > sizeof(GPTHeader)) && warn) {
564       cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
565       cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
566            << "which may result in a CRC false alarm.\n";
567    } // if/elseif
568    temp = new uint8_t[hSize];
569    if (temp != NULL) {
570       memset(temp, 0, hSize);
571       if (hSize < sizeof(GPTHeader))
572          memcpy(temp, header, hSize);
573       else
574          memcpy(temp, header, sizeof(GPTHeader));
575 
576       newCRC = chksum_crc32((unsigned char*) temp, hSize);
577       delete[] temp;
578    } else {
579       cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
580       exit(1);
581    }
582    if (IsLittleEndian() == 0)
583       ReverseHeaderBytes(header);
584    header->headerCRC = oldCRC;
585    return (oldCRC == newCRC);
586 } // GPTData::CheckHeaderCRC()
587 
588 // Recompute all the CRCs. Must be called before saving if any changes have
589 // been made. Must be called on platform-ordered data (this function reverses
590 // byte order and then undoes that reversal.)
RecomputeCRCs(void)591 void GPTData::RecomputeCRCs(void) {
592    uint32_t crc, hSize;
593    int littleEndian;
594 
595    // If the header size is bigger than the GPT header data structure, reset it;
596    // otherwise, set both header sizes to whatever the main one is....
597    if (mainHeader.headerSize > sizeof(GPTHeader))
598       hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
599    else
600       hSize = secondHeader.headerSize = mainHeader.headerSize;
601 
602    if ((littleEndian = IsLittleEndian()) == 0) {
603       ReversePartitionBytes();
604       ReverseHeaderBytes(&mainHeader);
605       ReverseHeaderBytes(&secondHeader);
606    } // if
607 
608    // Compute CRC of partition tables & store in main and secondary headers
609    crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
610    mainHeader.partitionEntriesCRC = crc;
611    secondHeader.partitionEntriesCRC = crc;
612    if (littleEndian == 0) {
613       ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
614       ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
615    } // if
616 
617    // Zero out GPT headers' own CRCs (required for correct computation)
618    mainHeader.headerCRC = 0;
619    secondHeader.headerCRC = 0;
620 
621    crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
622    if (littleEndian == 0)
623       ReverseBytes(&crc, 4);
624    mainHeader.headerCRC = crc;
625    crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
626    if (littleEndian == 0)
627       ReverseBytes(&crc, 4);
628    secondHeader.headerCRC = crc;
629 
630    if (littleEndian == 0) {
631       ReverseHeaderBytes(&mainHeader);
632       ReverseHeaderBytes(&secondHeader);
633       ReversePartitionBytes();
634    } // if
635 } // GPTData::RecomputeCRCs()
636 
637 // Rebuild the main GPT header, using the secondary header as a model.
638 // Typically called when the main header has been found to be corrupt.
RebuildMainHeader(void)639 void GPTData::RebuildMainHeader(void) {
640    mainHeader.signature = GPT_SIGNATURE;
641    mainHeader.revision = secondHeader.revision;
642    mainHeader.headerSize = secondHeader.headerSize;
643    mainHeader.headerCRC = UINT32_C(0);
644    mainHeader.reserved = secondHeader.reserved;
645    mainHeader.currentLBA = secondHeader.backupLBA;
646    mainHeader.backupLBA = secondHeader.currentLBA;
647    mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
648    mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
649    mainHeader.diskGUID = secondHeader.diskGUID;
650    mainHeader.numParts = secondHeader.numParts;
651    mainHeader.partitionEntriesLBA = secondHeader.firstUsableLBA - GetTableSizeInSectors();
652    mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
653    mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
654    memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
655    mainCrcOk = secondCrcOk;
656    SetGPTSize(mainHeader.numParts, 0);
657 } // GPTData::RebuildMainHeader()
658 
659 // Rebuild the secondary GPT header, using the main header as a model.
RebuildSecondHeader(void)660 void GPTData::RebuildSecondHeader(void) {
661    secondHeader.signature = GPT_SIGNATURE;
662    secondHeader.revision = mainHeader.revision;
663    secondHeader.headerSize = mainHeader.headerSize;
664    secondHeader.headerCRC = UINT32_C(0);
665    secondHeader.reserved = mainHeader.reserved;
666    secondHeader.currentLBA = mainHeader.backupLBA;
667    secondHeader.backupLBA = mainHeader.currentLBA;
668    secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
669    secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
670    secondHeader.diskGUID = mainHeader.diskGUID;
671    secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
672    secondHeader.numParts = mainHeader.numParts;
673    secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
674    secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
675    memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
676    secondCrcOk = mainCrcOk;
677    SetGPTSize(secondHeader.numParts, 0);
678 } // GPTData::RebuildSecondHeader()
679 
680 // Search for hybrid MBR entries that have no corresponding GPT partition.
681 // Returns number of such mismatches found
FindHybridMismatches(void)682 int GPTData::FindHybridMismatches(void) {
683    int i, found, numFound = 0;
684    uint32_t j;
685    uint64_t mbrFirst, mbrLast;
686 
687    for (i = 0; i < 4; i++) {
688       if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
689          j = 0;
690          found = 0;
691          mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
692          mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
693          do {
694             if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
695                 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
696                found = 1;
697             j++;
698          } while ((!found) && (j < numParts));
699          if (!found) {
700             numFound++;
701             cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
702                  << i + 1 << ", of type 0x";
703             cout.fill('0');
704             cout.setf(ios::uppercase);
705             cout.width(2);
706             cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
707                  << "has no corresponding GPT partition! You may continue, but this condition\n"
708                  << "might cause data loss in the future!\a\n" << dec;
709             cout.fill(' ');
710          } // if
711       } // if
712    } // for
713    return numFound;
714 } // GPTData::FindHybridMismatches
715 
716 // Find overlapping partitions and warn user about them. Returns number of
717 // overlapping partitions.
718 // Returns number of overlapping segments found.
FindOverlaps(void)719 int GPTData::FindOverlaps(void) {
720    int problems = 0;
721    uint32_t i, j;
722 
723    for (i = 1; i < numParts; i++) {
724       for (j = 0; j < i; j++) {
725          if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
726              (partitions[i].DoTheyOverlap(partitions[j]))) {
727             problems++;
728             cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
729             cout << "  Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
730                  << " to " << partitions[i].GetLastLBA() << "\n";
731             cout << "  Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
732                  << " to " << partitions[j].GetLastLBA() << "\n";
733          } // if
734       } // for j...
735    } // for i...
736    return problems;
737 } // GPTData::FindOverlaps()
738 
739 // Find partitions that are insane -- they start after they end or are too
740 // big for the disk. (The latter should duplicate detection of overlaps
741 // with GPT backup data structures, but better to err on the side of
742 // redundant tests than to miss something....)
743 // Returns number of problems found.
FindInsanePartitions(void)744 int GPTData::FindInsanePartitions(void) {
745    uint32_t i;
746    int problems = 0;
747 
748    for (i = 0; i < numParts; i++) {
749       if (partitions[i].IsUsed()) {
750          if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
751             problems++;
752             cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
753          } // if
754          if (partitions[i].GetLastLBA() >= diskSize) {
755             problems++;
756             cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
757          } // if
758       } // if
759    } // for
760    return problems;
761 } // GPTData::FindInsanePartitions(void)
762 
763 
764 /******************************************************************
765  *                                                                *
766  * Begin functions that load data from disk or save data to disk. *
767  *                                                                *
768  ******************************************************************/
769 
770 // Change the filename associated with the GPT. Used for duplicating
771 // the partition table to a new disk and saving backups.
772 // Returns 1 on success, 0 on failure.
SetDisk(const string & deviceFilename)773 int GPTData::SetDisk(const string & deviceFilename) {
774    int err, allOK = 1;
775 
776    device = deviceFilename;
777    if (allOK && myDisk.OpenForRead(deviceFilename)) {
778       // store disk information....
779       diskSize = myDisk.DiskSize(&err);
780       blockSize = (uint32_t) myDisk.GetBlockSize();
781       physBlockSize = (uint32_t) myDisk.GetPhysBlockSize();
782    } // if
783    protectiveMBR.SetDisk(&myDisk);
784    protectiveMBR.SetDiskSize(diskSize);
785    protectiveMBR.SetBlockSize(blockSize);
786    return allOK;
787 } // GPTData::SetDisk()
788 
SetDisk(const DiskIO & disk)789 int GPTData::SetDisk(const DiskIO & disk) {
790    myDisk = disk;
791    return 1;
792 } // GPTData::SetDisk()
793 
794 // Scan for partition data. This function loads the MBR data (regular MBR or
795 // protective MBR) and loads BSD disklabel data (which is probably invalid).
796 // It also looks for APM data, forces a load of GPT data, and summarizes
797 // the results.
PartitionScan(void)798 void GPTData::PartitionScan(void) {
799    BSDData bsdDisklabel;
800 
801    // Read the MBR & check for BSD disklabel
802    protectiveMBR.ReadMBRData(&myDisk);
803    bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
804 
805    // Load the GPT data, whether or not it's valid
806    ForceLoadGPTData();
807 
808    // Some tools create a 0xEE partition that's too big. If this is detected,
809    // normalize it....
810    if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
811       if (!beQuiet) {
812          cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
813       } // if
814       protectiveMBR.MakeProtectiveMBR();
815    } // if
816 
817    if (!beQuiet) {
818       cout << "Partition table scan:\n";
819       protectiveMBR.ShowState();
820       bsdDisklabel.ShowState();
821       ShowAPMState(); // Show whether there's an Apple Partition Map present
822       ShowGPTState(); // Show GPT status
823       cout << "\n";
824    } // if
825 
826    if (apmFound) {
827       cout << "\n*******************************************************************\n"
828            << "This disk appears to contain an Apple-format (APM) partition table!\n";
829       if (!justLooking) {
830          cout << "It will be destroyed if you continue!\n";
831       } // if
832       cout << "*******************************************************************\n\n\a";
833    } // if
834 } // GPTData::PartitionScan()
835 
836 // Read GPT data from a disk.
LoadPartitions(const string & deviceFilename)837 int GPTData::LoadPartitions(const string & deviceFilename) {
838    BSDData bsdDisklabel;
839    int err, allOK = 1;
840    MBRValidity mbrState;
841 
842    if (myDisk.OpenForRead(deviceFilename)) {
843       err = myDisk.OpenForWrite(deviceFilename);
844       if ((err == 0) && (!justLooking)) {
845          cout << "\aNOTE: Write test failed with error number " << errno
846               << ". It will be impossible to save\nchanges to this disk's partition table!\n";
847 #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
848          cout << "You may be able to enable writes by exiting this program, typing\n"
849               << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
850               << "program.\n";
851 #endif
852 #if defined (__APPLE__)
853          cout << "You may need to deactivate System Integrity Protection to use this program. See\n"
854               << "https://www.quora.com/How-do-I-turn-off-the-rootless-in-OS-X-El-Capitan-10-11\n"
855               << "for more information.\n";
856 #endif
857               cout << "\n";
858       } // if
859       myDisk.Close(); // Close and re-open read-only in case of bugs
860    } else allOK = 0; // if
861 
862    if (allOK && myDisk.OpenForRead(deviceFilename)) {
863       // store disk information....
864       diskSize = myDisk.DiskSize(&err);
865       blockSize = (uint32_t) myDisk.GetBlockSize();
866       physBlockSize = (uint32_t) myDisk.GetPhysBlockSize();
867       device = deviceFilename;
868       PartitionScan(); // Check for partition types, load GPT, & print summary
869 
870       whichWasUsed = UseWhichPartitions();
871       switch (whichWasUsed) {
872          case use_mbr:
873             XFormPartitions();
874             break;
875          case use_bsd:
876             bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
877 //            bsdDisklabel.DisplayBSDData();
878             ClearGPTData();
879             protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
880             XFormDisklabel(&bsdDisklabel);
881             break;
882          case use_gpt:
883             mbrState = protectiveMBR.GetValidity();
884             if ((mbrState == invalid) || (mbrState == mbr))
885                protectiveMBR.MakeProtectiveMBR();
886             break;
887          case use_new:
888             ClearGPTData();
889             protectiveMBR.MakeProtectiveMBR();
890             break;
891          case use_abort:
892             allOK = 0;
893             cerr << "Invalid partition data!\n";
894             break;
895       } // switch
896 
897       if (allOK) {
898          CheckGPTSize();
899          // Below is unlikely to happen on real disks, but could happen if
900          // the user is manipulating a truncated image file....
901          if (diskSize <= GetTableSizeInSectors() * 2 + 3) {
902              allOK = 0;
903              cout << "Disk is too small to hold GPT data (" << diskSize
904                   << " sectors)! Aborting!\n";
905          }
906       }
907       myDisk.Close();
908       ComputeAlignment();
909    } else {
910       allOK = 0;
911    } // if/else
912    return (allOK);
913 } // GPTData::LoadPartitions()
914 
915 // Loads the GPT, as much as possible. Returns 1 if this seems to have
916 // succeeded, 0 if there are obvious problems....
ForceLoadGPTData(void)917 int GPTData::ForceLoadGPTData(void) {
918    int allOK, validHeaders, loadedTable = 1;
919 
920    allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
921 
922    if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
923       allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
924    } else {
925       allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
926       if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
927          cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
928               << "secondary header from the last sector of the disk! You should use 'v' to\n"
929               << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
930               << "the disk.\n";
931    } // if/else
932    if (!allOK)
933       state = gpt_invalid;
934 
935    // Return valid headers code: 0 = both headers bad; 1 = main header
936    // good, backup bad; 2 = backup header good, main header bad;
937    // 3 = both headers good. Note these codes refer to valid GPT
938    // signatures, version numbers, and CRCs.
939    validHeaders = CheckHeaderValidity();
940 
941    // Read partitions (from primary array)
942    if (validHeaders > 0) { // if at least one header is OK....
943       // GPT appears to be valid....
944       state = gpt_valid;
945 
946       // We're calling the GPT valid, but there's a possibility that one
947       // of the two headers is corrupt. If so, use the one that seems to
948       // be in better shape to regenerate the bad one
949       if (validHeaders == 1) { // valid main header, invalid backup header
950          cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
951               << "backup header from main header.\n\n";
952          RebuildSecondHeader();
953          state = gpt_corrupt;
954          secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
955       } else if (validHeaders == 2) { // valid backup header, invalid main header
956          cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
957               << "from backup!\n\n";
958          RebuildMainHeader();
959          state = gpt_corrupt;
960          mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
961       } // if/else/if
962 
963       // Figure out which partition table to load....
964       // Load the main partition table, if its header's CRC is OK
965       if (validHeaders != 2) {
966          if (LoadMainTable() == 0)
967             allOK = 0;
968       } else { // bad main header CRC and backup header CRC is OK
969          state = gpt_corrupt;
970          if (LoadSecondTableAsMain()) {
971             loadedTable = 2;
972             cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
973          } else { // backup table bad, bad main header CRC, but try main table in desperation....
974             if (LoadMainTable() == 0) {
975                allOK = 0;
976                loadedTable = 0;
977                cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
978             } // if
979          } // if/else (LoadSecondTableAsMain())
980       } // if/else (load partition table)
981 
982       if (loadedTable == 1)
983          secondPartsCrcOk = CheckTable(&secondHeader);
984       else if (loadedTable == 2)
985          mainPartsCrcOk = CheckTable(&mainHeader);
986       else
987          mainPartsCrcOk = secondPartsCrcOk = 0;
988 
989       // Problem with main partition table; if backup is OK, use it instead....
990       if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
991          state = gpt_corrupt;
992          allOK = allOK && LoadSecondTableAsMain();
993          mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
994          cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
995               << "partition table\ninstead of main partition table!\n\n";
996       } // if */
997 
998       // Check for valid CRCs and warn if there are problems
999       if ((validHeaders != 3) || (mainPartsCrcOk == 0) ||
1000            (secondPartsCrcOk == 0)) {
1001          cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n";
1002          // Show detail status of header and table
1003          if (validHeaders & 0x1)
1004             cerr << "Main header: OK\n";
1005          else
1006             cerr << "Main header: ERROR\n";
1007          if (validHeaders & 0x2)
1008             cerr << "Backup header: OK\n";
1009          else
1010             cerr << "Backup header: ERROR\n";
1011          if (mainPartsCrcOk)
1012             cerr << "Main partition table: OK\n";
1013          else
1014             cerr << "Main partition table: ERROR\n";
1015          if (secondPartsCrcOk)
1016             cerr << "Backup partition table: OK\n";
1017          else
1018             cerr << "Backup partition table: ERROR\n";
1019          cerr << "\n";
1020          state = gpt_corrupt;
1021       } // if
1022    } else {
1023       state = gpt_invalid;
1024    } // if/else
1025    return allOK;
1026 } // GPTData::ForceLoadGPTData()
1027 
1028 // Loads the partition table pointed to by the main GPT header. The
1029 // main GPT header in memory MUST be valid for this call to do anything
1030 // sensible!
1031 // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadMainTable(void)1032 int GPTData::LoadMainTable(void) {
1033    return LoadPartitionTable(mainHeader, myDisk);
1034 } // GPTData::LoadMainTable()
1035 
1036 // Load the second (backup) partition table as the primary partition
1037 // table. Used in repair functions, and when starting up if the main
1038 // partition table is damaged.
1039 // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadSecondTableAsMain(void)1040 int GPTData::LoadSecondTableAsMain(void) {
1041    return LoadPartitionTable(secondHeader, myDisk);
1042 } // GPTData::LoadSecondTableAsMain()
1043 
1044 // Load a single GPT header (main or backup) from the specified disk device and
1045 // sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
1046 // value appropriately.
1047 // Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
1048 // failure.
LoadHeader(struct GPTHeader * header,DiskIO & disk,uint64_t sector,int * crcOk)1049 int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
1050    int allOK = 1;
1051    GPTHeader tempHeader;
1052 
1053    disk.Seek(sector);
1054    if (disk.Read(&tempHeader, 512) != 512) {
1055       cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
1056       allOK = 0;
1057    } // if
1058 
1059    // Reverse byte order, if necessary
1060    if (IsLittleEndian() == 0) {
1061       ReverseHeaderBytes(&tempHeader);
1062    } // if
1063    *crcOk = CheckHeaderCRC(&tempHeader);
1064 
1065    if (tempHeader.sizeOfPartitionEntries != sizeof(GPTPart)) {
1066       // Print the below warning only if the CRC is OK -- but correct the
1067       // problem either way. The warning is printed only on a valid CRC
1068       // because otherwise this warning will display inappropriately when
1069       // reading MBR disks. If the CRC is invalid, then a warning about
1070       // that will be shown later, so the user will still know that
1071       // something is wrong.
1072       if (*crcOk) {
1073          cerr << "Warning: Partition table header claims that the size of partition table\n";
1074          cerr << "entries is " << tempHeader.sizeOfPartitionEntries << " bytes, but this program ";
1075          cerr << " supports only " << sizeof(GPTPart) << "-byte entries.\n";
1076          cerr << "Adjusting accordingly, but partition table may be garbage.\n";
1077       }
1078       tempHeader.sizeOfPartitionEntries = sizeof(GPTPart);
1079    }
1080 
1081    if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
1082       allOK = SetGPTSize(tempHeader.numParts, 0);
1083    }
1084 
1085    *header = tempHeader;
1086    return allOK;
1087 } // GPTData::LoadHeader
1088 
1089 // Load a partition table (either main or secondary) from the specified disk,
1090 // using header as a reference for what to load. If sector != 0 (the default
1091 // is 0), loads from the specified sector; otherwise loads from the sector
1092 // indicated in header.
1093 // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadPartitionTable(const struct GPTHeader & header,DiskIO & disk,uint64_t sector)1094 int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
1095    uint32_t sizeOfParts, newCRC;
1096    int retval;
1097 
1098    if (header.sizeOfPartitionEntries != sizeof(GPTPart)) {
1099       cerr << "Error! GPT header contains invalid partition entry size!\n";
1100       retval = 0;
1101    } else if (disk.OpenForRead()) {
1102       if (sector == 0) {
1103          retval = disk.Seek(header.partitionEntriesLBA);
1104       } else {
1105          retval = disk.Seek(sector);
1106       } // if/else
1107       if (retval == 1)
1108          retval = SetGPTSize(header.numParts, 0);
1109       if (retval == 1) {
1110          sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
1111          if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
1112             cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
1113             retval = 0;
1114          } // if
1115          newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
1116          mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
1117          if (IsLittleEndian() == 0)
1118             ReversePartitionBytes();
1119          if (!mainPartsCrcOk) {
1120             cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
1121          } // if
1122       } else {
1123          cerr << "Error! Couldn't seek to partition table!\n";
1124       } // if/else
1125    } else {
1126       cerr << "Error! Couldn't open device " << device
1127            << " when reading partition table!\n";
1128       retval = 0;
1129    } // if/else
1130    return retval;
1131 } // GPTData::LoadPartitionsTable()
1132 
1133 // Check the partition table pointed to by header, but don't keep it
1134 // around.
1135 // Returns 1 if the CRC is OK & this table matches the one already in memory,
1136 // 0 if not or if there was a read error.
CheckTable(struct GPTHeader * header)1137 int GPTData::CheckTable(struct GPTHeader *header) {
1138    uint32_t sizeOfParts, newCRC;
1139    GPTPart *partsToCheck;
1140    GPTHeader *otherHeader;
1141    int allOK = 0;
1142 
1143    // Load partition table into temporary storage to check
1144    // its CRC and store the results, then discard this temporary
1145    // storage, since we don't use it in any but recovery operations
1146    if (myDisk.Seek(header->partitionEntriesLBA)) {
1147       partsToCheck = new GPTPart[header->numParts];
1148       sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
1149       if (partsToCheck == NULL) {
1150          cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
1151          exit(1);
1152       } // if
1153       if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
1154          cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
1155       } else {
1156          newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
1157          allOK = (newCRC == header->partitionEntriesCRC);
1158          if (header == &mainHeader)
1159             otherHeader = &secondHeader;
1160          else
1161             otherHeader = &mainHeader;
1162          if (newCRC != otherHeader->partitionEntriesCRC) {
1163             cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
1164                  << "on the recovery & transformation menu to examine the two tables.\n\n";
1165             allOK = 0;
1166          } // if
1167       } // if/else
1168       delete[] partsToCheck;
1169    } // if
1170    return allOK;
1171 } // GPTData::CheckTable()
1172 
1173 // Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1174 // header later on the disk without asking for permission, if necessary, and
1175 // doesn't confirm the operation before writing. If quiet==0, asks permission
1176 // before moving the second header and asks for final confirmation of any
1177 // write.
1178 // Returns 1 on successful write, 0 if there was a problem.
SaveGPTData(int quiet)1179 int GPTData::SaveGPTData(int quiet) {
1180    int allOK = 1, syncIt = 1;
1181    char answer;
1182 
1183    // First do some final sanity checks....
1184 
1185    // This test should only fail on read-only disks....
1186    if (justLooking) {
1187       cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
1188       allOK = 0;
1189    } // if
1190 
1191    // Check that disk is really big enough to handle the second header...
1192    if (mainHeader.backupLBA >= diskSize) {
1193       cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1194            << "header, but other problems may occur!\n";
1195       MoveSecondHeaderToEnd();
1196    } // if
1197 
1198    // Is there enough space to hold the GPT headers and partition tables,
1199    // given the partition sizes?
1200    if (CheckGPTSize() > 0) {
1201       allOK = 0;
1202    } // if
1203 
1204    // Check that second header is properly placed. Warn and ask if this should
1205    // be corrected if the test fails....
1206    if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1207       if (quiet == 0) {
1208          cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1209               << "correct this problem? ";
1210          if (GetYN() == 'Y') {
1211             MoveSecondHeaderToEnd();
1212             cout << "Have moved second header and partition table to correct location.\n";
1213          } else {
1214             cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1215          } // if correction requested
1216       } else { // Go ahead and do correction automatically
1217          MoveSecondHeaderToEnd();
1218       } // if/else quiet
1219    } // if
1220 
1221    if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1222       if (quiet == 0) {
1223          cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1224               << "this problem? ";
1225          if (GetYN() == 'Y') {
1226             MoveSecondHeaderToEnd();
1227             cout << "Have adjusted the second header and last usable sector value.\n";
1228          } else {
1229             cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1230          } // if correction requested
1231       } else { // go ahead and do correction automatically
1232          MoveSecondHeaderToEnd();
1233       } // if/else quiet
1234    } // if
1235 
1236    // Check for overlapping or insane partitions....
1237    if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
1238       allOK = 0;
1239       cerr << "Aborting write operation!\n";
1240    } // if
1241 
1242    // Check that protective MBR fits, and warn if it doesn't....
1243    if (!protectiveMBR.DoTheyFit()) {
1244       cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1245            << "fresh protective or hybrid MBR is recommended.\n";
1246    }
1247 
1248    // Check for mismatched MBR and GPT data, but let it pass if found
1249    // (function displays warning message)
1250    FindHybridMismatches();
1251 
1252    RecomputeCRCs();
1253 
1254    if ((allOK) && (!quiet)) {
1255       cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
1256            << "PARTITIONS!!\n\nDo you want to proceed? ";
1257       answer = GetYN();
1258       if (answer == 'Y') {
1259          cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
1260       } else {
1261          allOK = 0;
1262       } // if/else
1263    } // if
1264 
1265    // Do it!
1266    if (allOK) {
1267       if (myDisk.OpenForWrite()) {
1268          // As per UEFI specs, write the secondary table and GPT first....
1269          allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1270          if (!allOK) {
1271             cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1272                  << "menu will resolve this problem.\n";
1273             syncIt = 0;
1274          } // if
1275 
1276          // Now write the secondary GPT header...
1277          allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1278 
1279          // Now write the main partition tables...
1280          allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1281 
1282          // Now write the main GPT header...
1283          allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1284 
1285          // To top it off, write the protective MBR...
1286          allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
1287 
1288          // re-read the partition table
1289          // Note: Done even if some write operations failed, but not if all of them failed.
1290          // Done this way because I've received one problem report from a user one whose
1291          // system the MBR write failed but everything else was OK (on a GPT disk under
1292          // Windows), and the failure to sync therefore caused Windows to restore the
1293          // original partition table from its cache. OTOH, such restoration might be
1294          // desirable if the error occurs later; but that seems unlikely unless the initial
1295          // write fails....
1296          if (syncIt)
1297             myDisk.DiskSync();
1298 
1299          if (allOK) { // writes completed OK
1300             cout << "The operation has completed successfully.\n";
1301          } else {
1302             cerr << "Warning! An error was reported when writing the partition table! This error\n"
1303                  << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
1304          } // if/else
1305 
1306          myDisk.Close();
1307       } else {
1308          cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
1309               << errno << "! Aborting write!\n";
1310          allOK = 0;
1311       } // if/else
1312    } else {
1313       cout << "Aborting write of new partition table.\n";
1314    } // if
1315 
1316    return (allOK);
1317 } // GPTData::SaveGPTData()
1318 
1319 // Save GPT data to a backup file. This function does much less error
1320 // checking than SaveGPTData(). It can therefore preserve many types of
1321 // corruption for later analysis; however, it preserves only the MBR,
1322 // the main GPT header, the backup GPT header, and the main partition
1323 // table; it discards the backup partition table, since it should be
1324 // identical to the main partition table on healthy disks.
SaveGPTBackup(const string & filename)1325 int GPTData::SaveGPTBackup(const string & filename) {
1326    int allOK = 1;
1327    DiskIO backupFile;
1328 
1329    if (backupFile.OpenForWrite(filename)) {
1330       // Recomputing the CRCs is likely to alter them, which could be bad
1331       // if the intent is to save a potentially bad GPT for later analysis;
1332       // but if we don't do this, we get bogus errors when we load the
1333       // backup. I'm favoring misses over false alarms....
1334       RecomputeCRCs();
1335 
1336       protectiveMBR.WriteMBRData(&backupFile);
1337       protectiveMBR.SetDisk(&myDisk);
1338 
1339       if (allOK) {
1340          // MBR write closed disk, so re-open and seek to end....
1341          backupFile.OpenForWrite();
1342          allOK = SaveHeader(&mainHeader, backupFile, 1);
1343       } // if (allOK)
1344 
1345       if (allOK)
1346          allOK = SaveHeader(&secondHeader, backupFile, 2);
1347 
1348       if (allOK)
1349          allOK = SavePartitionTable(backupFile, 3);
1350 
1351       if (allOK) { // writes completed OK
1352          cout << "The operation has completed successfully.\n";
1353       } else {
1354          cerr << "Warning! An error was reported when writing the backup file.\n"
1355               << "It may not be usable!\n";
1356       } // if/else
1357       backupFile.Close();
1358    } else {
1359       cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
1360       allOK = 0;
1361    } // if/else
1362    return allOK;
1363 } // GPTData::SaveGPTBackup()
1364 
1365 // Write a GPT header (main or backup) to the specified sector. Used by both
1366 // the SaveGPTData() and SaveGPTBackup() functions.
1367 // Should be passed an architecture-appropriate header (DO NOT call
1368 // ReverseHeaderBytes() on the header before calling this function)
1369 // Returns 1 on success, 0 on failure
SaveHeader(struct GPTHeader * header,DiskIO & disk,uint64_t sector)1370 int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1371    int littleEndian, allOK = 1;
1372 
1373    littleEndian = IsLittleEndian();
1374    if (!littleEndian)
1375       ReverseHeaderBytes(header);
1376    if (disk.Seek(sector)) {
1377       if (disk.Write(header, 512) == -1)
1378          allOK = 0;
1379    } else allOK = 0; // if (disk.Seek()...)
1380    if (!littleEndian)
1381       ReverseHeaderBytes(header);
1382    return allOK;
1383 } // GPTData::SaveHeader()
1384 
1385 // Save the partitions to the specified sector. Used by both the SaveGPTData()
1386 // and SaveGPTBackup() functions.
1387 // Should be passed an architecture-appropriate header (DO NOT call
1388 // ReverseHeaderBytes() on the header before calling this function)
1389 // Returns 1 on success, 0 on failure
SavePartitionTable(DiskIO & disk,uint64_t sector)1390 int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1391    int littleEndian, allOK = 1;
1392 
1393    littleEndian = IsLittleEndian();
1394    if (disk.Seek(sector)) {
1395       if (!littleEndian)
1396          ReversePartitionBytes();
1397       if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
1398          allOK = 0;
1399       if (!littleEndian)
1400          ReversePartitionBytes();
1401    } else allOK = 0; // if (myDisk.Seek()...)
1402    return allOK;
1403 } // GPTData::SavePartitionTable()
1404 
1405 // Load GPT data from a backup file created by SaveGPTBackup(). This function
1406 // does minimal error checking. It returns 1 if it completed successfully,
1407 // 0 if there was a problem. In the latter case, it creates a new empty
1408 // set of partitions.
LoadGPTBackup(const string & filename)1409 int GPTData::LoadGPTBackup(const string & filename) {
1410    int allOK = 1, val, err;
1411    int shortBackup = 0;
1412    DiskIO backupFile;
1413 
1414    if (backupFile.OpenForRead(filename)) {
1415       // Let the MBRData class load the saved MBR...
1416       protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
1417       protectiveMBR.SetDisk(&myDisk);
1418 
1419       LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
1420 
1421       // Check backup file size and rebuild second header if file is right
1422       // size to be direct dd copy of MBR, main header, and main partition
1423       // table; if other size, treat it like a GPT fdisk-generated backup
1424       // file
1425       shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1426                      (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1427       if (shortBackup) {
1428          RebuildSecondHeader();
1429          secondCrcOk = mainCrcOk;
1430       } else {
1431          LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1432       } // if/else
1433 
1434       // Return valid headers code: 0 = both headers bad; 1 = main header
1435       // good, backup bad; 2 = backup header good, main header bad;
1436       // 3 = both headers good. Note these codes refer to valid GPT
1437       // signatures and version numbers; more subtle problems will elude
1438       // this check!
1439       if ((val = CheckHeaderValidity()) > 0) {
1440          if (val == 2) { // only backup header seems to be good
1441             SetGPTSize(secondHeader.numParts, 0);
1442          } else { // main header is OK
1443             SetGPTSize(mainHeader.numParts, 0);
1444          } // if/else
1445 
1446          if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
1447             cout << "Warning! Current disk size doesn't match that of the backup!\n"
1448                  << "Adjusting sizes to match, but subsequent problems are possible!\n";
1449             MoveSecondHeaderToEnd();
1450          } // if
1451 
1452          if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1453             cerr << "Warning! Read error " << errno
1454                  << " loading partition table; strange behavior now likely!\n";
1455       } else {
1456          allOK = 0;
1457       } // if/else
1458       // Something went badly wrong, so blank out partitions
1459       if (allOK == 0) {
1460          cerr << "Improper backup file! Clearing all partition data!\n";
1461          ClearGPTData();
1462          protectiveMBR.MakeProtectiveMBR();
1463       } // if
1464    } else {
1465       allOK = 0;
1466       cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
1467    } // if/else
1468 
1469    return allOK;
1470 } // GPTData::LoadGPTBackup()
1471 
SaveMBR(void)1472 int GPTData::SaveMBR(void) {
1473    return protectiveMBR.WriteMBRData(&myDisk);
1474 } // GPTData::SaveMBR()
1475 
1476 // This function destroys the on-disk GPT structures, but NOT the on-disk
1477 // MBR.
1478 // Returns 1 if the operation succeeds, 0 if not.
DestroyGPT(void)1479 int GPTData::DestroyGPT(void) {
1480    int sum, tableSize, allOK = 1;
1481    uint8_t blankSector[512];
1482    uint8_t* emptyTable;
1483 
1484    memset(blankSector, 0, sizeof(blankSector));
1485    ClearGPTData();
1486 
1487    if (myDisk.OpenForWrite()) {
1488       if (!myDisk.Seek(mainHeader.currentLBA))
1489          allOK = 0;
1490       if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1491          cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1492          allOK = 0;
1493       } // if
1494       if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1495          allOK = 0;
1496       tableSize = numParts * mainHeader.sizeOfPartitionEntries;
1497       emptyTable = new uint8_t[tableSize];
1498       if (emptyTable == NULL) {
1499          cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
1500          exit(1);
1501       } // if
1502       memset(emptyTable, 0, tableSize);
1503       if (allOK) {
1504          sum = myDisk.Write(emptyTable, tableSize);
1505          if (sum != tableSize) {
1506             cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1507             allOK = 0;
1508          } // if write failed
1509       } // if
1510       if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1511          allOK = 0;
1512       if (allOK) {
1513          sum = myDisk.Write(emptyTable, tableSize);
1514          if (sum != tableSize) {
1515             cerr << "Warning! GPT backup partition table not overwritten! Error is "
1516                  << errno << "\n";
1517             allOK = 0;
1518          } // if wrong size written
1519       } // if
1520       if (!myDisk.Seek(secondHeader.currentLBA))
1521          allOK = 0;
1522       if (allOK) {
1523          if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1524             cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1525             allOK = 0;
1526          } // if
1527       } // if
1528       myDisk.DiskSync();
1529       myDisk.Close();
1530       cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1531            << "other utilities.\n";
1532       delete[] emptyTable;
1533    } else {
1534       cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
1535    } // if/else (fd != -1)
1536    return (allOK);
1537 } // GPTDataTextUI::DestroyGPT()
1538 
1539 // Wipe MBR data from the disk (zero it out completely)
1540 // Returns 1 on success, 0 on failure.
DestroyMBR(void)1541 int GPTData::DestroyMBR(void) {
1542    int allOK;
1543    uint8_t blankSector[512];
1544 
1545    memset(blankSector, 0, sizeof(blankSector));
1546 
1547    allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1548 
1549    if (!allOK)
1550       cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1551    return allOK;
1552 } // GPTData::DestroyMBR(void)
1553 
1554 // Tell user whether Apple Partition Map (APM) was discovered....
ShowAPMState(void)1555 void GPTData::ShowAPMState(void) {
1556    if (apmFound)
1557       cout << "  APM: present\n";
1558    else
1559       cout << "  APM: not present\n";
1560 } // GPTData::ShowAPMState()
1561 
1562 // Tell user about the state of the GPT data....
ShowGPTState(void)1563 void GPTData::ShowGPTState(void) {
1564    switch (state) {
1565       case gpt_invalid:
1566          cout << "  GPT: not present\n";
1567          break;
1568       case gpt_valid:
1569          cout << "  GPT: present\n";
1570          break;
1571       case gpt_corrupt:
1572          cout << "  GPT: damaged\n";
1573          break;
1574       default:
1575          cout << "\a  GPT: unknown -- bug!\n";
1576          break;
1577    } // switch
1578 } // GPTData::ShowGPTState()
1579 
1580 // Display the basic GPT data
DisplayGPTData(void)1581 void GPTData::DisplayGPTData(void) {
1582    uint32_t i;
1583    uint64_t temp, totalFree;
1584 
1585    cout << "Disk " << device << ": " << diskSize << " sectors, "
1586         << BytesToIeee(diskSize, blockSize) << "\n";
1587    if (myDisk.GetModel() != "")
1588       cout << "Model: " << myDisk.GetModel() << "\n";
1589    if (physBlockSize > 0)
1590       cout << "Sector size (logical/physical): " << blockSize << "/" << physBlockSize << " bytes\n";
1591    else
1592       cout << "Sector size (logical): " << blockSize << " bytes\n";
1593    cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
1594    cout << "Partition table holds up to " << numParts << " entries\n";
1595    cout << "Main partition table begins at sector " << mainHeader.partitionEntriesLBA
1596         << " and ends at sector " << mainHeader.partitionEntriesLBA + GetTableSizeInSectors() - 1 << "\n";
1597    cout << "First usable sector is " << mainHeader.firstUsableLBA
1598         << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
1599    totalFree = FindFreeBlocks(&i, &temp);
1600    cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
1601    cout << "Total free space is " << totalFree << " sectors ("
1602         << BytesToIeee(totalFree, blockSize) << ")\n";
1603    cout << "\nNumber  Start (sector)    End (sector)  Size       Code  Name\n";
1604    for (i = 0; i < numParts; i++) {
1605       partitions[i].ShowSummary(i, blockSize);
1606    } // for
1607 } // GPTData::DisplayGPTData()
1608 
1609 // Show detailed information on the specified partition
ShowPartDetails(uint32_t partNum)1610 void GPTData::ShowPartDetails(uint32_t partNum) {
1611    if ((partNum < numParts) && !IsFreePartNum(partNum)) {
1612       partitions[partNum].ShowDetails(blockSize);
1613    } else {
1614       cout << "Partition #" << partNum + 1 << " does not exist.\n";
1615    } // if
1616 } // GPTData::ShowPartDetails()
1617 
1618 /**************************************************************************
1619  *                                                                        *
1620  * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1621  * (some of these functions may require user interaction)                 *
1622  *                                                                        *
1623  **************************************************************************/
1624 
1625 // Examines the MBR & GPT data to determine which set of data to use: the
1626 // MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1627 // a new set of partitions (use_new). A return value of use_abort indicates
1628 // that this function couldn't determine what to do. Overriding functions
1629 // in derived classes may ask users questions in such cases.
UseWhichPartitions(void)1630 WhichToUse GPTData::UseWhichPartitions(void) {
1631    WhichToUse which = use_new;
1632    MBRValidity mbrState;
1633 
1634    mbrState = protectiveMBR.GetValidity();
1635 
1636    if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
1637       cout << "\n***************************************************************\n"
1638            << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1639            << "in memory. ";
1640       if (!justLooking) {
1641          cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1642               << "typing 'q' if you don't want to convert your MBR partitions\n"
1643               << "to GPT format!";
1644       } // if
1645       cout << "\n***************************************************************\n\n";
1646       which = use_mbr;
1647    } // if
1648 
1649    if ((state == gpt_invalid) && bsdFound) {
1650       cout << "\n**********************************************************************\n"
1651            << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1652            << "to GPT format.";
1653       if ((!justLooking) && (!beQuiet)) {
1654       cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
1655            << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1656            << "want to convert your BSD partitions to GPT format!";
1657       } // if
1658       cout << "\n**********************************************************************\n\n";
1659       which = use_bsd;
1660    } // if
1661 
1662    if ((state == gpt_valid) && (mbrState == gpt)) {
1663       which = use_gpt;
1664       if (!beQuiet)
1665          cout << "Found valid GPT with protective MBR; using GPT.\n";
1666    } // if
1667    if ((state == gpt_valid) && (mbrState == hybrid)) {
1668       which = use_gpt;
1669       if (!beQuiet)
1670          cout << "Found valid GPT with hybrid MBR; using GPT.\n";
1671    } // if
1672    if ((state == gpt_valid) && (mbrState == invalid)) {
1673       cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
1674            << "protective MBR on save.\n";
1675       which = use_gpt;
1676    } // if
1677    if ((state == gpt_valid) && (mbrState == mbr)) {
1678       which = use_abort;
1679    } // if
1680 
1681    if (state == gpt_corrupt) {
1682       if (mbrState == gpt) {
1683          cout << "\a\a****************************************************************************\n"
1684               << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1685               << "verification and recovery are STRONGLY recommended.\n"
1686               << "****************************************************************************\n";
1687          which = use_gpt;
1688       } else {
1689          which = use_abort;
1690       } // if/else MBR says disk is GPT
1691    } // if GPT corrupt
1692 
1693    if (which == use_new)
1694       cout << "Creating new GPT entries in memory.\n";
1695 
1696    return which;
1697 } // UseWhichPartitions()
1698 
1699 // Convert MBR partition table into GPT form.
XFormPartitions(void)1700 void GPTData::XFormPartitions(void) {
1701    int i, numToConvert;
1702    uint8_t origType;
1703 
1704    // Clear out old data & prepare basics....
1705    ClearGPTData();
1706 
1707    // Convert the smaller of the # of GPT or MBR partitions
1708    if (numParts > MAX_MBR_PARTS)
1709       numToConvert = MAX_MBR_PARTS;
1710    else
1711       numToConvert = numParts;
1712 
1713    for (i = 0; i < numToConvert; i++) {
1714       origType = protectiveMBR.GetType(i);
1715       // don't waste CPU time trying to convert extended, hybrid protective, or
1716       // null (non-existent) partitions
1717       if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
1718           (origType != 0x00) && (origType != 0xEE))
1719          partitions[i] = protectiveMBR.AsGPT(i);
1720    } // for
1721 
1722    // Convert MBR into protective MBR
1723    protectiveMBR.MakeProtectiveMBR();
1724 
1725    // Record that all original CRCs were OK so as not to raise flags
1726    // when doing a disk verification
1727    mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1728 } // GPTData::XFormPartitions()
1729 
1730 // Transforms BSD disklabel on the specified partition (numbered from 0).
1731 // If an invalid partition number is given, the program does nothing.
1732 // Returns the number of new partitions created.
XFormDisklabel(uint32_t partNum)1733 int GPTData::XFormDisklabel(uint32_t partNum) {
1734    uint32_t low, high;
1735    int goOn = 1, numDone = 0;
1736    BSDData disklabel;
1737 
1738    if (GetPartRange(&low, &high) == 0) {
1739       goOn = 0;
1740       cout << "No partitions!\n";
1741    } // if
1742    if (partNum > high) {
1743       goOn = 0;
1744       cout << "Specified partition is invalid!\n";
1745    } // if
1746 
1747    // If all is OK, read the disklabel and convert it.
1748    if (goOn) {
1749       goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1750                                    partitions[partNum].GetLastLBA());
1751       if ((goOn) && (disklabel.IsDisklabel())) {
1752          numDone = XFormDisklabel(&disklabel);
1753          if (numDone == 1)
1754             cout << "Converted 1 BSD partition.\n";
1755          else
1756             cout << "Converted " << numDone << " BSD partitions.\n";
1757       } else {
1758          cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1759       } // if/else
1760    } // if
1761    if (numDone > 0) { // converted partitions; delete carrier
1762       partitions[partNum].BlankPartition();
1763    } // if
1764    return numDone;
1765 } // GPTData::XFormDisklabel(uint32_t i)
1766 
1767 // Transform the partitions on an already-loaded BSD disklabel...
XFormDisklabel(BSDData * disklabel)1768 int GPTData::XFormDisklabel(BSDData* disklabel) {
1769    int i, partNum = 0, numDone = 0;
1770 
1771    if (disklabel->IsDisklabel()) {
1772       for (i = 0; i < disklabel->GetNumParts(); i++) {
1773          partNum = FindFirstFreePart();
1774          if (partNum >= 0) {
1775             partitions[partNum] = disklabel->AsGPT(i);
1776             if (partitions[partNum].IsUsed())
1777                numDone++;
1778          } // if
1779       } // for
1780       if (partNum == -1)
1781          cerr << "Warning! Too many partitions to convert!\n";
1782    } // if
1783 
1784    // Record that all original CRCs were OK so as not to raise flags
1785    // when doing a disk verification
1786    mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1787 
1788    return numDone;
1789 } // GPTData::XFormDisklabel(BSDData* disklabel)
1790 
1791 // Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1792 // partition has the active/bootable flag UNset and uses the GPT fdisk
1793 // type code divided by 0x0100 as the MBR type code.
1794 // Returns 1 if operation was 100% successful, 0 if there were ANY
1795 // problems.
OnePartToMBR(uint32_t gptPart,int mbrPart)1796 int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1797    int allOK = 1;
1798 
1799    if ((mbrPart < 0) || (mbrPart > 3)) {
1800       cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
1801       allOK = 0;
1802    } // if
1803    if (gptPart >= numParts) {
1804       cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
1805       allOK = 0;
1806    } // if
1807    if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
1808       cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
1809       allOK = 0;
1810    } // if
1811    if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1812        (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1813       if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
1814          cout << "Caution: Partition end point past 32-bit pointer boundary;"
1815               << " some OSes may\nreact strangely.\n";
1816       } // if
1817       protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1818                              (uint32_t) partitions[gptPart].GetLengthLBA(),
1819                              partitions[gptPart].GetHexType() / 256, 0);
1820    } else { // partition out of range
1821       if (allOK) // Display only if "else" triggered by out-of-bounds condition
1822          cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1823               << "partitions, or is\n too big; omitting it.\n";
1824       allOK = 0;
1825    } // if/else
1826    return allOK;
1827 } // GPTData::OnePartToMBR()
1828 
1829 
1830 /**********************************************************************
1831  *                                                                    *
1832  * Functions that adjust GPT data structures WITHOUT user interaction *
1833  * (they may display information for the user's benefit, though)      *
1834  *                                                                    *
1835  **********************************************************************/
1836 
1837 // Resizes GPT to specified number of entries. Creates a new table if
1838 // necessary, copies data if it already exists. If fillGPTSectors is 1
1839 // (the default), rounds numEntries to fill all the sectors necessary to
1840 // hold the GPT.
1841 // Returns 1 if all goes well, 0 if an error is encountered.
SetGPTSize(uint32_t numEntries,int fillGPTSectors)1842 int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
1843    GPTPart* newParts;
1844    uint32_t i, high, copyNum, entriesPerSector;
1845    int allOK = 1;
1846 
1847    // First, adjust numEntries upward, if necessary, to get a number
1848    // that fills the allocated sectors
1849    entriesPerSector = blockSize / GPT_SIZE;
1850    if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
1851       cout << "Adjusting GPT size from " << numEntries << " to ";
1852       numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
1853       cout << numEntries << " to fill the sector\n";
1854    } // if
1855 
1856    // Do the work only if the # of partitions is changing. Along with being
1857    // efficient, this prevents mucking with the location of the secondary
1858    // partition table, which causes problems when loading data from a RAID
1859    // array that's been expanded because this function is called when loading
1860    // data.
1861    if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
1862       newParts = new GPTPart [numEntries];
1863       if (newParts != NULL) {
1864          if (partitions != NULL) { // existing partitions; copy them over
1865             GetPartRange(&i, &high);
1866             if (numEntries < (high + 1)) { // Highest entry too high for new #
1867                cout << "The highest-numbered partition is " << high + 1
1868                     << ", which is greater than the requested\n"
1869                     << "partition table size of " << numEntries
1870                     << "; cannot resize. Perhaps sorting will help.\n";
1871                allOK = 0;
1872                delete[] newParts;
1873             } else { // go ahead with copy
1874                if (numEntries < numParts)
1875                   copyNum = numEntries;
1876                else
1877                   copyNum = numParts;
1878                for (i = 0; i < copyNum; i++) {
1879                   newParts[i] = partitions[i];
1880                } // for
1881                delete[] partitions;
1882                partitions = newParts;
1883             } // if
1884          } else { // No existing partition table; just create it
1885             partitions = newParts;
1886          } // if/else existing partitions
1887          numParts = numEntries;
1888          mainHeader.firstUsableLBA = GetTableSizeInSectors() + mainHeader.partitionEntriesLBA;
1889          secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1890          MoveSecondHeaderToEnd();
1891          if (diskSize > 0)
1892             CheckGPTSize();
1893       } else { // Bad memory allocation
1894          cerr << "Error allocating memory for partition table! Size is unchanged!\n";
1895          allOK = 0;
1896       } // if/else
1897    } // if/else
1898    mainHeader.numParts = numParts;
1899    secondHeader.numParts = numParts;
1900    return (allOK);
1901 } // GPTData::SetGPTSize()
1902 
1903 // Change the start sector for the main partition table.
1904 // Returns 1 on success, 0 on failure
MoveMainTable(uint64_t pteSector)1905 int GPTData::MoveMainTable(uint64_t pteSector) {
1906     uint64_t pteSize = GetTableSizeInSectors();
1907     int retval = 1;
1908 
1909     if ((pteSector >= 2) && ((pteSector + pteSize) <= FindFirstUsedLBA())) {
1910        mainHeader.partitionEntriesLBA = pteSector;
1911        mainHeader.firstUsableLBA = pteSector + pteSize;
1912        RebuildSecondHeader();
1913     } else {
1914        cerr << "Unable to set the main partition table's location to " << pteSector << "!\n";
1915        retval = 0;
1916     } // if/else
1917     return retval;
1918 } // GPTData::MoveMainTable()
1919 
1920 // Blank the partition array
BlankPartitions(void)1921 void GPTData::BlankPartitions(void) {
1922    uint32_t i;
1923 
1924    for (i = 0; i < numParts; i++) {
1925       partitions[i].BlankPartition();
1926    } // for
1927 } // GPTData::BlankPartitions()
1928 
1929 // Delete a partition by number. Returns 1 if successful,
1930 // 0 if there was a problem. Returns 1 if partition was in
1931 // range, 0 if it was out of range.
DeletePartition(uint32_t partNum)1932 int GPTData::DeletePartition(uint32_t partNum) {
1933    uint64_t startSector, length;
1934    uint32_t low, high, numUsedParts, retval = 1;;
1935 
1936    numUsedParts = GetPartRange(&low, &high);
1937    if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
1938       // In case there's a protective MBR, look for & delete matching
1939       // MBR partition....
1940       startSector = partitions[partNum].GetFirstLBA();
1941       length = partitions[partNum].GetLengthLBA();
1942       protectiveMBR.DeleteByLocation(startSector, length);
1943 
1944       // Now delete the GPT partition
1945       partitions[partNum].BlankPartition();
1946    } else {
1947       cerr << "Partition number " << partNum + 1 << " out of range!\n";
1948       retval = 0;
1949    } // if/else
1950    return retval;
1951 } // GPTData::DeletePartition(uint32_t partNum)
1952 
1953 // Non-interactively create a partition.
1954 // Returns 1 if the operation was successful, 0 if a problem was discovered.
CreatePartition(uint32_t partNum,uint64_t startSector,uint64_t endSector)1955 uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
1956    int retval = 1; // assume there'll be no problems
1957    uint64_t origSector = startSector;
1958 
1959    if (IsFreePartNum(partNum)) {
1960       if (Align(&startSector)) {
1961          cout << "Information: Moved requested sector from " << origSector << " to "
1962               << startSector << " in\norder to align on " << sectorAlignment
1963               << "-sector boundaries.\n";
1964       } // if
1965       if (IsFree(startSector) && (startSector <= endSector)) {
1966          if (FindLastInFree(startSector) >= endSector) {
1967             partitions[partNum].SetFirstLBA(startSector);
1968             partitions[partNum].SetLastLBA(endSector);
1969             partitions[partNum].SetType(DEFAULT_GPT_TYPE);
1970             partitions[partNum].RandomizeUniqueGUID();
1971          } else retval = 0; // if free space until endSector
1972       } else retval = 0; // if startSector is free
1973    } else retval = 0; // if legal partition number
1974    return retval;
1975 } // GPTData::CreatePartition(partNum, startSector, endSector)
1976 
1977 // Sort the GPT entries, eliminating gaps and making for a logical
1978 // ordering.
SortGPT(void)1979 void GPTData::SortGPT(void) {
1980    if (numParts > 0)
1981       sort(partitions, partitions + numParts);
1982 } // GPTData::SortGPT()
1983 
1984 // Swap the contents of two partitions.
1985 // Returns 1 if successful, 0 if either partition is out of range
1986 // (that is, not a legal number; either or both can be empty).
1987 // Note that if partNum1 = partNum2 and this number is in range,
1988 // it will be considered successful.
SwapPartitions(uint32_t partNum1,uint32_t partNum2)1989 int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1990    GPTPart temp;
1991    int allOK = 1;
1992 
1993    if ((partNum1 < numParts) && (partNum2 < numParts)) {
1994       if (partNum1 != partNum2) {
1995          temp = partitions[partNum1];
1996          partitions[partNum1] = partitions[partNum2];
1997          partitions[partNum2] = temp;
1998       } // if
1999    } else allOK = 0; // partition numbers are valid
2000    return allOK;
2001 } // GPTData::SwapPartitions()
2002 
2003 // Set up data structures for entirely new set of partitions on the
2004 // specified device. Returns 1 if OK, 0 if there were problems.
2005 // Note that this function does NOT clear the protectiveMBR data
2006 // structure, since it may hold the original MBR partitions if the
2007 // program was launched on an MBR disk, and those may need to be
2008 // converted to GPT format.
ClearGPTData(void)2009 int GPTData::ClearGPTData(void) {
2010    int goOn = 1, i;
2011 
2012    // Set up the partition table....
2013    delete[] partitions;
2014    partitions = NULL;
2015    SetGPTSize(NUM_GPT_ENTRIES);
2016 
2017    // Now initialize a bunch of stuff that's static....
2018    mainHeader.signature = GPT_SIGNATURE;
2019    mainHeader.revision = 0x00010000;
2020    mainHeader.headerSize = HEADER_SIZE;
2021    mainHeader.reserved = 0;
2022    mainHeader.currentLBA = UINT64_C(1);
2023    mainHeader.partitionEntriesLBA = (uint64_t) 2;
2024    mainHeader.sizeOfPartitionEntries = GPT_SIZE;
2025    mainHeader.firstUsableLBA = GetTableSizeInSectors() + mainHeader.partitionEntriesLBA;
2026    for (i = 0; i < GPT_RESERVED; i++) {
2027       mainHeader.reserved2[i] = '\0';
2028    } // for
2029    if (blockSize > 0)
2030       sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2031    else
2032       sectorAlignment = DEFAULT_ALIGNMENT;
2033 
2034    // Now some semi-static items (computed based on end of disk)
2035    mainHeader.backupLBA = diskSize - UINT64_C(1);
2036    mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2037 
2038    // Set a unique GUID for the disk, based on random numbers
2039    mainHeader.diskGUID.Randomize();
2040 
2041    // Copy main header to backup header
2042    RebuildSecondHeader();
2043 
2044    // Blank out the partitions array....
2045    BlankPartitions();
2046 
2047    // Flag all CRCs as being OK....
2048    mainCrcOk = 1;
2049    secondCrcOk = 1;
2050    mainPartsCrcOk = 1;
2051    secondPartsCrcOk = 1;
2052 
2053    return (goOn);
2054 } // GPTData::ClearGPTData()
2055 
2056 // Set the location of the second GPT header data to the end of the disk.
2057 // If the disk size has actually changed, this also adjusts the protective
2058 // entry in the MBR, since it's probably no longer correct.
2059 // Used internally and called by the 'e' option on the recovery &
2060 // transformation menu, to help users of RAID arrays who add disk space
2061 // to their arrays or to adjust data structures in restore operations
2062 // involving unequal-sized disks.
MoveSecondHeaderToEnd()2063 void GPTData::MoveSecondHeaderToEnd() {
2064    mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2065    if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
2066       if (protectiveMBR.GetValidity() == hybrid) {
2067          protectiveMBR.OptimizeEESize();
2068          RecomputeCHS();
2069       } // if
2070       if (protectiveMBR.GetValidity() == gpt)
2071          MakeProtectiveMBR();
2072    } // if
2073    mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2074    secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2075 } // GPTData::FixSecondHeaderLocation()
2076 
2077 // Sets the partition's name to the specified UnicodeString without
2078 // user interaction.
2079 // Returns 1 on success, 0 on failure (invalid partition number).
SetName(uint32_t partNum,const UnicodeString & theName)2080 int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
2081    int retval = 1;
2082 
2083    if (IsUsedPartNum(partNum))
2084       partitions[partNum].SetName(theName);
2085    else
2086       retval = 0;
2087 
2088    return retval;
2089 } // GPTData::SetName
2090 
2091 // Set the disk GUID to the specified value. Note that the header CRCs must
2092 // be recomputed after calling this function.
SetDiskGUID(GUIDData newGUID)2093 void GPTData::SetDiskGUID(GUIDData newGUID) {
2094    mainHeader.diskGUID = newGUID;
2095    secondHeader.diskGUID = newGUID;
2096 } // SetDiskGUID()
2097 
2098 // Set the unique GUID of the specified partition. Returns 1 on
2099 // successful completion, 0 if there were problems (invalid
2100 // partition number).
SetPartitionGUID(uint32_t pn,GUIDData theGUID)2101 int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2102    int retval = 0;
2103 
2104    if (pn < numParts) {
2105       if (partitions[pn].IsUsed()) {
2106          partitions[pn].SetUniqueGUID(theGUID);
2107          retval = 1;
2108       } // if
2109    } // if
2110    return retval;
2111 } // GPTData::SetPartitionGUID()
2112 
2113 // Set new random GUIDs for the disk and all partitions. Intended to be used
2114 // after disk cloning or similar operations that don't randomize the GUIDs.
RandomizeGUIDs(void)2115 void GPTData::RandomizeGUIDs(void) {
2116    uint32_t i;
2117 
2118    mainHeader.diskGUID.Randomize();
2119    secondHeader.diskGUID = mainHeader.diskGUID;
2120    for (i = 0; i < numParts; i++)
2121       if (partitions[i].IsUsed())
2122          partitions[i].RandomizeUniqueGUID();
2123 } // GPTData::RandomizeGUIDs()
2124 
2125 // Change partition type code non-interactively. Returns 1 if
2126 // successful, 0 if not....
ChangePartType(uint32_t partNum,PartType theGUID)2127 int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
2128    int retval = 1;
2129 
2130    if (!IsFreePartNum(partNum)) {
2131       partitions[partNum].SetType(theGUID);
2132    } else retval = 0;
2133    return retval;
2134 } // GPTData::ChangePartType()
2135 
2136 // Recompute the CHS values of all the MBR partitions. Used to reset
2137 // CHS values that some BIOSes require, despite the fact that the
2138 // resulting CHS values violate the GPT standard.
RecomputeCHS(void)2139 void GPTData::RecomputeCHS(void) {
2140    int i;
2141 
2142    for (i = 0; i < 4; i++)
2143       protectiveMBR.RecomputeCHS(i);
2144 } // GPTData::RecomputeCHS()
2145 
2146 // Adjust sector number so that it falls on a sector boundary that's a
2147 // multiple of sectorAlignment. This is done to improve the performance
2148 // of Western Digital Advanced Format disks and disks with similar
2149 // technology from other companies, which use 4096-byte sectors
2150 // internally although they translate to 512-byte sectors for the
2151 // benefit of the OS. If partitions aren't properly aligned on these
2152 // disks, some filesystem data structures can span multiple physical
2153 // sectors, degrading performance. This function should be called
2154 // only on the FIRST sector of the partition, not the last!
2155 // This function returns 1 if the alignment was altered, 0 if it
2156 // was unchanged.
Align(uint64_t * sector)2157 int GPTData::Align(uint64_t* sector) {
2158    int retval = 0, sectorOK = 0;
2159    uint64_t earlier, later, testSector;
2160 
2161    if ((*sector % sectorAlignment) != 0) {
2162       earlier = (*sector / sectorAlignment) * sectorAlignment;
2163       later = earlier + (uint64_t) sectorAlignment;
2164 
2165       // Check to see that every sector between the earlier one and the
2166       // requested one is clear, and that it's not too early....
2167       if (earlier >= mainHeader.firstUsableLBA) {
2168          testSector = earlier;
2169          do {
2170             sectorOK = IsFree(testSector++);
2171          } while ((sectorOK == 1) && (testSector < *sector));
2172          if (sectorOK == 1) {
2173             *sector = earlier;
2174             retval = 1;
2175          } // if
2176       } // if firstUsableLBA check
2177 
2178       // If couldn't move the sector earlier, try to move it later instead....
2179       if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2180          testSector = later;
2181          do {
2182             sectorOK = IsFree(testSector--);
2183          } while ((sectorOK == 1) && (testSector > *sector));
2184          if (sectorOK == 1) {
2185             *sector = later;
2186             retval = 1;
2187          } // if
2188       } // if
2189    } // if
2190    return retval;
2191 } // GPTData::Align()
2192 
2193 /********************************************************
2194  *                                                      *
2195  * Functions that return data about GPT data structures *
2196  * (most of these are inline in gpt.h)                  *
2197  *                                                      *
2198  ********************************************************/
2199 
2200 // Find the low and high used partition numbers (numbered from 0).
2201 // Return value is the number of partitions found. Note that the
2202 // *low and *high values are both set to 0 when no partitions
2203 // are found, as well as when a single partition in the first
2204 // position exists. Thus, the return value is the only way to
2205 // tell when no partitions exist.
GetPartRange(uint32_t * low,uint32_t * high)2206 int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2207    uint32_t i;
2208    int numFound = 0;
2209 
2210    *low = numParts + 1; // code for "not found"
2211    *high = 0;
2212    for (i = 0; i < numParts; i++) {
2213       if (partitions[i].IsUsed()) { // it exists
2214          *high = i; // since we're counting up, set the high value
2215          // Set the low value only if it's not yet found...
2216          if (*low == (numParts + 1)) *low = i;
2217             numFound++;
2218       } // if
2219    } // for
2220 
2221    // Above will leave *low pointing to its "not found" value if no partitions
2222    // are defined, so reset to 0 if this is the case....
2223    if (*low == (numParts + 1))
2224       *low = 0;
2225    return numFound;
2226 } // GPTData::GetPartRange()
2227 
2228 // Returns the value of the first free partition, or -1 if none is
2229 // unused.
FindFirstFreePart(void)2230 int GPTData::FindFirstFreePart(void) {
2231    int i = 0;
2232 
2233    if (partitions != NULL) {
2234       while ((i < (int) numParts) && (partitions[i].IsUsed()))
2235          i++;
2236       if (i >= (int) numParts)
2237          i = -1;
2238    } else i = -1;
2239    return i;
2240 } // GPTData::FindFirstFreePart()
2241 
2242 // Returns the number of defined partitions.
CountParts(void)2243 uint32_t GPTData::CountParts(void) {
2244    uint32_t i, counted = 0;
2245 
2246    for (i = 0; i < numParts; i++) {
2247       if (partitions[i].IsUsed())
2248          counted++;
2249    } // for
2250    return counted;
2251 } // GPTData::CountParts()
2252 
2253 /****************************************************
2254  *                                                  *
2255  * Functions that return data about disk free space *
2256  *                                                  *
2257  ****************************************************/
2258 
2259 // Find the first available block after the starting point; returns 0 if
2260 // there are no available blocks left
FindFirstAvailable(uint64_t start)2261 uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2262    uint64_t first;
2263    uint32_t i;
2264    int firstMoved = 0;
2265 
2266    // Begin from the specified starting point or from the first usable
2267    // LBA, whichever is greater...
2268    if (start < mainHeader.firstUsableLBA)
2269       first = mainHeader.firstUsableLBA;
2270    else
2271       first = start;
2272 
2273    // ...now search through all partitions; if first is within an
2274    // existing partition, move it to the next sector after that
2275    // partition and repeat. If first was moved, set firstMoved
2276    // flag; repeat until firstMoved is not set, so as to catch
2277    // cases where partitions are out of sequential order....
2278    do {
2279       firstMoved = 0;
2280       for (i = 0; i < numParts; i++) {
2281          if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
2282              (first <= partitions[i].GetLastLBA())) { // in existing part.
2283             first = partitions[i].GetLastLBA() + 1;
2284             firstMoved = 1;
2285          } // if
2286       } // for
2287    } while (firstMoved == 1);
2288    if (first > mainHeader.lastUsableLBA)
2289       first = 0;
2290    return (first);
2291 } // GPTData::FindFirstAvailable()
2292 
2293 // Returns the LBA of the start of the first partition on the disk (by
2294 // sector number), or 0 if there are no partitions defined.
FindFirstUsedLBA(void)2295 uint64_t GPTData::FindFirstUsedLBA(void) {
2296     uint32_t i;
2297     uint64_t firstFound = UINT64_MAX;
2298 
2299     for (i = 0; i < numParts; i++) {
2300         if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() < firstFound)) {
2301             firstFound = partitions[i].GetFirstLBA();
2302         } // if
2303     } // for
2304     return firstFound;
2305 } // GPTData::FindFirstUsedLBA()
2306 
2307 // Finds the first available sector in the largest block of unallocated
2308 // space on the disk. Returns 0 if there are no available blocks left
FindFirstInLargest(void)2309 uint64_t GPTData::FindFirstInLargest(void) {
2310    uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
2311 
2312    start = 0;
2313    do {
2314       firstBlock = FindFirstAvailable(start);
2315       if (firstBlock != UINT32_C(0)) { // something's free...
2316          lastBlock = FindLastInFree(firstBlock);
2317          segmentSize = lastBlock - firstBlock + UINT32_C(1);
2318          if (segmentSize > selectedSize) {
2319             selectedSize = segmentSize;
2320             selectedSegment = firstBlock;
2321          } // if
2322          start = lastBlock + 1;
2323       } // if
2324    } while (firstBlock != 0);
2325    return selectedSegment;
2326 } // GPTData::FindFirstInLargest()
2327 
2328 // Find the last available block on the disk.
2329 // Returns 0 if there are no available sectors
FindLastAvailable(void)2330 uint64_t GPTData::FindLastAvailable(void) {
2331    uint64_t last;
2332    uint32_t i;
2333    int lastMoved = 0;
2334 
2335    // Start by assuming the last usable LBA is available....
2336    last = mainHeader.lastUsableLBA;
2337 
2338    // ...now, similar to algorithm in FindFirstAvailable(), search
2339    // through all partitions, moving last when it's in an existing
2340    // partition. Set the lastMoved flag so we repeat to catch cases
2341    // where partitions are out of logical order.
2342    do {
2343       lastMoved = 0;
2344       for (i = 0; i < numParts; i++) {
2345          if ((last >= partitions[i].GetFirstLBA()) &&
2346              (last <= partitions[i].GetLastLBA())) { // in existing part.
2347             last = partitions[i].GetFirstLBA() - 1;
2348             lastMoved = 1;
2349          } // if
2350       } // for
2351    } while (lastMoved == 1);
2352    if (last < mainHeader.firstUsableLBA)
2353       last = 0;
2354    return (last);
2355 } // GPTData::FindLastAvailable()
2356 
2357 // Find the last available block in the free space pointed to by start.
2358 // If align == true, returns the last sector that's aligned on the
2359 // system alignment value (unless that's less than the start value);
2360 // if align == false, returns the last available block regardless of
2361 // alignment. (The align variable is set to false by default.)
FindLastInFree(uint64_t start,bool align)2362 uint64_t GPTData::FindLastInFree(uint64_t start, bool align) {
2363    uint64_t nearestEnd, endPlus;
2364    uint32_t i;
2365 
2366    nearestEnd = mainHeader.lastUsableLBA;
2367    for (i = 0; i < numParts; i++) {
2368       if ((nearestEnd > partitions[i].GetFirstLBA()) &&
2369           (partitions[i].GetFirstLBA() > start)) {
2370          nearestEnd = partitions[i].GetFirstLBA() - 1;
2371       } // if
2372    } // for
2373    if (align) {
2374        endPlus = nearestEnd + 1;
2375        if (Align(&endPlus) && IsFree(endPlus - 1) && (endPlus > start)) {
2376            nearestEnd = endPlus - 1;
2377        } // if
2378    } // if
2379    return (nearestEnd);
2380 } // GPTData::FindLastInFree()
2381 
2382 // Finds the total number of free blocks, the number of segments in which
2383 // they reside, and the size of the largest of those segments
FindFreeBlocks(uint32_t * numSegments,uint64_t * largestSegment)2384 uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
2385    uint64_t start = UINT64_C(0); // starting point for each search
2386    uint64_t totalFound = UINT64_C(0); // running total
2387    uint64_t firstBlock; // first block in a segment
2388    uint64_t lastBlock; // last block in a segment
2389    uint64_t segmentSize; // size of segment in blocks
2390    uint32_t num = 0;
2391 
2392    *largestSegment = UINT64_C(0);
2393    if (diskSize > 0) {
2394       do {
2395          firstBlock = FindFirstAvailable(start);
2396          if (firstBlock != UINT64_C(0)) { // something's free...
2397             lastBlock = FindLastInFree(firstBlock);
2398             segmentSize = lastBlock - firstBlock + UINT64_C(1);
2399             if (segmentSize > *largestSegment) {
2400                *largestSegment = segmentSize;
2401             } // if
2402             totalFound += segmentSize;
2403             num++;
2404             start = lastBlock + 1;
2405          } // if
2406       } while (firstBlock != 0);
2407    } // if
2408    *numSegments = num;
2409    return totalFound;
2410 } // GPTData::FindFreeBlocks()
2411 
2412 // Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2413 // If it's allocated, return the partition number to which it's allocated
2414 // in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2415 // returned in partNum if the sector is in use by basic GPT data structures.)
IsFree(uint64_t sector,uint32_t * partNum)2416 int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
2417    int isFree = 1;
2418    uint32_t i;
2419 
2420    for (i = 0; i < numParts; i++) {
2421       if ((sector >= partitions[i].GetFirstLBA()) &&
2422            (sector <= partitions[i].GetLastLBA())) {
2423          isFree = 0;
2424          if (partNum != NULL)
2425             *partNum = i;
2426       } // if
2427    } // for
2428    if ((sector < mainHeader.firstUsableLBA) ||
2429         (sector > mainHeader.lastUsableLBA)) {
2430       isFree = 0;
2431       if (partNum != NULL)
2432          *partNum = UINT32_MAX;
2433    } // if
2434    return (isFree);
2435 } // GPTData::IsFree()
2436 
2437 // Returns 1 if partNum is unused AND if it's a legal value.
IsFreePartNum(uint32_t partNum)2438 int GPTData::IsFreePartNum(uint32_t partNum) {
2439    return ((partNum < numParts) && (partitions != NULL) &&
2440            (!partitions[partNum].IsUsed()));
2441 } // GPTData::IsFreePartNum()
2442 
2443 // Returns 1 if partNum is in use.
IsUsedPartNum(uint32_t partNum)2444 int GPTData::IsUsedPartNum(uint32_t partNum) {
2445    return ((partNum < numParts) && (partitions != NULL) &&
2446            (partitions[partNum].IsUsed()));
2447 } // GPTData::IsUsedPartNum()
2448 
2449 /***********************************************************
2450  *                                                         *
2451  * Change how functions work or return information on them *
2452  *                                                         *
2453  ***********************************************************/
2454 
2455 // Set partition alignment value; partitions will begin on multiples of
2456 // the specified value, and the default end values will be set so that
2457 // partition sizes are multiples of this value in cgdisk and gdisk, too.
2458 // (In sgdisk, end-alignment is done only if the '-I' command-line option
2459 // is used.)
SetAlignment(uint32_t n)2460 void GPTData::SetAlignment(uint32_t n) {
2461    if (n > 0) {
2462       sectorAlignment = n;
2463       if ((physBlockSize > 0) && (n % (physBlockSize / blockSize) != 0)) {
2464          cout << "Warning: Setting alignment to a value that does not match the disk's\n"
2465               << "physical block size! Performance degradation may result!\n"
2466               << "Physical block size = " << physBlockSize << "\n"
2467               << "Logical block size = " << blockSize << "\n"
2468               << "Optimal alignment = " << physBlockSize / blockSize << " or multiples thereof.\n";
2469       } // if
2470    } else {
2471       cerr << "Attempt to set partition alignment to 0!\n";
2472    } // if/else
2473 } // GPTData::SetAlignment()
2474 
2475 // Compute sector alignment based on the current partitions (if any). Each
2476 // partition's starting LBA is examined, and if it's divisible by a power-of-2
2477 // value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2478 // sector size), but not by the previously-located alignment value, then the
2479 // alignment value is adjusted down. If the computed alignment is less than 8
2480 // and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2481 // is a safety measure for Advanced Format drives. If no partitions are
2482 // defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2483 // adjustment of that based on the current sector size). The result is that new
2484 // drives are aligned to 2048-sector multiples but the program won't complain
2485 // about other alignments on existing disks unless a smaller-than-8 alignment
2486 // is used on big disks (as safety for Advanced Format drives).
2487 // Returns the computed alignment value.
ComputeAlignment(void)2488 uint32_t GPTData::ComputeAlignment(void) {
2489    uint32_t i = 0, found, exponent;
2490    uint32_t align = DEFAULT_ALIGNMENT;
2491 
2492    if (blockSize > 0)
2493       align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2494    exponent = (uint32_t) log2(align);
2495    for (i = 0; i < numParts; i++) {
2496       if (partitions[i].IsUsed()) {
2497          found = 0;
2498          while (!found) {
2499             align = UINT64_C(1) << exponent;
2500             if ((partitions[i].GetFirstLBA() % align) == 0) {
2501                found = 1;
2502             } else {
2503                exponent--;
2504             } // if/else
2505          } // while
2506       } // if
2507    } // for
2508    if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2509       align = MIN_AF_ALIGNMENT;
2510    sectorAlignment = align;
2511    return align;
2512 } // GPTData::ComputeAlignment()
2513 
2514 /********************************
2515  *                              *
2516  * Endianness support functions *
2517  *                              *
2518  ********************************/
2519 
ReverseHeaderBytes(struct GPTHeader * header)2520 void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
2521    ReverseBytes(&header->signature, 8);
2522    ReverseBytes(&header->revision, 4);
2523    ReverseBytes(&header->headerSize, 4);
2524    ReverseBytes(&header->headerCRC, 4);
2525    ReverseBytes(&header->reserved, 4);
2526    ReverseBytes(&header->currentLBA, 8);
2527    ReverseBytes(&header->backupLBA, 8);
2528    ReverseBytes(&header->firstUsableLBA, 8);
2529    ReverseBytes(&header->lastUsableLBA, 8);
2530    ReverseBytes(&header->partitionEntriesLBA, 8);
2531    ReverseBytes(&header->numParts, 4);
2532    ReverseBytes(&header->sizeOfPartitionEntries, 4);
2533    ReverseBytes(&header->partitionEntriesCRC, 4);
2534    ReverseBytes(header->reserved2, GPT_RESERVED);
2535 } // GPTData::ReverseHeaderBytes()
2536 
2537 // Reverse byte order for all partitions.
ReversePartitionBytes()2538 void GPTData::ReversePartitionBytes() {
2539    uint32_t i;
2540 
2541    for (i = 0; i < numParts; i++) {
2542       partitions[i].ReversePartBytes();
2543    } // for
2544 } // GPTData::ReversePartitionBytes()
2545 
2546 // Validate partition number
ValidPartNum(const uint32_t partNum)2547 bool GPTData::ValidPartNum (const uint32_t partNum) {
2548    if (partNum >= numParts) {
2549       cerr << "Partition number out of range: " << partNum << "\n";
2550       return false;
2551    } // if
2552    return true;
2553 } // GPTData::ValidPartNum
2554 
2555 // Return a single partition for inspection (not modification!) by other
2556 // functions.
operator [](uint32_t partNum) const2557 const GPTPart & GPTData::operator[](uint32_t partNum) const {
2558    if (partNum >= numParts) {
2559       cerr << "Partition number out of range (" << partNum << " requested, but only "
2560            << numParts << " available)\n";
2561       exit(1);
2562    } // if
2563    if (partitions == NULL) {
2564       cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2565       exit(1);
2566    } // if
2567    return partitions[partNum];
2568 } // operator[]
2569 
2570 // Return (not for modification!) the disk's GUID value
GetDiskGUID(void) const2571 const GUIDData & GPTData::GetDiskGUID(void) const {
2572    return mainHeader.diskGUID;
2573 } // GPTData::GetDiskGUID()
2574 
2575 // Manage attributes for a partition, based on commands passed to this function.
2576 // (Function is non-interactive.)
2577 // Returns 1 if a modification command succeeded, 0 if the command should not have
2578 // modified data, and -1 if a modification command failed.
ManageAttributes(int partNum,const string & command,const string & bits)2579 int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2580    int retval = 0;
2581    Attributes theAttr;
2582 
2583    if (partNum >= (int) numParts) {
2584       cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2585       retval = -1;
2586    } else {
2587       if (command == "show") {
2588          ShowAttributes(partNum);
2589       } else if (command == "get") {
2590          GetAttribute(partNum, bits);
2591       } else {
2592          theAttr = partitions[partNum].GetAttributes();
2593          if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2594             partitions[partNum].SetAttributes(theAttr.GetAttributes());
2595             retval = 1;
2596          } else {
2597             retval = -1;
2598          } // if/else
2599       } // if/elseif/else
2600    } // if/else invalid partition #
2601 
2602    return retval;
2603 } // GPTData::ManageAttributes()
2604 
2605 // Show all attributes for a specified partition....
ShowAttributes(const uint32_t partNum)2606 void GPTData::ShowAttributes(const uint32_t partNum) {
2607    if ((partNum < numParts) && partitions[partNum].IsUsed())
2608       partitions[partNum].ShowAttributes(partNum);
2609 } // GPTData::ShowAttributes
2610 
2611 // Show whether a single attribute bit is set (terse output)...
GetAttribute(const uint32_t partNum,const string & attributeBits)2612 void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
2613    if (partNum < numParts)
2614       partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
2615 } // GPTData::GetAttribute
2616 
2617 
2618 /******************************************
2619  *                                        *
2620  * Additional non-class support functions *
2621  *                                        *
2622  ******************************************/
2623 
2624 // Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2625 // never fail these tests, but the struct types may fail depending on compile options.
2626 // Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2627 // sizes.
SizesOK(void)2628 int SizesOK(void) {
2629    int allOK = 1;
2630 
2631    if (sizeof(uint8_t) != 1) {
2632       cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
2633       allOK = 0;
2634    } // if
2635    if (sizeof(uint16_t) != 2) {
2636       cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
2637       allOK = 0;
2638    } // if
2639    if (sizeof(uint32_t) != 4) {
2640       cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
2641       allOK = 0;
2642    } // if
2643    if (sizeof(uint64_t) != 8) {
2644       cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
2645       allOK = 0;
2646    } // if
2647    if (sizeof(struct MBRRecord) != 16) {
2648       cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
2649       allOK = 0;
2650    } // if
2651    if (sizeof(struct TempMBR) != 512) {
2652       cerr << "TempMBR is " <<  sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
2653       allOK = 0;
2654    } // if
2655    if (sizeof(struct GPTHeader) != 512) {
2656       cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
2657       allOK = 0;
2658    } // if
2659    if (sizeof(GPTPart) != 128) {
2660       cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
2661       allOK = 0;
2662    } // if
2663    if (sizeof(GUIDData) != 16) {
2664       cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2665       allOK = 0;
2666    } // if
2667    if (sizeof(PartType) != 16) {
2668       cerr << "PartType is " << sizeof(PartType) << " bytes, should be 16 bytes; aborting!\n";
2669       allOK = 0;
2670    } // if
2671    return (allOK);
2672 } // SizesOK()
2673 
2674