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