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