blob: 16bf718af2843ec96105b7afac8fe5ea40cb830c [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2 data. */
3
srs5694e4ac11e2009-08-31 10:13:04 -04004/* By Rod Smith, initial coding January to February, 2009 */
srs5694e7b4ff92009-08-18 13:16:10 -04005
Roderick W. Smithe3ee7332013-09-24 12:56:11 -04006/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040022#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "crc32.h"
24#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040025#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040026#include "support.h"
27#include "parttypes.h"
28#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050029#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040030
31using namespace std;
32
srs56948f1b2d62010-05-23 13:07:19 -040033#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040034#define log2(x) (log(x) / M_LN2)
35#endif // __FreeBSD__
36
srs56948f1b2d62010-05-23 13:07:19 -040037#ifdef _MSC_VER
38#define log2(x) (log((double) x) / log(2.0))
39#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040040
Roderick W. Smith1f7822e2014-03-28 23:54:21 -040041#ifdef EFI
42// in UEFI mode MMX registers are not yet available so using the
43// x86_64 ABI to move "double" values around is not an option.
44#ifdef log2
45#undef log2
46#endif
47#define log2(x) log2_32( x )
48static inline uint32_t log2_32(uint32_t v) {
49 int r = -1;
50 while (v >= 1) {
51 r++;
52 v >>= 1;
53 }
54 return r;
55}
56#endif
57
srs5694e7b4ff92009-08-18 13:16:10 -040058/****************************************
59 * *
60 * GPTData class and related structures *
61 * *
62 ****************************************/
63
srs5694e4ac11e2009-08-31 10:13:04 -040064// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040065GPTData::GPTData(void) {
66 blockSize = SECTOR_SIZE; // set a default
67 diskSize = 0;
68 partitions = NULL;
69 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050070 device = "";
srs56945d58fe02010-01-03 20:57:08 -050071 justLooking = 0;
Greg Hartman2c2deeb2016-04-21 18:20:25 -070072 syncing = 1;
srs5694e7b4ff92009-08-18 13:16:10 -040073 mainCrcOk = 0;
74 secondCrcOk = 0;
75 mainPartsCrcOk = 0;
76 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040077 apmFound = 0;
78 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040079 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050080 beQuiet = 0;
81 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050082 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040083 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040084 SetGPTSize(NUM_GPT_ENTRIES);
srs5694d1b11e82011-09-18 21:12:28 -040085 // Initialize CRC functions...
86 chksum_crc32gentab();
srs5694e7b4ff92009-08-18 13:16:10 -040087} // GPTData default constructor
88
89// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050090GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040091 blockSize = SECTOR_SIZE; // set a default
92 diskSize = 0;
93 partitions = NULL;
94 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050095 device = "";
srs56945d58fe02010-01-03 20:57:08 -050096 justLooking = 0;
Greg Hartman2c2deeb2016-04-21 18:20:25 -070097 syncing = 1;
srs5694e7b4ff92009-08-18 13:16:10 -040098 mainCrcOk = 0;
99 secondCrcOk = 0;
100 mainPartsCrcOk = 0;
101 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -0400102 apmFound = 0;
103 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -0400104 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -0500105 beQuiet = 0;
106 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -0500107 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -0400108 numParts = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400109 // Initialize CRC functions...
110 chksum_crc32gentab();
srs56943c0af382010-01-15 19:19:18 -0500111 if (!LoadPartitions(filename))
112 exit(2);
srs5694fed16d02010-01-27 23:03:40 -0500113} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -0400114
srs5694e4ac11e2009-08-31 10:13:04 -0400115// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -0400116GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500117 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -0400118} // GPTData destructor
119
srs569464cbd172011-03-01 22:03:54 -0500120// Assignment operator
121GPTData & GPTData::operator=(const GPTData & orig) {
122 uint32_t i;
123
124 mainHeader = orig.mainHeader;
125 numParts = orig.numParts;
126 secondHeader = orig.secondHeader;
127 protectiveMBR = orig.protectiveMBR;
128 device = orig.device;
129 blockSize = orig.blockSize;
130 diskSize = orig.diskSize;
131 state = orig.state;
132 justLooking = orig.justLooking;
Greg Hartman2c2deeb2016-04-21 18:20:25 -0700133 syncing = orig.syncing;
srs569464cbd172011-03-01 22:03:54 -0500134 mainCrcOk = orig.mainCrcOk;
135 secondCrcOk = orig.secondCrcOk;
136 mainPartsCrcOk = orig.mainPartsCrcOk;
137 secondPartsCrcOk = orig.secondPartsCrcOk;
138 apmFound = orig.apmFound;
139 bsdFound = orig.bsdFound;
140 sectorAlignment = orig.sectorAlignment;
141 beQuiet = orig.beQuiet;
142 whichWasUsed = orig.whichWasUsed;
143
144 myDisk.OpenForRead(orig.myDisk.GetName());
145
146 delete[] partitions;
srs569401f7f082011-03-15 23:53:31 -0400147 partitions = new GPTPart [numParts];
srs56946aae2a92011-06-10 01:16:51 -0400148 if (partitions == NULL) {
srs569464cbd172011-03-01 22:03:54 -0500149 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
srs56946aae2a92011-06-10 01:16:51 -0400150 << "Terminating!\n";
151 exit(1);
152 } // if
153 for (i = 0; i < numParts; i++) {
154 partitions[i] = orig.partitions[i];
srs5694d1b11e82011-09-18 21:12:28 -0400155 } // for
156
srs569464cbd172011-03-01 22:03:54 -0500157 return *this;
158} // GPTData::operator=()
159
srs5694e4ac11e2009-08-31 10:13:04 -0400160/*********************************************************************
161 * *
162 * Begin functions that verify data, or that adjust the verification *
163 * information (compute CRCs, rebuild headers) *
164 * *
165 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400166
srs5694e4ac11e2009-08-31 10:13:04 -0400167// Perform detailed verification, reporting on any problems found, but
168// do *NOT* recover from these problems. Returns the total number of
169// problems identified.
170int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500171 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500172 uint32_t i, numSegments;
173 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400174
175 // First, check for CRC errors in the GPT data....
176 if (!mainCrcOk) {
177 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500178 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
179 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
180 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
181 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400182 } // if
183 if (!mainPartsCrcOk) {
184 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500185 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
186 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
187 << "transformation menu). This report may be a false alarm if you've already\n"
188 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400189 } // if
190 if (!secondCrcOk) {
191 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500192 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
193 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
194 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
195 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400196 } // if
197 if (!secondPartsCrcOk) {
198 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500199 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
200 << "be corrupt. This program will automatically create a new backup partition\n"
201 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400202 } // if
203
srs5694978041c2009-09-21 20:51:47 -0400204 // Now check that the main and backup headers both point to themselves....
205 if (mainHeader.currentLBA != 1) {
206 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500207 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
208 << "is being automatically corrected, but it may be a symptom of more serious\n"
209 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400210 mainHeader.currentLBA = 1;
211 } // if
212 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
213 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500214 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
215 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
216 << "option on the experts' menu to adjust the secondary header's and partition\n"
217 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400218 } // if
219
220 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400221 if (mainHeader.currentLBA != secondHeader.backupLBA) {
222 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500223 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
224 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
225 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400226 } // if
227 if (mainHeader.backupLBA != secondHeader.currentLBA) {
228 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500229 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
230 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
231 << secondHeader.currentLBA << ").\n"
232 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400233 } // if
234 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
235 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500236 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
237 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
238 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400239 } // if
240 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
241 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500242 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
243 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
244 << secondHeader.lastUsableLBA << ")\n"
245 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400246 } // if
srs56946699b012010-02-04 00:55:30 -0500247 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400248 problems++;
srs56945a081752010-09-24 20:39:41 -0400249 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500250 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400251 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500252 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
253 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400254 } // if
255 if (mainHeader.numParts != secondHeader.numParts) {
256 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500257 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
258 << ") doesn't\nmatch the backup GPT header's number of partitions ("
259 << secondHeader.numParts << ")\n"
260 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400261 } // if
262 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
263 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500264 cout << "\nProblem: main GPT header's size of partition entries ("
265 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
266 << "match the backup GPT header's size of partition entries ("
267 << secondHeader.sizeOfPartitionEntries << ")\n"
268 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
269 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400270 } // if
271
272 // Now check for a few other miscellaneous problems...
273 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500274 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400275 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "\nProblem: Disk is too small to hold all the data!\n"
277 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500278 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500279 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400280 } // if
281
srs5694d8eed462012-12-15 01:55:21 -0500282 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
283 problems++;
srs56940741fa22013-01-09 12:55:40 -0500284 cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
285 << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
286 << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
287 << "The 'e' option on the experts' menu will probably fix this problem\n";
srs5694d8eed462012-12-15 01:55:21 -0500288 }
289
srs5694e4ac11e2009-08-31 10:13:04 -0400290 // Check for overlapping partitions....
291 problems += FindOverlaps();
292
srs569455d92612010-03-07 22:16:07 -0500293 // Check for insane partitions (start after end, hugely big, etc.)
294 problems += FindInsanePartitions();
295
srs5694e4ac11e2009-08-31 10:13:04 -0400296 // Check for mismatched MBR and GPT partitions...
297 problems += FindHybridMismatches();
298
srs5694327129e2010-09-22 01:07:31 -0400299 // Check for MBR-specific problems....
300 problems += VerifyMBR();
301
Roderick W. Smith042f38a2013-08-31 17:40:15 -0400302 // Check for a 0xEE protective partition that's marked as active....
303 if (protectiveMBR.IsEEActive()) {
304 cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
305 << "technically a violation of the GPT specification, and can cause some EFIs to\n"
306 << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
307 << "computers. You can clear this flag by creating a fresh protective MBR using\n"
308 << "the 'n' option on the experts' menu.\n";
309 }
310
srs5694e4ac11e2009-08-31 10:13:04 -0400311 // Verify that partitions don't run into GPT data areas....
312 problems += CheckGPTSize();
313
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500314 if (!protectiveMBR.DoTheyFit()) {
315 cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
316 << "fresh protective or hybrid MBR is recommended.\n";
317 problems++;
318 }
319
srs56941d1448a2009-12-31 21:20:19 -0500320 // Check that partitions are aligned on proper boundaries (for WD Advanced
321 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400322 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500323 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500324 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
325 << sectorAlignment << "-sector boundary. This may\nresult "
326 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500327 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500328 } // if
329 } // for
srs569464cbd172011-03-01 22:03:54 -0500330 if (alignProbs > 0)
331 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
332 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500333
srs5694e4ac11e2009-08-31 10:13:04 -0400334 // Now compute available space, but only if no problems found, since
335 // problems could affect the results
336 if (problems == 0) {
337 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500338 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400339 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500340 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400341 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400342 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400343 } else {
srs56940a697312010-01-28 21:10:52 -0500344 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400345 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400346
347 return (problems);
348} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400349
350// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400351// do, issues a warning but takes no action. Returns number of problems
352// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400353int GPTData::CheckGPTSize(void) {
354 uint64_t overlap, firstUsedBlock, lastUsedBlock;
355 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400356 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400357
358 // first, locate the first & last used blocks
359 firstUsedBlock = UINT64_MAX;
360 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400361 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500362 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500363 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500364 firstUsedBlock = partitions[i].GetFirstLBA();
365 if (partitions[i].GetLastLBA() > lastUsedBlock) {
366 lastUsedBlock = partitions[i].GetLastLBA();
367 } // if
368 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400369 } // for
370
371 // If the disk size is 0 (the default), then it means that various
372 // variables aren't yet set, so the below tests will be useless;
373 // therefore we should skip everything
374 if (diskSize != 0) {
375 if (mainHeader.firstUsableLBA > firstUsedBlock) {
376 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500377 cout << "Warning! Main partition table overlaps the first partition by "
378 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400379 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500380 cout << "Try reducing the partition table size by " << overlap * 4
381 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400382 } else {
srs5694fed16d02010-01-27 23:03:40 -0500383 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400384 } // if/else
385 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400386 } // Problem at start of disk
387 if (mainHeader.lastUsableLBA < lastUsedBlock) {
388 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500389 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500390 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400391 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500392 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400393 } else {
srs5694fed16d02010-01-27 23:03:40 -0500394 cout << "Try reducing the partition table size by " << overlap * 4
395 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400396 } // if/else
397 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400398 } // Problem at end of disk
399 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400400 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400401} // GPTData::CheckGPTSize()
402
srs5694e7b4ff92009-08-18 13:16:10 -0400403// Check the validity of the GPT header. Returns 1 if the main header
404// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400405// 0 if neither is valid. Note that this function checks the GPT signature,
406// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400407int GPTData::CheckHeaderValidity(void) {
408 int valid = 3;
409
srs5694fed16d02010-01-27 23:03:40 -0500410 cout.setf(ios::uppercase);
411 cout.fill('0');
412
413 // Note: failed GPT signature checks produce no error message because
414 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400415 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400416 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400417 } else if ((mainHeader.revision != 0x00010000) && valid) {
418 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500419 cout << "Unsupported GPT version in main header; read 0x";
420 cout.width(8);
421 cout << hex << mainHeader.revision << ", should be\n0x";
422 cout.width(8);
423 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400424 } // if/else/if
425
srs5694d1b11e82011-09-18 21:12:28 -0400426 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400427 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400428 } else if ((secondHeader.revision != 0x00010000) && valid) {
429 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500430 cout << "Unsupported GPT version in backup header; read 0x";
431 cout.width(8);
432 cout << hex << secondHeader.revision << ", should be\n0x";
433 cout.width(8);
434 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400435 } // if/else/if
436
srs5694df9d3632011-01-08 18:33:24 -0500437 // Check for an Apple disk signature
438 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
439 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400440 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500441 } // if
srs5694fed16d02010-01-27 23:03:40 -0500442 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400443
srs5694fed16d02010-01-27 23:03:40 -0500444 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400445} // GPTData::CheckHeaderValidity()
446
447// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400448// Note: Must be called with header in platform-ordered byte order.
449// Returns 1 if header's computed CRC matches the stored value, 0 if the
450// computed and stored values don't match
451int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400452 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400453 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400454
srs56942a9f5da2009-08-26 00:48:01 -0400455 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400456 // computation to be valid
457 oldCRC = header->headerCRC;
458 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400459
srs5694978041c2009-09-21 20:51:47 -0400460 hSize = header->headerSize;
461
srs5694d1b11e82011-09-18 21:12:28 -0400462 if (IsLittleEndian() == 0)
463 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400464
srs5694d1b11e82011-09-18 21:12:28 -0400465 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
466 if (warn) {
467 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
468 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
469 } // if
470 hSize = HEADER_SIZE;
471 } else if ((hSize > sizeof(GPTHeader)) && warn) {
472 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
473 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
474 << "which may result in a CRC false alarm.\n";
475 } // if/elseif
476 temp = new uint8_t[hSize];
477 if (temp != NULL) {
478 memset(temp, 0, hSize);
479 if (hSize < sizeof(GPTHeader))
480 memcpy(temp, header, hSize);
481 else
482 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400483
srs5694d1b11e82011-09-18 21:12:28 -0400484 newCRC = chksum_crc32((unsigned char*) temp, hSize);
485 delete[] temp;
486 } else {
487 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
488 exit(1);
489 }
490 if (IsLittleEndian() == 0)
491 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400492 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400493 return (oldCRC == newCRC);
494} // GPTData::CheckHeaderCRC()
495
srs56946699b012010-02-04 00:55:30 -0500496// Recompute all the CRCs. Must be called before saving if any changes have
497// been made. Must be called on platform-ordered data (this function reverses
498// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400499void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400500 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400501 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400502
srs5694d1b11e82011-09-18 21:12:28 -0400503 // If the header size is bigger than the GPT header data structure, reset it;
504 // otherwise, set both header sizes to whatever the main one is....
505 if (mainHeader.headerSize > sizeof(GPTHeader))
506 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
507 else
508 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500509
510 if ((littleEndian = IsLittleEndian()) == 0) {
511 ReversePartitionBytes();
512 ReverseHeaderBytes(&mainHeader);
513 ReverseHeaderBytes(&secondHeader);
514 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400515
srs5694e7b4ff92009-08-18 13:16:10 -0400516 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400517 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400518 mainHeader.partitionEntriesCRC = crc;
519 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400520 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400521 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
522 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400523 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400524
srs5694d1b11e82011-09-18 21:12:28 -0400525 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400526 mainHeader.headerCRC = 0;
527 secondHeader.headerCRC = 0;
528
srs5694978041c2009-09-21 20:51:47 -0400529 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400530 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400531 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400532 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400533 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400534 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400535 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400536 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500537
srs5694d1b11e82011-09-18 21:12:28 -0400538 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500539 ReverseHeaderBytes(&mainHeader);
540 ReverseHeaderBytes(&secondHeader);
541 ReversePartitionBytes();
542 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400543} // GPTData::RecomputeCRCs()
544
srs5694e7b4ff92009-08-18 13:16:10 -0400545// Rebuild the main GPT header, using the secondary header as a model.
546// Typically called when the main header has been found to be corrupt.
547void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400548 mainHeader.signature = GPT_SIGNATURE;
549 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400550 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400551 mainHeader.headerCRC = UINT32_C(0);
552 mainHeader.reserved = secondHeader.reserved;
553 mainHeader.currentLBA = secondHeader.backupLBA;
554 mainHeader.backupLBA = secondHeader.currentLBA;
555 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
556 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500557 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400558 mainHeader.partitionEntriesLBA = UINT64_C(2);
559 mainHeader.numParts = secondHeader.numParts;
560 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
561 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400562 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500563 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500564 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400565} // GPTData::RebuildMainHeader()
566
567// Rebuild the secondary GPT header, using the main header as a model.
568void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400569 secondHeader.signature = GPT_SIGNATURE;
570 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400571 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400572 secondHeader.headerCRC = UINT32_C(0);
573 secondHeader.reserved = mainHeader.reserved;
574 secondHeader.currentLBA = mainHeader.backupLBA;
575 secondHeader.backupLBA = mainHeader.currentLBA;
576 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
577 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500578 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400579 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
580 secondHeader.numParts = mainHeader.numParts;
581 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
582 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400583 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500584 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500585 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400586} // GPTData::RebuildSecondHeader()
587
588// Search for hybrid MBR entries that have no corresponding GPT partition.
589// Returns number of such mismatches found
590int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500591 int i, found, numFound = 0;
592 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400593 uint64_t mbrFirst, mbrLast;
594
595 for (i = 0; i < 4; i++) {
596 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
597 j = 0;
598 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400599 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
600 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400601 do {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -0400602 if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500603 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400604 found = 1;
605 j++;
srs56940283dae2010-04-28 16:44:34 -0400606 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400607 if (!found) {
608 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500609 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
610 << i + 1 << ", of type 0x";
611 cout.fill('0');
612 cout.setf(ios::uppercase);
613 cout.width(2);
614 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
615 << "has no corresponding GPT partition! You may continue, but this condition\n"
616 << "might cause data loss in the future!\a\n" << dec;
617 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400618 } // if
619 } // if
620 } // for
621 return numFound;
622} // GPTData::FindHybridMismatches
623
624// Find overlapping partitions and warn user about them. Returns number of
625// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400626// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400627int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500628 int problems = 0;
629 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400630
srs56940283dae2010-04-28 16:44:34 -0400631 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400632 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500633 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
634 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400635 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500636 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
637 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
638 << " to " << partitions[i].GetLastLBA() << "\n";
639 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
640 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400641 } // if
642 } // for j...
643 } // for i...
644 return problems;
645} // GPTData::FindOverlaps()
646
srs569455d92612010-03-07 22:16:07 -0500647// Find partitions that are insane -- they start after they end or are too
648// big for the disk. (The latter should duplicate detection of overlaps
649// with GPT backup data structures, but better to err on the side of
650// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400651// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500652int GPTData::FindInsanePartitions(void) {
653 uint32_t i;
654 int problems = 0;
655
srs56940283dae2010-04-28 16:44:34 -0400656 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500657 if (partitions[i].IsUsed()) {
658 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
659 problems++;
660 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
661 } // if
662 if (partitions[i].GetLastLBA() >= diskSize) {
663 problems++;
664 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
665 } // if
srs569455d92612010-03-07 22:16:07 -0500666 } // if
667 } // for
668 return problems;
669} // GPTData::FindInsanePartitions(void)
670
671
srs5694e4ac11e2009-08-31 10:13:04 -0400672/******************************************************************
673 * *
674 * Begin functions that load data from disk or save data to disk. *
675 * *
676 ******************************************************************/
677
srs569464cbd172011-03-01 22:03:54 -0500678// Change the filename associated with the GPT. Used for duplicating
679// the partition table to a new disk and saving backups.
680// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500681int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500682 int err, allOK = 1;
683
684 device = deviceFilename;
685 if (allOK && myDisk.OpenForRead(deviceFilename)) {
686 // store disk information....
687 diskSize = myDisk.DiskSize(&err);
688 blockSize = (uint32_t) myDisk.GetBlockSize();
689 } // if
690 protectiveMBR.SetDisk(&myDisk);
691 protectiveMBR.SetDiskSize(diskSize);
692 protectiveMBR.SetBlockSize(blockSize);
693 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500694} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500695
srs5694e4ac11e2009-08-31 10:13:04 -0400696// Scan for partition data. This function loads the MBR data (regular MBR or
697// protective MBR) and loads BSD disklabel data (which is probably invalid).
698// It also looks for APM data, forces a load of GPT data, and summarizes
699// the results.
srs5694546a9c72010-01-26 16:00:26 -0500700void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400701 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400702
703 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500704 protectiveMBR.ReadMBRData(&myDisk);
705 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400706
707 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500708 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500709
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500710 // Some tools create a 0xEE partition that's too big. If this is detected,
711 // normalize it....
712 if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
713 if (!beQuiet) {
714 cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
715 } // if
716 protectiveMBR.MakeProtectiveMBR();
717 } // if
718
srs5694ba00fed2010-01-12 18:18:36 -0500719 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500720 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500721 protectiveMBR.ShowState();
722 bsdDisklabel.ShowState();
723 ShowAPMState(); // Show whether there's an Apple Partition Map present
724 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500725 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500726 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400727
728 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500729 cout << "\n*******************************************************************\n"
730 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500731 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500732 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500733 } // if
srs5694fed16d02010-01-27 23:03:40 -0500734 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400735 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400736} // GPTData::PartitionScan()
737
738// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500739int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500740 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500741 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500742 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400743
srs5694546a9c72010-01-26 16:00:26 -0500744 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500745 err = myDisk.OpenForWrite(deviceFilename);
746 if ((err == 0) && (!justLooking)) {
747 cout << "\aNOTE: Write test failed with error number " << errno
748 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
749#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
750 cout << "You may be able to enable writes by exiting this program, typing\n"
751 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
752 << "program.\n";
753#endif
Aurimas Liutikas74b74902016-05-10 18:53:54 -0700754#if defined (__APPLE__)
755 cout << "You may need to deactivate System Integrity Protection to use this program. See\n"
756 << "https://www.quora.com/How-do-I-turn-off-the-rootless-in-OS-X-El-Capitan-10-11\n"
757 << "for more information.\n";
758#endif
759 cout << "\n";
srs569455d92612010-03-07 22:16:07 -0500760 } // if
761 myDisk.Close(); // Close and re-open read-only in case of bugs
762 } else allOK = 0; // if
763
764 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400765 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500766 diskSize = myDisk.DiskSize(&err);
767 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500768 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500769 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400770
srs5694ba00fed2010-01-12 18:18:36 -0500771 whichWasUsed = UseWhichPartitions();
772 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400773 case use_mbr:
774 XFormPartitions();
775 break;
776 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500777 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400778// bsdDisklabel.DisplayBSDData();
779 ClearGPTData();
780 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500781 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400782 break;
783 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500784 mbrState = protectiveMBR.GetValidity();
785 if ((mbrState == invalid) || (mbrState == mbr))
786 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400787 break;
788 case use_new:
789 ClearGPTData();
790 protectiveMBR.MakeProtectiveMBR();
791 break;
srs56943c0af382010-01-15 19:19:18 -0500792 case use_abort:
793 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400794 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500795 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400796 } // switch
797
srs569455d92612010-03-07 22:16:07 -0500798 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500799 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500800 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400801 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400802 } else {
803 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400804 } // if/else
805 return (allOK);
806} // GPTData::LoadPartitions()
807
808// Loads the GPT, as much as possible. Returns 1 if this seems to have
809// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500810int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500811 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400812
srs5694cb76c672010-02-11 22:22:22 -0500813 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400814
srs5694cb76c672010-02-11 22:22:22 -0500815 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
816 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
817 } else {
srs569408bb0da2010-02-19 17:19:55 -0500818 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
819 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500820 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
821 << "secondary header from the last sector of the disk! You should use 'v' to\n"
822 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
823 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500824 } // if/else
825 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400826 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400827
828 // Return valid headers code: 0 = both headers bad; 1 = main header
829 // good, backup bad; 2 = backup header good, main header bad;
830 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400831 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400832 validHeaders = CheckHeaderValidity();
833
834 // Read partitions (from primary array)
835 if (validHeaders > 0) { // if at least one header is OK....
836 // GPT appears to be valid....
837 state = gpt_valid;
838
839 // We're calling the GPT valid, but there's a possibility that one
840 // of the two headers is corrupt. If so, use the one that seems to
841 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500842 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500843 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
844 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400845 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500846 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400847 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500848 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500849 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
850 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500851 RebuildMainHeader();
852 state = gpt_corrupt;
853 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400854 } // if/else/if
855
srs5694546a9c72010-01-26 16:00:26 -0500856 // Figure out which partition table to load....
857 // Load the main partition table, since either its header's CRC is OK or the
858 // backup header's CRC is not OK....
859 if (mainCrcOk || !secondCrcOk) {
860 if (LoadMainTable() == 0)
861 allOK = 0;
862 } else { // bad main header CRC and backup header CRC is OK
863 state = gpt_corrupt;
864 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500865 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500866 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500867 } else { // backup table bad, bad main header CRC, but try main table in desperation....
868 if (LoadMainTable() == 0) {
869 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500870 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500871 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500872 } // if
873 } // if/else (LoadSecondTableAsMain())
874 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400875
srs5694cb76c672010-02-11 22:22:22 -0500876 if (loadedTable == 1)
877 secondPartsCrcOk = CheckTable(&secondHeader);
878 else if (loadedTable == 2)
879 mainPartsCrcOk = CheckTable(&mainHeader);
880 else
881 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400882
srs5694546a9c72010-01-26 16:00:26 -0500883 // Problem with main partition table; if backup is OK, use it instead....
884 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
885 state = gpt_corrupt;
886 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500887 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500888 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
889 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500890 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500891
srs5694e4ac11e2009-08-31 10:13:04 -0400892 // Check for valid CRCs and warn if there are problems
893 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
894 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500895 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400896 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500897 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400898 } else {
899 state = gpt_invalid;
900 } // if/else
901 return allOK;
902} // GPTData::ForceLoadGPTData()
903
srs5694247657a2009-11-26 18:36:12 -0500904// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400905// main GPT header in memory MUST be valid for this call to do anything
906// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500907// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400908int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500909 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400910} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400911
912// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500913// table. Used in repair functions, and when starting up if the main
914// partition table is damaged.
915// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
916int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500917 return LoadPartitionTable(secondHeader, myDisk);
918} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400919
srs5694cb76c672010-02-11 22:22:22 -0500920// Load a single GPT header (main or backup) from the specified disk device and
921// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
922// value appropriately.
923// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
924// failure.
925int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
926 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500927 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500928
929 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500930 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500931 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
932 allOK = 0;
933 } // if
srs5694cb76c672010-02-11 22:22:22 -0500934
srs56941c6f8b02010-02-21 11:09:20 -0500935 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500936 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500937 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500938 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400939 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500940
srs56940283dae2010-04-28 16:44:34 -0400941 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500942 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500943 }
srs56941c6f8b02010-02-21 11:09:20 -0500944
945 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500946 return allOK;
947} // GPTData::LoadHeader
948
949// Load a partition table (either main or secondary) from the specified disk,
950// using header as a reference for what to load. If sector != 0 (the default
951// is 0), loads from the specified sector; otherwise loads from the sector
952// indicated in header.
953// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
954int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
955 uint32_t sizeOfParts, newCRC;
956 int retval;
957
958 if (disk.OpenForRead()) {
959 if (sector == 0) {
960 retval = disk.Seek(header.partitionEntriesLBA);
961 } else {
962 retval = disk.Seek(sector);
963 } // if/else
srs569455d92612010-03-07 22:16:07 -0500964 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500965 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500966 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500967 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
968 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500969 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500970 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500971 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400972 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500973 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400974 if (IsLittleEndian() == 0)
975 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500976 if (!mainPartsCrcOk) {
977 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400978 } // if
979 } else {
srs5694cb76c672010-02-11 22:22:22 -0500980 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400981 } // if/else
982 } else {
srs5694fed16d02010-01-27 23:03:40 -0500983 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500984 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500985 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400986 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500987 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500988} // GPTData::LoadPartitionsTable()
989
990// Check the partition table pointed to by header, but don't keep it
991// around.
srs5694a17fe692011-09-10 20:30:20 -0400992// Returns 1 if the CRC is OK & this table matches the one already in memory,
993// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500994int GPTData::CheckTable(struct GPTHeader *header) {
995 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400996 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400997 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400998 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500999
srs56940283dae2010-04-28 16:44:34 -04001000 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -05001001 // its CRC and store the results, then discard this temporary
1002 // storage, since we don't use it in any but recovery operations
1003 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -04001004 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -04001005 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -04001006 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -04001007 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
1008 exit(1);
1009 } // if
srs5694a17fe692011-09-10 20:30:20 -04001010 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -04001011 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -05001012 } else {
srs5694d1b11e82011-09-18 21:12:28 -04001013 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -04001014 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -04001015 if (header == &mainHeader)
1016 otherHeader = &secondHeader;
1017 else
1018 otherHeader = &mainHeader;
1019 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -04001020 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
1021 << "on the recovery & transformation menu to examine the two tables.\n\n";
1022 allOK = 0;
1023 } // if
srs5694cb76c672010-02-11 22:22:22 -05001024 } // if/else
srs5694a17fe692011-09-10 20:30:20 -04001025 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -05001026 } // if
srs5694a17fe692011-09-10 20:30:20 -04001027 return allOK;
srs5694cb76c672010-02-11 22:22:22 -05001028} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -04001029
srs56944307ef22012-05-30 12:30:48 -04001030// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1031// header later on the disk without asking for permission, if necessary, and
1032// doesn't confirm the operation before writing. If quiet==0, asks permission
1033// before moving the second header and asks for final confirmation of any
1034// write.
srs5694a17fe692011-09-10 20:30:20 -04001035// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -05001036int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -04001037 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -05001038 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -04001039
srs5694e7b4ff92009-08-18 13:16:10 -04001040 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -05001041
1042 // This test should only fail on read-only disks....
1043 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001044 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -05001045 allOK = 0;
1046 } // if
1047
srs569464cbd172011-03-01 22:03:54 -05001048 // Check that disk is really big enough to handle the second header...
1049 if (mainHeader.backupLBA >= diskSize) {
1050 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1051 << "header, but other problems may occur!\n";
1052 MoveSecondHeaderToEnd();
1053 } // if
1054
srs5694e7b4ff92009-08-18 13:16:10 -04001055 // Is there enough space to hold the GPT headers and partition tables,
1056 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001057 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001058 allOK = 0;
1059 } // if
1060
srs5694247657a2009-11-26 18:36:12 -05001061 // Check that second header is properly placed. Warn and ask if this should
1062 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001063 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1064 if (quiet == 0) {
1065 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1066 << "correct this problem? ";
1067 if (GetYN() == 'Y') {
1068 MoveSecondHeaderToEnd();
1069 cout << "Have moved second header and partition table to correct location.\n";
1070 } else {
1071 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1072 } // if correction requested
1073 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001074 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001075 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001076 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001077
srs5694d8eed462012-12-15 01:55:21 -05001078 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1079 if (quiet == 0) {
1080 cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1081 << "this problem? ";
1082 if (GetYN() == 'Y') {
1083 MoveSecondHeaderToEnd();
1084 cout << "Have adjusted the second header and last usable sector value.\n";
1085 } else {
1086 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1087 } // if correction requested
1088 } else { // go ahead and do correction automatically
1089 MoveSecondHeaderToEnd();
1090 } // if/else quiet
1091 } // if
1092
srs569455d92612010-03-07 22:16:07 -05001093 // Check for overlapping or insane partitions....
1094 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001095 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001096 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001097 } // if
1098
Roderick W. Smith4a702a22014-01-25 23:46:42 -05001099 // Check that protective MBR fits, and warn if it doesn't....
1100 if (!protectiveMBR.DoTheyFit()) {
1101 cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1102 << "fresh protective or hybrid MBR is recommended.\n";
1103 }
1104
srs5694e4ac11e2009-08-31 10:13:04 -04001105 // Check for mismatched MBR and GPT data, but let it pass if found
1106 // (function displays warning message)
1107 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001108
1109 RecomputeCRCs();
1110
srs5694ba00fed2010-01-12 18:18:36 -05001111 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001112 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001113 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001114 answer = GetYN();
1115 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001116 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001117 } else {
1118 allOK = 0;
1119 } // if/else
1120 } // if
1121
1122 // Do it!
1123 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001124 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001125 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001126 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001127 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001128 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1129 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001130 syncIt = 0;
1131 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001132
1133 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001134 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1135
1136 // Now write the main partition tables...
1137 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1138
1139 // Now write the main GPT header...
1140 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1141
1142 // To top it off, write the protective MBR...
1143 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001144
1145 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001146 // Note: Done even if some write operations failed, but not if all of them failed.
1147 // Done this way because I've received one problem report from a user one whose
1148 // system the MBR write failed but everything else was OK (on a GPT disk under
1149 // Windows), and the failure to sync therefore caused Windows to restore the
1150 // original partition table from its cache. OTOH, such restoration might be
1151 // desirable if the error occurs later; but that seems unlikely unless the initial
1152 // write fails....
Greg Hartman2c2deeb2016-04-21 18:20:25 -07001153 if (syncIt && syncing)
srs5694546a9c72010-01-26 16:00:26 -05001154 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001155
1156 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001157 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001158 } else {
srs5694fed16d02010-01-27 23:03:40 -05001159 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001160 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001161 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001162
srs5694546a9c72010-01-26 16:00:26 -05001163 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001164 } else {
srs56945a608532011-03-17 13:53:01 -04001165 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001166 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001167 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001168 } // if/else
1169 } else {
srs5694fed16d02010-01-27 23:03:40 -05001170 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001171 } // if
1172
1173 return (allOK);
1174} // GPTData::SaveGPTData()
1175
1176// Save GPT data to a backup file. This function does much less error
1177// checking than SaveGPTData(). It can therefore preserve many types of
1178// corruption for later analysis; however, it preserves only the MBR,
1179// the main GPT header, the backup GPT header, and the main partition
1180// table; it discards the backup partition table, since it should be
1181// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001182int GPTData::SaveGPTBackup(const string & filename) {
1183 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001184 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001185
srs5694546a9c72010-01-26 16:00:26 -05001186 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001187 // Recomputing the CRCs is likely to alter them, which could be bad
1188 // if the intent is to save a potentially bad GPT for later analysis;
1189 // but if we don't do this, we get bogus errors when we load the
1190 // backup. I'm favoring misses over false alarms....
1191 RecomputeCRCs();
1192
srs5694546a9c72010-01-26 16:00:26 -05001193 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001194 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001195
srs5694cb76c672010-02-11 22:22:22 -05001196 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001197 // MBR write closed disk, so re-open and seek to end....
1198 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001199 allOK = SaveHeader(&mainHeader, backupFile, 1);
1200 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001201
srs5694e7b4ff92009-08-18 13:16:10 -04001202 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001203 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001204
srs5694cb76c672010-02-11 22:22:22 -05001205 if (allOK)
1206 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001207
1208 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001209 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001210 } else {
srs5694fed16d02010-01-27 23:03:40 -05001211 cerr << "Warning! An error was reported when writing the backup file.\n"
1212 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001213 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001214 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001215 } else {
srs56945a608532011-03-17 13:53:01 -04001216 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001217 allOK = 0;
1218 } // if/else
1219 return allOK;
1220} // GPTData::SaveGPTBackup()
1221
srs5694cb76c672010-02-11 22:22:22 -05001222// Write a GPT header (main or backup) to the specified sector. Used by both
1223// the SaveGPTData() and SaveGPTBackup() functions.
1224// Should be passed an architecture-appropriate header (DO NOT call
1225// ReverseHeaderBytes() on the header before calling this function)
1226// Returns 1 on success, 0 on failure
1227int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1228 int littleEndian, allOK = 1;
1229
1230 littleEndian = IsLittleEndian();
1231 if (!littleEndian)
1232 ReverseHeaderBytes(header);
1233 if (disk.Seek(sector)) {
1234 if (disk.Write(header, 512) == -1)
1235 allOK = 0;
1236 } else allOK = 0; // if (disk.Seek()...)
1237 if (!littleEndian)
1238 ReverseHeaderBytes(header);
1239 return allOK;
1240} // GPTData::SaveHeader()
1241
1242// Save the partitions to the specified sector. Used by both the SaveGPTData()
1243// and SaveGPTBackup() functions.
1244// Should be passed an architecture-appropriate header (DO NOT call
1245// ReverseHeaderBytes() on the header before calling this function)
1246// Returns 1 on success, 0 on failure
1247int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1248 int littleEndian, allOK = 1;
1249
1250 littleEndian = IsLittleEndian();
1251 if (disk.Seek(sector)) {
1252 if (!littleEndian)
1253 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001254 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001255 allOK = 0;
1256 if (!littleEndian)
1257 ReversePartitionBytes();
1258 } else allOK = 0; // if (myDisk.Seek()...)
1259 return allOK;
1260} // GPTData::SavePartitionTable()
1261
srs5694e7b4ff92009-08-18 13:16:10 -04001262// Load GPT data from a backup file created by SaveGPTBackup(). This function
1263// does minimal error checking. It returns 1 if it completed successfully,
1264// 0 if there was a problem. In the latter case, it creates a new empty
1265// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001266int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001267 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001268 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001269 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001270
srs5694546a9c72010-01-26 16:00:26 -05001271 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001272 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001273 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001274 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001275
srs5694cb76c672010-02-11 22:22:22 -05001276 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001277
srs5694cb76c672010-02-11 22:22:22 -05001278 // Check backup file size and rebuild second header if file is right
1279 // size to be direct dd copy of MBR, main header, and main partition
1280 // table; if other size, treat it like a GPT fdisk-generated backup
1281 // file
1282 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1283 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1284 if (shortBackup) {
1285 RebuildSecondHeader();
1286 secondCrcOk = mainCrcOk;
1287 } else {
1288 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1289 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001290
srs5694e7b4ff92009-08-18 13:16:10 -04001291 // Return valid headers code: 0 = both headers bad; 1 = main header
1292 // good, backup bad; 2 = backup header good, main header bad;
1293 // 3 = both headers good. Note these codes refer to valid GPT
1294 // signatures and version numbers; more subtle problems will elude
1295 // this check!
1296 if ((val = CheckHeaderValidity()) > 0) {
1297 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001298 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001299 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001300 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001301 } // if/else
1302
srs5694e7b4ff92009-08-18 13:16:10 -04001303 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001304 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1305 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001306 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001307 } // if
1308
srs5694cb76c672010-02-11 22:22:22 -05001309 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1310 cerr << "Warning! Read error " << errno
1311 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001312 } else {
1313 allOK = 0;
1314 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001315 // Something went badly wrong, so blank out partitions
1316 if (allOK == 0) {
1317 cerr << "Improper backup file! Clearing all partition data!\n";
1318 ClearGPTData();
1319 protectiveMBR.MakeProtectiveMBR();
1320 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001321 } else {
1322 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001323 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001324 } // if/else
1325
srs5694e7b4ff92009-08-18 13:16:10 -04001326 return allOK;
1327} // GPTData::LoadGPTBackup()
1328
srs569408bb0da2010-02-19 17:19:55 -05001329int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001330 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001331} // GPTData::SaveMBR()
1332
1333// This function destroys the on-disk GPT structures, but NOT the on-disk
1334// MBR.
1335// Returns 1 if the operation succeeds, 0 if not.
1336int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001337 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001338 uint8_t blankSector[512];
1339 uint8_t* emptyTable;
1340
srs569401f7f082011-03-15 23:53:31 -04001341 memset(blankSector, 0, sizeof(blankSector));
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001342 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001343
1344 if (myDisk.OpenForWrite()) {
1345 if (!myDisk.Seek(mainHeader.currentLBA))
1346 allOK = 0;
1347 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1348 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1349 allOK = 0;
1350 } // if
1351 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1352 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001353 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001354 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001355 if (emptyTable == NULL) {
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001356 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
1357 exit(1);
srs56946aae2a92011-06-10 01:16:51 -04001358 } // if
srs569401f7f082011-03-15 23:53:31 -04001359 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001360 if (allOK) {
1361 sum = myDisk.Write(emptyTable, tableSize);
1362 if (sum != tableSize) {
1363 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1364 allOK = 0;
1365 } // if write failed
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001366 } // if
1367 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1368 allOK = 0;
1369 if (allOK) {
1370 sum = myDisk.Write(emptyTable, tableSize);
1371 if (sum != tableSize) {
1372 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1373 << errno << "\n";
1374 allOK = 0;
1375 } // if wrong size written
srs569408bb0da2010-02-19 17:19:55 -05001376 } // if
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001377 if (!myDisk.Seek(secondHeader.currentLBA))
1378 allOK = 0;
1379 if (allOK) {
1380 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1381 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs569408bb0da2010-02-19 17:19:55 -05001382 allOK = 0;
1383 } // if
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001384 } // if
Greg Hartman2c2deeb2016-04-21 18:20:25 -07001385 if (syncing) {
1386 myDisk.DiskSync();
1387 }
srs569408bb0da2010-02-19 17:19:55 -05001388 myDisk.Close();
1389 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1390 << "other utilities.\n";
1391 delete[] emptyTable;
1392 } else {
srs56945a608532011-03-17 13:53:01 -04001393 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001394 } // if/else (fd != -1)
1395 return (allOK);
1396} // GPTDataTextUI::DestroyGPT()
1397
1398// Wipe MBR data from the disk (zero it out completely)
1399// Returns 1 on success, 0 on failure.
1400int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001401 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001402 uint8_t blankSector[512];
1403
srs569401f7f082011-03-15 23:53:31 -04001404 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001405
srs569401f7f082011-03-15 23:53:31 -04001406 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1407
srs569408bb0da2010-02-19 17:19:55 -05001408 if (!allOK)
1409 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1410 return allOK;
1411} // GPTData::DestroyMBR(void)
1412
srs5694e4ac11e2009-08-31 10:13:04 -04001413// Tell user whether Apple Partition Map (APM) was discovered....
1414void GPTData::ShowAPMState(void) {
1415 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001416 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001417 else
srs5694fed16d02010-01-27 23:03:40 -05001418 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001419} // GPTData::ShowAPMState()
1420
1421// Tell user about the state of the GPT data....
1422void GPTData::ShowGPTState(void) {
1423 switch (state) {
1424 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001425 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001426 break;
1427 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001428 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001429 break;
1430 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001431 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001432 break;
1433 default:
srs5694fed16d02010-01-27 23:03:40 -05001434 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001435 break;
1436 } // switch
1437} // GPTData::ShowGPTState()
1438
1439// Display the basic GPT data
1440void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001441 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001442 uint64_t temp, totalFree;
1443
srs5694fed16d02010-01-27 23:03:40 -05001444 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001445 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001446 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001447 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001448 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001449 cout << "First usable sector is " << mainHeader.firstUsableLBA
1450 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001451 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001452 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001453 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001454 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001455 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001456 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001457 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001458 } // for
1459} // GPTData::DisplayGPTData()
1460
srs5694e4ac11e2009-08-31 10:13:04 -04001461// Show detailed information on the specified partition
Jeff Sharkeyd761ff52015-02-28 19:18:39 -08001462void GPTData::ShowPartDetails(uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001463 if ((partNum < numParts) && !IsFreePartNum(partNum)) {
Jeff Sharkeyd761ff52015-02-28 19:18:39 -08001464 partitions[partNum].ShowDetails(blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001465 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001466 cout << "Partition #" << partNum + 1 << " does not exist.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001467 } // if
1468} // GPTData::ShowPartDetails()
1469
srs5694e4ac11e2009-08-31 10:13:04 -04001470/**************************************************************************
1471 * *
1472 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1473 * (some of these functions may require user interaction) *
1474 * *
1475 **************************************************************************/
1476
srs569408bb0da2010-02-19 17:19:55 -05001477// Examines the MBR & GPT data to determine which set of data to use: the
1478// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1479// a new set of partitions (use_new). A return value of use_abort indicates
1480// that this function couldn't determine what to do. Overriding functions
1481// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001482WhichToUse GPTData::UseWhichPartitions(void) {
1483 WhichToUse which = use_new;
1484 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001485
1486 mbrState = protectiveMBR.GetValidity();
1487
1488 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001489 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001490 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1491 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001492 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001493 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1494 << "typing 'q' if you don't want to convert your MBR partitions\n"
1495 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001496 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001497 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001498 which = use_mbr;
1499 } // if
1500
1501 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001502 cout << "\n**********************************************************************\n"
1503 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1504 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001505 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001506 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001507 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1508 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001509 } // if
srs5694fed16d02010-01-27 23:03:40 -05001510 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001511 which = use_bsd;
1512 } // if
1513
1514 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001515 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001516 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001517 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001518 } // if
1519 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001520 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001521 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001522 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001523 } // if
1524 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001525 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001526 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001527 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001528 } // if
1529 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001530 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001531 } // if
1532
srs5694e4ac11e2009-08-31 10:13:04 -04001533 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001534 if (mbrState == gpt) {
1535 cout << "\a\a****************************************************************************\n"
1536 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1537 << "verification and recovery are STRONGLY recommended.\n"
1538 << "****************************************************************************\n";
1539 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001540 } else {
srs569408bb0da2010-02-19 17:19:55 -05001541 which = use_abort;
1542 } // if/else MBR says disk is GPT
1543 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001544
1545 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001546 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001547
1548 return which;
1549} // UseWhichPartitions()
1550
srs569408bb0da2010-02-19 17:19:55 -05001551// Convert MBR partition table into GPT form.
1552void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001553 int i, numToConvert;
1554 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001555
1556 // Clear out old data & prepare basics....
1557 ClearGPTData();
1558
1559 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001560 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001561 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001562 else
srs56940283dae2010-04-28 16:44:34 -04001563 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001564
1565 for (i = 0; i < numToConvert; i++) {
1566 origType = protectiveMBR.GetType(i);
1567 // don't waste CPU time trying to convert extended, hybrid protective, or
1568 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001569 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001570 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001571 partitions[i] = protectiveMBR.AsGPT(i);
1572 } // for
1573
1574 // Convert MBR into protective MBR
1575 protectiveMBR.MakeProtectiveMBR();
1576
1577 // Record that all original CRCs were OK so as not to raise flags
1578 // when doing a disk verification
1579 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001580} // GPTData::XFormPartitions()
1581
1582// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001583// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001584// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001585int GPTData::XFormDisklabel(uint32_t partNum) {
1586 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001587 int goOn = 1, numDone = 0;
1588 BSDData disklabel;
1589
srs569408bb0da2010-02-19 17:19:55 -05001590 if (GetPartRange(&low, &high) == 0) {
1591 goOn = 0;
1592 cout << "No partitions!\n";
1593 } // if
1594 if (partNum > high) {
1595 goOn = 0;
1596 cout << "Specified partition is invalid!\n";
1597 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001598
srs569408bb0da2010-02-19 17:19:55 -05001599 // If all is OK, read the disklabel and convert it.
1600 if (goOn) {
1601 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1602 partitions[partNum].GetLastLBA());
1603 if ((goOn) && (disklabel.IsDisklabel())) {
1604 numDone = XFormDisklabel(&disklabel);
1605 if (numDone == 1)
1606 cout << "Converted 1 BSD partition.\n";
1607 else
1608 cout << "Converted " << numDone << " BSD partitions.\n";
1609 } else {
1610 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1611 } // if/else
1612 } // if
1613 if (numDone > 0) { // converted partitions; delete carrier
1614 partitions[partNum].BlankPartition();
1615 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001616 return numDone;
srs569455d92612010-03-07 22:16:07 -05001617} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001618
1619// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001620int GPTData::XFormDisklabel(BSDData* disklabel) {
1621 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001622
srs569408bb0da2010-02-19 17:19:55 -05001623 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001624 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001625 partNum = FindFirstFreePart();
1626 if (partNum >= 0) {
1627 partitions[partNum] = disklabel->AsGPT(i);
1628 if (partitions[partNum].IsUsed())
1629 numDone++;
1630 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001631 } // for
srs569408bb0da2010-02-19 17:19:55 -05001632 if (partNum == -1)
1633 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001634 } // if
1635
1636 // Record that all original CRCs were OK so as not to raise flags
1637 // when doing a disk verification
1638 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1639
1640 return numDone;
1641} // GPTData::XFormDisklabel(BSDData* disklabel)
1642
srs569408bb0da2010-02-19 17:19:55 -05001643// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1644// partition has the active/bootable flag UNset and uses the GPT fdisk
1645// type code divided by 0x0100 as the MBR type code.
1646// Returns 1 if operation was 100% successful, 0 if there were ANY
1647// problems.
srs5694978041c2009-09-21 20:51:47 -04001648int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001649 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001650
srs5694978041c2009-09-21 20:51:47 -04001651 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001652 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001653 allOK = 0;
1654 } // if
srs56940283dae2010-04-28 16:44:34 -04001655 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001656 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001657 allOK = 0;
1658 } // if
1659 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001660 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001661 allOK = 0;
1662 } // if
1663 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1664 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1665 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001666 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1667 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001668 } // if
srs5694978041c2009-09-21 20:51:47 -04001669 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001670 (uint32_t) partitions[gptPart].GetLengthLBA(),
1671 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001672 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001673 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1674 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1675 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001676 allOK = 0;
1677 } // if/else
1678 return allOK;
1679} // GPTData::OnePartToMBR()
1680
srs5694e4ac11e2009-08-31 10:13:04 -04001681
1682/**********************************************************************
1683 * *
1684 * Functions that adjust GPT data structures WITHOUT user interaction *
1685 * (they may display information for the user's benefit, though) *
1686 * *
1687 **********************************************************************/
1688
1689// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001690// necessary, copies data if it already exists. If fillGPTSectors is 1
1691// (the default), rounds numEntries to fill all the sectors necessary to
1692// hold the GPT.
1693// Returns 1 if all goes well, 0 if an error is encountered.
1694int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001695 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001696 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001697 int allOK = 1;
1698
1699 // First, adjust numEntries upward, if necessary, to get a number
1700 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001701 entriesPerSector = blockSize / GPT_SIZE;
1702 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001703 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001704 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001705 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001706 } // if
1707
srs5694247657a2009-11-26 18:36:12 -05001708 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001709 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001710 // partition table, which causes problems when loading data from a RAID
1711 // array that's been expanded because this function is called when loading
1712 // data.
srs56940283dae2010-04-28 16:44:34 -04001713 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001714 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001715 if (newParts != NULL) {
1716 if (partitions != NULL) { // existing partitions; copy them over
1717 GetPartRange(&i, &high);
1718 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001719 cout << "The highest-numbered partition is " << high + 1
1720 << ", which is greater than the requested\n"
1721 << "partition table size of " << numEntries
1722 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001723 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001724 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001725 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001726 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001727 copyNum = numEntries;
1728 else
srs56940283dae2010-04-28 16:44:34 -04001729 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001730 for (i = 0; i < copyNum; i++) {
1731 newParts[i] = partitions[i];
1732 } // for
srs569401f7f082011-03-15 23:53:31 -04001733 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001734 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001735 } // if
1736 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001737 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001738 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001739 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001740 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001741 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1742 MoveSecondHeaderToEnd();
1743 if (diskSize > 0)
1744 CheckGPTSize();
1745 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001746 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001747 allOK = 0;
1748 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001749 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001750 mainHeader.numParts = numParts;
1751 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001752 return (allOK);
1753} // GPTData::SetGPTSize()
1754
1755// Blank the partition array
1756void GPTData::BlankPartitions(void) {
1757 uint32_t i;
1758
srs56940283dae2010-04-28 16:44:34 -04001759 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001760 partitions[i].BlankPartition();
1761 } // for
1762} // GPTData::BlankPartitions()
1763
srs5694ba00fed2010-01-12 18:18:36 -05001764// Delete a partition by number. Returns 1 if successful,
1765// 0 if there was a problem. Returns 1 if partition was in
1766// range, 0 if it was out of range.
1767int GPTData::DeletePartition(uint32_t partNum) {
1768 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001769 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001770
srs56940283dae2010-04-28 16:44:34 -04001771 numUsedParts = GetPartRange(&low, &high);
1772 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001773 // In case there's a protective MBR, look for & delete matching
1774 // MBR partition....
1775 startSector = partitions[partNum].GetFirstLBA();
1776 length = partitions[partNum].GetLengthLBA();
1777 protectiveMBR.DeleteByLocation(startSector, length);
1778
1779 // Now delete the GPT partition
1780 partitions[partNum].BlankPartition();
1781 } else {
srs5694fed16d02010-01-27 23:03:40 -05001782 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001783 retval = 0;
1784 } // if/else
1785 return retval;
1786} // GPTData::DeletePartition(uint32_t partNum)
1787
srs569408bb0da2010-02-19 17:19:55 -05001788// Non-interactively create a partition.
1789// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001790uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001791 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001792 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001793
1794 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001795 if (Align(&startSector)) {
1796 cout << "Information: Moved requested sector from " << origSector << " to "
1797 << startSector << " in\norder to align on " << sectorAlignment
1798 << "-sector boundaries.\n";
1799 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001800 if (IsFree(startSector) && (startSector <= endSector)) {
1801 if (FindLastInFree(startSector) >= endSector) {
1802 partitions[partNum].SetFirstLBA(startSector);
1803 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001804 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001805 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001806 } else retval = 0; // if free space until endSector
1807 } else retval = 0; // if startSector is free
1808 } else retval = 0; // if legal partition number
1809 return retval;
1810} // GPTData::CreatePartition(partNum, startSector, endSector)
1811
srs5694e4ac11e2009-08-31 10:13:04 -04001812// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001813// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001814void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001815 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001816 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001817} // GPTData::SortGPT()
1818
srs569408bb0da2010-02-19 17:19:55 -05001819// Swap the contents of two partitions.
1820// Returns 1 if successful, 0 if either partition is out of range
1821// (that is, not a legal number; either or both can be empty).
1822// Note that if partNum1 = partNum2 and this number is in range,
1823// it will be considered successful.
1824int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1825 GPTPart temp;
1826 int allOK = 1;
1827
srs56940283dae2010-04-28 16:44:34 -04001828 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001829 if (partNum1 != partNum2) {
1830 temp = partitions[partNum1];
1831 partitions[partNum1] = partitions[partNum2];
1832 partitions[partNum2] = temp;
1833 } // if
1834 } else allOK = 0; // partition numbers are valid
1835 return allOK;
1836} // GPTData::SwapPartitions()
1837
srs5694e4ac11e2009-08-31 10:13:04 -04001838// Set up data structures for entirely new set of partitions on the
1839// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001840// Note that this function does NOT clear the protectiveMBR data
1841// structure, since it may hold the original MBR partitions if the
1842// program was launched on an MBR disk, and those may need to be
1843// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001844int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001845 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001846
1847 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001848 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001849 partitions = NULL;
1850 SetGPTSize(NUM_GPT_ENTRIES);
1851
1852 // Now initialize a bunch of stuff that's static....
1853 mainHeader.signature = GPT_SIGNATURE;
1854 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001855 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001856 mainHeader.reserved = 0;
1857 mainHeader.currentLBA = UINT64_C(1);
1858 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1859 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1860 for (i = 0; i < GPT_RESERVED; i++) {
1861 mainHeader.reserved2[i] = '\0';
1862 } // for
srs56940873e9d2010-10-07 13:00:45 -04001863 if (blockSize > 0)
1864 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1865 else
1866 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001867
1868 // Now some semi-static items (computed based on end of disk)
1869 mainHeader.backupLBA = diskSize - UINT64_C(1);
1870 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1871
1872 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001873 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001874
1875 // Copy main header to backup header
1876 RebuildSecondHeader();
1877
1878 // Blank out the partitions array....
1879 BlankPartitions();
1880
1881 // Flag all CRCs as being OK....
1882 mainCrcOk = 1;
1883 secondCrcOk = 1;
1884 mainPartsCrcOk = 1;
1885 secondPartsCrcOk = 1;
1886
1887 return (goOn);
1888} // GPTData::ClearGPTData()
1889
srs5694247657a2009-11-26 18:36:12 -05001890// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001891// If the disk size has actually changed, this also adjusts the protective
1892// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001893// Used internally and called by the 'e' option on the recovery &
1894// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001895// to their arrays or to adjust data structures in restore operations
1896// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001897void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001898 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001899 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1900 if (protectiveMBR.GetValidity() == hybrid) {
1901 protectiveMBR.OptimizeEESize();
1902 RecomputeCHS();
1903 } // if
1904 if (protectiveMBR.GetValidity() == gpt)
1905 MakeProtectiveMBR();
1906 } // if
srs56948bb78762009-11-24 15:43:49 -05001907 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1908 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1909} // GPTData::FixSecondHeaderLocation()
1910
srs5694699941e2011-03-21 21:33:57 -04001911// Sets the partition's name to the specified UnicodeString without
1912// user interaction.
1913// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001914int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001915 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001916
srs5694699941e2011-03-21 21:33:57 -04001917 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001918 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001919 else
1920 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001921
1922 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001923} // GPTData::SetName
1924
1925// Set the disk GUID to the specified value. Note that the header CRCs must
1926// be recomputed after calling this function.
1927void GPTData::SetDiskGUID(GUIDData newGUID) {
1928 mainHeader.diskGUID = newGUID;
1929 secondHeader.diskGUID = newGUID;
1930} // SetDiskGUID()
1931
1932// Set the unique GUID of the specified partition. Returns 1 on
1933// successful completion, 0 if there were problems (invalid
1934// partition number).
1935int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1936 int retval = 0;
1937
srs56940283dae2010-04-28 16:44:34 -04001938 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001939 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001940 partitions[pn].SetUniqueGUID(theGUID);
1941 retval = 1;
1942 } // if
1943 } // if
1944 return retval;
1945} // GPTData::SetPartitionGUID()
1946
srs56949ba54212010-05-18 23:24:02 -04001947// Set new random GUIDs for the disk and all partitions. Intended to be used
1948// after disk cloning or similar operations that don't randomize the GUIDs.
1949void GPTData::RandomizeGUIDs(void) {
1950 uint32_t i;
1951
1952 mainHeader.diskGUID.Randomize();
1953 secondHeader.diskGUID = mainHeader.diskGUID;
1954 for (i = 0; i < numParts; i++)
1955 if (partitions[i].IsUsed())
1956 partitions[i].RandomizeUniqueGUID();
1957} // GPTData::RandomizeGUIDs()
1958
srs5694ba00fed2010-01-12 18:18:36 -05001959// Change partition type code non-interactively. Returns 1 if
1960// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001961int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1962 int retval = 1;
1963
1964 if (!IsFreePartNum(partNum)) {
1965 partitions[partNum].SetType(theGUID);
1966 } else retval = 0;
1967 return retval;
1968} // GPTData::ChangePartType()
1969
srs56949ba54212010-05-18 23:24:02 -04001970// Recompute the CHS values of all the MBR partitions. Used to reset
1971// CHS values that some BIOSes require, despite the fact that the
1972// resulting CHS values violate the GPT standard.
1973void GPTData::RecomputeCHS(void) {
1974 int i;
1975
1976 for (i = 0; i < 4; i++)
1977 protectiveMBR.RecomputeCHS(i);
1978} // GPTData::RecomputeCHS()
1979
srs56941d1448a2009-12-31 21:20:19 -05001980// Adjust sector number so that it falls on a sector boundary that's a
1981// multiple of sectorAlignment. This is done to improve the performance
1982// of Western Digital Advanced Format disks and disks with similar
1983// technology from other companies, which use 4096-byte sectors
1984// internally although they translate to 512-byte sectors for the
1985// benefit of the OS. If partitions aren't properly aligned on these
1986// disks, some filesystem data structures can span multiple physical
1987// sectors, degrading performance. This function should be called
1988// only on the FIRST sector of the partition, not the last!
1989// This function returns 1 if the alignment was altered, 0 if it
1990// was unchanged.
1991int GPTData::Align(uint64_t* sector) {
1992 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001993 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001994
1995 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001996 earlier = (*sector / sectorAlignment) * sectorAlignment;
1997 later = earlier + (uint64_t) sectorAlignment;
1998
1999 // Check to see that every sector between the earlier one and the
2000 // requested one is clear, and that it's not too early....
2001 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05002002 sectorOK = 1;
2003 testSector = earlier;
2004 do {
2005 sectorOK = IsFree(testSector++);
2006 } while ((sectorOK == 1) && (testSector < *sector));
2007 if (sectorOK == 1) {
2008 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04002009 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05002010 } // if
2011 } // if firstUsableLBA check
2012
2013 // If couldn't move the sector earlier, try to move it later instead....
2014 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2015 sectorOK = 1;
2016 testSector = later;
2017 do {
2018 sectorOK = IsFree(testSector--);
2019 } while ((sectorOK == 1) && (testSector > *sector));
2020 if (sectorOK == 1) {
2021 *sector = later;
srs56945a081752010-09-24 20:39:41 -04002022 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05002023 } // if
2024 } // if
srs56941d1448a2009-12-31 21:20:19 -05002025 } // if
2026 return retval;
2027} // GPTData::Align()
2028
srs5694e4ac11e2009-08-31 10:13:04 -04002029/********************************************************
2030 * *
2031 * Functions that return data about GPT data structures *
2032 * (most of these are inline in gpt.h) *
2033 * *
2034 ********************************************************/
2035
2036// Find the low and high used partition numbers (numbered from 0).
2037// Return value is the number of partitions found. Note that the
2038// *low and *high values are both set to 0 when no partitions
2039// are found, as well as when a single partition in the first
2040// position exists. Thus, the return value is the only way to
2041// tell when no partitions exist.
2042int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2043 uint32_t i;
2044 int numFound = 0;
2045
srs56940283dae2010-04-28 16:44:34 -04002046 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04002047 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04002048 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002049 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04002050 *high = i; // since we're counting up, set the high value
2051 // Set the low value only if it's not yet found...
2052 if (*low == (numParts + 1)) *low = i;
2053 numFound++;
2054 } // if
2055 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04002056
2057 // Above will leave *low pointing to its "not found" value if no partitions
2058 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002059 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002060 *low = 0;
2061 return numFound;
2062} // GPTData::GetPartRange()
2063
srs569408bb0da2010-02-19 17:19:55 -05002064// Returns the value of the first free partition, or -1 if none is
2065// unused.
2066int GPTData::FindFirstFreePart(void) {
2067 int i = 0;
2068
2069 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002070 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002071 i++;
srs56940283dae2010-04-28 16:44:34 -04002072 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002073 i = -1;
2074 } else i = -1;
2075 return i;
2076} // GPTData::FindFirstFreePart()
2077
srs5694978041c2009-09-21 20:51:47 -04002078// Returns the number of defined partitions.
2079uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002080 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002081
srs56940283dae2010-04-28 16:44:34 -04002082 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002083 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002084 counted++;
2085 } // for
2086 return counted;
2087} // GPTData::CountParts()
2088
srs5694e4ac11e2009-08-31 10:13:04 -04002089/****************************************************
2090 * *
2091 * Functions that return data about disk free space *
2092 * *
2093 ****************************************************/
2094
2095// Find the first available block after the starting point; returns 0 if
2096// there are no available blocks left
2097uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2098 uint64_t first;
2099 uint32_t i;
2100 int firstMoved = 0;
2101
2102 // Begin from the specified starting point or from the first usable
2103 // LBA, whichever is greater...
2104 if (start < mainHeader.firstUsableLBA)
2105 first = mainHeader.firstUsableLBA;
2106 else
2107 first = start;
2108
2109 // ...now search through all partitions; if first is within an
2110 // existing partition, move it to the next sector after that
2111 // partition and repeat. If first was moved, set firstMoved
2112 // flag; repeat until firstMoved is not set, so as to catch
2113 // cases where partitions are out of sequential order....
2114 do {
2115 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002116 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002117 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002118 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002119 first = partitions[i].GetLastLBA() + 1;
2120 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002121 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002122 } // for
2123 } while (firstMoved == 1);
2124 if (first > mainHeader.lastUsableLBA)
2125 first = 0;
2126 return (first);
2127} // GPTData::FindFirstAvailable()
2128
2129// Finds the first available sector in the largest block of unallocated
2130// space on the disk. Returns 0 if there are no available blocks left
2131uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002132 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002133
2134 start = 0;
2135 do {
2136 firstBlock = FindFirstAvailable(start);
2137 if (firstBlock != UINT32_C(0)) { // something's free...
2138 lastBlock = FindLastInFree(firstBlock);
2139 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2140 if (segmentSize > selectedSize) {
2141 selectedSize = segmentSize;
2142 selectedSegment = firstBlock;
2143 } // if
2144 start = lastBlock + 1;
2145 } // if
2146 } while (firstBlock != 0);
2147 return selectedSegment;
2148} // GPTData::FindFirstInLargest()
2149
srs5694cb76c672010-02-11 22:22:22 -05002150// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002151// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002152uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002153 uint64_t last;
2154 uint32_t i;
2155 int lastMoved = 0;
2156
2157 // Start by assuming the last usable LBA is available....
2158 last = mainHeader.lastUsableLBA;
2159
2160 // ...now, similar to algorithm in FindFirstAvailable(), search
2161 // through all partitions, moving last when it's in an existing
2162 // partition. Set the lastMoved flag so we repeat to catch cases
2163 // where partitions are out of logical order.
2164 do {
2165 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002166 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002167 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002168 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002169 last = partitions[i].GetFirstLBA() - 1;
2170 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002171 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002172 } // for
2173 } while (lastMoved == 1);
2174 if (last < mainHeader.firstUsableLBA)
2175 last = 0;
2176 return (last);
2177} // GPTData::FindLastAvailable()
2178
2179// Find the last available block in the free space pointed to by start.
2180uint64_t GPTData::FindLastInFree(uint64_t start) {
2181 uint64_t nearestStart;
2182 uint32_t i;
2183
2184 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002185 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002186 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002187 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002188 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002189 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002190 } // for
2191 return (nearestStart);
2192} // GPTData::FindLastInFree()
2193
2194// Finds the total number of free blocks, the number of segments in which
2195// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002196uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002197 uint64_t start = UINT64_C(0); // starting point for each search
2198 uint64_t totalFound = UINT64_C(0); // running total
2199 uint64_t firstBlock; // first block in a segment
2200 uint64_t lastBlock; // last block in a segment
2201 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002202 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002203
2204 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002205 if (diskSize > 0) {
2206 do {
2207 firstBlock = FindFirstAvailable(start);
2208 if (firstBlock != UINT64_C(0)) { // something's free...
2209 lastBlock = FindLastInFree(firstBlock);
2210 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2211 if (segmentSize > *largestSegment) {
2212 *largestSegment = segmentSize;
2213 } // if
2214 totalFound += segmentSize;
2215 num++;
2216 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002217 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002218 } while (firstBlock != 0);
2219 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002220 *numSegments = num;
2221 return totalFound;
2222} // GPTData::FindFreeBlocks()
2223
srs569455d92612010-03-07 22:16:07 -05002224// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2225// If it's allocated, return the partition number to which it's allocated
2226// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2227// returned in partNum if the sector is in use by basic GPT data structures.)
2228int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002229 int isFree = 1;
2230 uint32_t i;
2231
srs56940283dae2010-04-28 16:44:34 -04002232 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002233 if ((sector >= partitions[i].GetFirstLBA()) &&
2234 (sector <= partitions[i].GetLastLBA())) {
2235 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002236 if (partNum != NULL)
2237 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002238 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002239 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002240 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002241 (sector > mainHeader.lastUsableLBA)) {
2242 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002243 if (partNum != NULL)
2244 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002245 } // if
2246 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002247} // GPTData::IsFree()
2248
srs5694815fb652011-03-18 12:35:56 -04002249// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002250int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002251 return ((partNum < numParts) && (partitions != NULL) &&
2252 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002253} // GPTData::IsFreePartNum()
2254
srs5694815fb652011-03-18 12:35:56 -04002255// Returns 1 if partNum is in use.
2256int GPTData::IsUsedPartNum(uint32_t partNum) {
2257 return ((partNum < numParts) && (partitions != NULL) &&
2258 (partitions[partNum].IsUsed()));
2259} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002260
2261/***********************************************************
2262 * *
2263 * Change how functions work or return information on them *
2264 * *
2265 ***********************************************************/
2266
2267// Set partition alignment value; partitions will begin on multiples of
2268// the specified value
2269void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002270 if (n > 0)
2271 sectorAlignment = n;
2272 else
2273 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002274} // GPTData::SetAlignment()
2275
2276// Compute sector alignment based on the current partitions (if any). Each
2277// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002278// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2279// sector size), but not by the previously-located alignment value, then the
2280// alignment value is adjusted down. If the computed alignment is less than 8
2281// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002282// is a safety measure for Advanced Format drives. If no partitions are
2283// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002284// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002285// drives are aligned to 2048-sector multiples but the program won't complain
2286// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002287// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002288// Returns the computed alignment value.
2289uint32_t GPTData::ComputeAlignment(void) {
2290 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002291 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002292
srs56940873e9d2010-10-07 13:00:45 -04002293 if (blockSize > 0)
2294 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2295 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002296 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002297 if (partitions[i].IsUsed()) {
2298 found = 0;
2299 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002300 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002301 if ((partitions[i].GetFirstLBA() % align) == 0) {
2302 found = 1;
2303 } else {
2304 exponent--;
2305 } // if/else
2306 } // while
2307 } // if
2308 } // for
srs56940873e9d2010-10-07 13:00:45 -04002309 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2310 align = MIN_AF_ALIGNMENT;
2311 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002312 return align;
2313} // GPTData::ComputeAlignment()
2314
srs5694e4ac11e2009-08-31 10:13:04 -04002315/********************************
2316 * *
2317 * Endianness support functions *
2318 * *
2319 ********************************/
2320
srs56942a9f5da2009-08-26 00:48:01 -04002321void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002322 ReverseBytes(&header->signature, 8);
2323 ReverseBytes(&header->revision, 4);
2324 ReverseBytes(&header->headerSize, 4);
2325 ReverseBytes(&header->headerCRC, 4);
2326 ReverseBytes(&header->reserved, 4);
2327 ReverseBytes(&header->currentLBA, 8);
2328 ReverseBytes(&header->backupLBA, 8);
2329 ReverseBytes(&header->firstUsableLBA, 8);
2330 ReverseBytes(&header->lastUsableLBA, 8);
2331 ReverseBytes(&header->partitionEntriesLBA, 8);
2332 ReverseBytes(&header->numParts, 4);
2333 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2334 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002335 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002336} // GPTData::ReverseHeaderBytes()
2337
srs56940283dae2010-04-28 16:44:34 -04002338// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002339void GPTData::ReversePartitionBytes() {
2340 uint32_t i;
2341
srs56940283dae2010-04-28 16:44:34 -04002342 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002343 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002344 } // for
2345} // GPTData::ReversePartitionBytes()
2346
srs56949ddc14b2010-08-22 22:44:42 -04002347// Validate partition number
2348bool GPTData::ValidPartNum (const uint32_t partNum) {
2349 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002350 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002351 return false;
2352 } // if
2353 return true;
2354} // GPTData::ValidPartNum
2355
srs56945a081752010-09-24 20:39:41 -04002356// Return a single partition for inspection (not modification!) by other
2357// functions.
2358const GPTPart & GPTData::operator[](uint32_t partNum) const {
2359 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002360 cerr << "Partition number out of range (" << partNum << " requested, but only "
2361 << numParts << " available)\n";
2362 exit(1);
2363 } // if
2364 if (partitions == NULL) {
2365 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2366 exit(1);
srs56945a081752010-09-24 20:39:41 -04002367 } // if
2368 return partitions[partNum];
2369} // operator[]
2370
2371// Return (not for modification!) the disk's GUID value
2372const GUIDData & GPTData::GetDiskGUID(void) const {
2373 return mainHeader.diskGUID;
2374} // GPTData::GetDiskGUID()
2375
srs56949ddc14b2010-08-22 22:44:42 -04002376// Manage attributes for a partition, based on commands passed to this function.
2377// (Function is non-interactive.)
2378// Returns 1 if a modification command succeeded, 0 if the command should not have
2379// modified data, and -1 if a modification command failed.
2380int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2381 int retval = 0;
2382 Attributes theAttr;
2383
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002384 if (partNum >= (int) numParts) {
2385 cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2386 retval = -1;
srs56949ddc14b2010-08-22 22:44:42 -04002387 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002388 if (command == "show") {
2389 ShowAttributes(partNum);
2390 } else if (command == "get") {
2391 GetAttribute(partNum, bits);
srs56949ddc14b2010-08-22 22:44:42 -04002392 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002393 theAttr = partitions[partNum].GetAttributes();
2394 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2395 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2396 retval = 1;
2397 } else {
2398 retval = -1;
2399 } // if/else
2400 } // if/elseif/else
2401 } // if/else invalid partition #
srs56949ddc14b2010-08-22 22:44:42 -04002402
2403 return retval;
2404} // GPTData::ManageAttributes()
2405
2406// Show all attributes for a specified partition....
2407void GPTData::ShowAttributes(const uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002408 if ((partNum < numParts) && partitions[partNum].IsUsed())
srs5694e69e6802012-01-20 22:37:12 -05002409 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002410} // GPTData::ShowAttributes
2411
2412// Show whether a single attribute bit is set (terse output)...
2413void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002414 if (partNum < numParts)
2415 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002416} // GPTData::GetAttribute
2417
2418
srs56942a9f5da2009-08-26 00:48:01 -04002419/******************************************
2420 * *
2421 * Additional non-class support functions *
2422 * *
2423 ******************************************/
2424
srs5694e7b4ff92009-08-18 13:16:10 -04002425// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2426// never fail these tests, but the struct types may fail depending on compile options.
2427// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2428// sizes.
2429int SizesOK(void) {
2430 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002431
2432 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002433 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002434 allOK = 0;
2435 } // if
2436 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002437 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002438 allOK = 0;
2439 } // if
2440 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002441 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002442 allOK = 0;
2443 } // if
2444 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002445 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002446 allOK = 0;
2447 } // if
2448 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002449 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002450 allOK = 0;
2451 } // if
srs5694978041c2009-09-21 20:51:47 -04002452 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002453 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002454 allOK = 0;
2455 } // if
2456 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002457 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002458 allOK = 0;
2459 } // if
srs5694221e0872009-08-29 15:00:31 -04002460 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002461 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002462 allOK = 0;
2463 } // if
srs56946699b012010-02-04 00:55:30 -05002464 if (sizeof(GUIDData) != 16) {
2465 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2466 allOK = 0;
2467 } // if
2468 if (sizeof(PartType) != 16) {
Roderick W. Smith84aaff62014-02-17 16:17:11 -05002469 cerr << "PartType is " << sizeof(PartType) << " bytes, should be 16 bytes; aborting!\n";
srs56946699b012010-02-04 00:55:30 -05002470 allOK = 0;
2471 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002472 return (allOK);
2473} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002474