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