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