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