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