blob: 3bd56c577d47580be6fac00176e5aa1c8cdf11c1 [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
srs5694221e0872009-08-29 15:00:31 -04006/* This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
7 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>
13#include <unistd.h>
14#include <stdlib.h>
15#include <stdint.h>
16#include <fcntl.h>
17#include <string.h>
18#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs5694e7b4ff92009-08-18 13:16:10 -040022#include "crc32.h"
23#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040024#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040025#include "support.h"
26#include "parttypes.h"
27#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050028#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040029
30using namespace std;
31
32/****************************************
33 * *
34 * GPTData class and related structures *
35 * *
36 ****************************************/
37
srs5694e4ac11e2009-08-31 10:13:04 -040038// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040039GPTData::GPTData(void) {
40 blockSize = SECTOR_SIZE; // set a default
41 diskSize = 0;
42 partitions = NULL;
43 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050044 device = "";
srs56945d58fe02010-01-03 20:57:08 -050045 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040046 mainCrcOk = 0;
47 secondCrcOk = 0;
48 mainPartsCrcOk = 0;
49 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040050 apmFound = 0;
51 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050052 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050053 beQuiet = 0;
54 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040055 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050056 mainHeader.numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040057 SetGPTSize(NUM_GPT_ENTRIES);
58} // GPTData default constructor
59
60// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050061GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040062 blockSize = SECTOR_SIZE; // set a default
63 diskSize = 0;
64 partitions = NULL;
65 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050066 device = "";
srs56945d58fe02010-01-03 20:57:08 -050067 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040068 mainCrcOk = 0;
69 secondCrcOk = 0;
70 mainPartsCrcOk = 0;
71 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040072 apmFound = 0;
73 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050074 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050075 beQuiet = 0;
76 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040077 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050078 mainHeader.numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050079 if (!LoadPartitions(filename))
80 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050081} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040082
srs5694e4ac11e2009-08-31 10:13:04 -040083// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040084GPTData::~GPTData(void) {
85 free(partitions);
86} // GPTData destructor
87
srs5694e4ac11e2009-08-31 10:13:04 -040088/*********************************************************************
89 * *
90 * Begin functions that verify data, or that adjust the verification *
91 * information (compute CRCs, rebuild headers) *
92 * *
93 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040094
srs5694e4ac11e2009-08-31 10:13:04 -040095// Perform detailed verification, reporting on any problems found, but
96// do *NOT* recover from these problems. Returns the total number of
97// problems identified.
98int GPTData::Verify(void) {
srs56941d1448a2009-12-31 21:20:19 -050099 int problems = 0, numSegments, i;
100 uint64_t totalFree, largestSegment, firstSector;
srs5694e4ac11e2009-08-31 10:13:04 -0400101 char tempStr[255], siTotal[255], siLargest[255];
102
103 // First, check for CRC errors in the GPT data....
104 if (!mainCrcOk) {
105 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500106 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
107 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
108 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
109 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400110 } // if
111 if (!mainPartsCrcOk) {
112 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500113 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
114 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
115 << "transformation menu). This report may be a false alarm if you've already\n"
116 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400117 } // if
118 if (!secondCrcOk) {
119 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500120 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
121 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
122 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
123 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400124 } // if
125 if (!secondPartsCrcOk) {
126 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500127 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
128 << "be corrupt. This program will automatically create a new backup partition\n"
129 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400130 } // if
131
srs5694978041c2009-09-21 20:51:47 -0400132 // Now check that the main and backup headers both point to themselves....
133 if (mainHeader.currentLBA != 1) {
134 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500135 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
136 << "is being automatically corrected, but it may be a symptom of more serious\n"
137 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400138 mainHeader.currentLBA = 1;
139 } // if
140 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
141 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500142 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
143 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
144 << "option on the experts' menu to adjust the secondary header's and partition\n"
145 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400146 } // if
147
148 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400149 if (mainHeader.currentLBA != secondHeader.backupLBA) {
150 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500151 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
152 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
153 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400154 } // if
155 if (mainHeader.backupLBA != secondHeader.currentLBA) {
156 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500157 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
158 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
159 << secondHeader.currentLBA << ").\n"
160 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400161 } // if
162 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
163 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500164 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
165 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
166 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400167 } // if
168 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
169 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500170 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
171 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
172 << secondHeader.lastUsableLBA << ")\n"
173 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400174 } // if
175 if ((mainHeader.diskGUID.data1 != secondHeader.diskGUID.data1) ||
176 (mainHeader.diskGUID.data2 != secondHeader.diskGUID.data2)) {
177 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500178 cout << "\nProblem: main header's disk GUID (" << GUIDToStr(mainHeader.diskGUID)
179 << ") doesn't\nmatch the backup GPT header's disk GUID ("
180 << GUIDToStr(secondHeader.diskGUID) << ")\n"
181 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
182 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400183 } // if
184 if (mainHeader.numParts != secondHeader.numParts) {
185 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500186 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
187 << ") doesn't\nmatch the backup GPT header's number of partitions ("
188 << secondHeader.numParts << ")\n"
189 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400190 } // if
191 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
192 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500193 cout << "\nProblem: main GPT header's size of partition entries ("
194 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
195 << "match the backup GPT header's size of partition entries ("
196 << secondHeader.sizeOfPartitionEntries << ")\n"
197 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
198 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400199 } // if
200
201 // Now check for a few other miscellaneous problems...
202 // Check that the disk size will hold the data...
203 if (mainHeader.backupLBA > diskSize) {
204 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500205 cout << "\nProblem: Disk is too small to hold all the data!\n"
206 << "(Disk size is " << diskSize << " sectors, needs to be "
207 << mainHeader.backupLBA << " sectors.)\n"
208 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400209 } // if
210
211 // Check for overlapping partitions....
212 problems += FindOverlaps();
213
214 // Check for mismatched MBR and GPT partitions...
215 problems += FindHybridMismatches();
216
217 // Verify that partitions don't run into GPT data areas....
218 problems += CheckGPTSize();
219
srs56941d1448a2009-12-31 21:20:19 -0500220 // Check that partitions are aligned on proper boundaries (for WD Advanced
221 // Format and similar disks)....
222 for (i = 0; i < mainHeader.numParts; i++) {
223 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500224 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
225 << sectorAlignment << "-sector boundary. This may\nresult "
226 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500227 } // if
228 } // for
229
srs5694e4ac11e2009-08-31 10:13:04 -0400230 // Now compute available space, but only if no problems found, since
231 // problems could affect the results
232 if (problems == 0) {
233 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500234 strcpy(siTotal, BytesToSI(totalFree * (uint64_t) blockSize).c_str());
235 strcpy(siLargest, BytesToSI(largestSegment * (uint64_t) blockSize).c_str());
236 cout << "No problems found. " << totalFree << " free sectors ("
237 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
238 << numSegments << "\nsegments, the largest of which is "
239 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
240 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } else {
srs56940a697312010-01-28 21:10:52 -0500242 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400243 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400244
245 return (problems);
246} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400247
248// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400249// do, issues a warning but takes no action. Returns number of problems
250// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400251int GPTData::CheckGPTSize(void) {
252 uint64_t overlap, firstUsedBlock, lastUsedBlock;
253 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400254 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400255
256 // first, locate the first & last used blocks
257 firstUsedBlock = UINT64_MAX;
258 lastUsedBlock = 0;
259 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400260 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400261 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400262 firstUsedBlock = partitions[i].GetFirstLBA();
263 if (partitions[i].GetLastLBA() > lastUsedBlock)
264 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400265 } // for
266
267 // If the disk size is 0 (the default), then it means that various
268 // variables aren't yet set, so the below tests will be useless;
269 // therefore we should skip everything
270 if (diskSize != 0) {
271 if (mainHeader.firstUsableLBA > firstUsedBlock) {
272 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500273 cout << "Warning! Main partition table overlaps the first partition by "
274 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400275 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "Try reducing the partition table size by " << overlap * 4
277 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400278 } else {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400280 } // if/else
281 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400282 } // Problem at start of disk
283 if (mainHeader.lastUsableLBA < lastUsedBlock) {
284 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs5694fed16d02010-01-27 23:03:40 -0500285 cout << "Warning! Secondary partition table overlaps the last partition by "
286 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400287 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500288 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400289 } else {
srs5694fed16d02010-01-27 23:03:40 -0500290 cout << "Try reducing the partition table size by " << overlap * 4
291 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400292 } // if/else
293 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400294 } // Problem at end of disk
295 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400296 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400297} // GPTData::CheckGPTSize()
298
srs5694e7b4ff92009-08-18 13:16:10 -0400299// Check the validity of the GPT header. Returns 1 if the main header
300// is valid, 2 if the backup header is valid, 3 if both are valid, and
301// 0 if neither is valid. Note that this function just checks the GPT
302// signature and revision numbers, not CRCs or other data.
303int GPTData::CheckHeaderValidity(void) {
304 int valid = 3;
305
srs5694fed16d02010-01-27 23:03:40 -0500306 cout.setf(ios::uppercase);
307 cout.fill('0');
308
309 // Note: failed GPT signature checks produce no error message because
310 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400311 if (mainHeader.signature != GPT_SIGNATURE) {
312 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400313 } else if ((mainHeader.revision != 0x00010000) && valid) {
314 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500315 cout << "Unsupported GPT version in main header; read 0x";
316 cout.width(8);
317 cout << hex << mainHeader.revision << ", should be\n0x";
318 cout.width(8);
319 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400320 } // if/else/if
321
322 if (secondHeader.signature != GPT_SIGNATURE) {
323 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } else if ((secondHeader.revision != 0x00010000) && valid) {
325 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500326 cout << "Unsupported GPT version in backup header; read 0x";
327 cout.width(8);
328 cout << hex << secondHeader.revision << ", should be\n0x";
329 cout.width(8);
330 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400331 } // if/else/if
332
srs56942a9f5da2009-08-26 00:48:01 -0400333 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400334 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400335 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400336 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400337 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500338 } // if
srs5694fed16d02010-01-27 23:03:40 -0500339 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400340
srs5694fed16d02010-01-27 23:03:40 -0500341 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400342} // GPTData::CheckHeaderValidity()
343
344// Check the header CRC to see if it's OK...
srs56942a9f5da2009-08-26 00:48:01 -0400345// Note: Must be called BEFORE byte-order reversal on big-endian
346// systems!
srs5694e7b4ff92009-08-18 13:16:10 -0400347int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400348 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400349
srs56942a9f5da2009-08-26 00:48:01 -0400350 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400351 // computation to be valid
352 oldCRC = header->headerCRC;
353 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400354 hSize = header->headerSize;
355
356 // If big-endian system, reverse byte order
357 if (IsLittleEndian() == 0) {
358 ReverseBytes(&oldCRC, 4);
359 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400360
361 // Initialize CRC functions...
362 chksum_crc32gentab();
363
364 // Compute CRC, restore original, and return result of comparison
365 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400366 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400367 return (oldCRC == newCRC);
368} // GPTData::CheckHeaderCRC()
369
srs56942a9f5da2009-08-26 00:48:01 -0400370// Recompute all the CRCs. Must be called before saving (but after reversing
371// byte order on big-endian systems) if any changes have been made.
srs5694e7b4ff92009-08-18 13:16:10 -0400372void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400373 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400374 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400375
376 // Initialize CRC functions...
377 chksum_crc32gentab();
378
srs5694978041c2009-09-21 20:51:47 -0400379 hSize = mainHeader.headerSize;
srs56942a9f5da2009-08-26 00:48:01 -0400380 littleEndian = IsLittleEndian();
381
srs5694e7b4ff92009-08-18 13:16:10 -0400382 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400383 trueNumParts = mainHeader.numParts;
384 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400385 ReverseBytes(&trueNumParts, 4); // unreverse this key piece of data....
srs56942a9f5da2009-08-26 00:48:01 -0400386 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400387 mainHeader.partitionEntriesCRC = crc;
388 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400389 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400390 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
391 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400392 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400393
394 // Zero out GPT tables' own CRCs (required for correct computation)
395 mainHeader.headerCRC = 0;
396 secondHeader.headerCRC = 0;
397
398 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400399 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400400 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400401 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400402 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400403 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400404 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400405 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400406 secondHeader.headerCRC = crc;
407} // GPTData::RecomputeCRCs()
408
srs5694e7b4ff92009-08-18 13:16:10 -0400409// Rebuild the main GPT header, using the secondary header as a model.
410// Typically called when the main header has been found to be corrupt.
411void GPTData::RebuildMainHeader(void) {
412 int i;
413
414 mainHeader.signature = GPT_SIGNATURE;
415 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400416 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400417 mainHeader.headerCRC = UINT32_C(0);
418 mainHeader.reserved = secondHeader.reserved;
419 mainHeader.currentLBA = secondHeader.backupLBA;
420 mainHeader.backupLBA = secondHeader.currentLBA;
421 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
422 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
423 mainHeader.diskGUID.data1 = secondHeader.diskGUID.data1;
424 mainHeader.diskGUID.data2 = secondHeader.diskGUID.data2;
425 mainHeader.partitionEntriesLBA = UINT64_C(2);
426 mainHeader.numParts = secondHeader.numParts;
427 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
428 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
429 for (i = 0 ; i < GPT_RESERVED; i++)
430 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500431 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400432} // GPTData::RebuildMainHeader()
433
434// Rebuild the secondary GPT header, using the main header as a model.
435void GPTData::RebuildSecondHeader(void) {
436 int i;
437
438 secondHeader.signature = GPT_SIGNATURE;
439 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400440 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400441 secondHeader.headerCRC = UINT32_C(0);
442 secondHeader.reserved = mainHeader.reserved;
443 secondHeader.currentLBA = mainHeader.backupLBA;
444 secondHeader.backupLBA = mainHeader.currentLBA;
445 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
446 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
447 secondHeader.diskGUID.data1 = mainHeader.diskGUID.data1;
448 secondHeader.diskGUID.data2 = mainHeader.diskGUID.data2;
449 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
450 secondHeader.numParts = mainHeader.numParts;
451 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
452 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
453 for (i = 0 ; i < GPT_RESERVED; i++)
454 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500455 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400456} // GPTData::RebuildSecondHeader()
457
458// Search for hybrid MBR entries that have no corresponding GPT partition.
459// Returns number of such mismatches found
460int GPTData::FindHybridMismatches(void) {
461 int i, j, found, numFound = 0;
462 uint64_t mbrFirst, mbrLast;
463
464 for (i = 0; i < 4; i++) {
465 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
466 j = 0;
467 found = 0;
468 do {
469 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
470 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
471 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
472 (partitions[j].GetLastLBA() == mbrLast))
473 found = 1;
474 j++;
475 } while ((!found) && (j < mainHeader.numParts));
476 if (!found) {
477 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500478 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
479 << i + 1 << ", of type 0x";
480 cout.fill('0');
481 cout.setf(ios::uppercase);
482 cout.width(2);
483 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
484 << "has no corresponding GPT partition! You may continue, but this condition\n"
485 << "might cause data loss in the future!\a\n" << dec;
486 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400487 } // if
488 } // if
489 } // for
490 return numFound;
491} // GPTData::FindHybridMismatches
492
493// Find overlapping partitions and warn user about them. Returns number of
494// overlapping partitions.
495int GPTData::FindOverlaps(void) {
496 int i, j, problems = 0;
497
498 for (i = 1; i < mainHeader.numParts; i++) {
499 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500500 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400501 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500502 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
503 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
504 << " to " << partitions[i].GetLastLBA() << "\n";
505 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
506 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400507 } // if
508 } // for j...
509 } // for i...
510 return problems;
511} // GPTData::FindOverlaps()
512
513/******************************************************************
514 * *
515 * Begin functions that load data from disk or save data to disk. *
516 * *
517 ******************************************************************/
518
519// Scan for partition data. This function loads the MBR data (regular MBR or
520// protective MBR) and loads BSD disklabel data (which is probably invalid).
521// It also looks for APM data, forces a load of GPT data, and summarizes
522// the results.
srs5694546a9c72010-01-26 16:00:26 -0500523void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400524 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400525
526 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500527 protectiveMBR.ReadMBRData(&myDisk);
528 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400529
530 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500531 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500532
533 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500534 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500535 protectiveMBR.ShowState();
536 bsdDisklabel.ShowState();
537 ShowAPMState(); // Show whether there's an Apple Partition Map present
538 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500539 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500540 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400541
542 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500543 cout << "\n*******************************************************************\n"
544 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500545 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500546 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500547 } // if
srs5694fed16d02010-01-27 23:03:40 -0500548 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400549 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400550} // GPTData::PartitionScan()
551
552// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500553int GPTData::LoadPartitions(const string & deviceFilename) {
srs5694fed16d02010-01-27 23:03:40 -0500554 int err;
srs5694e4ac11e2009-08-31 10:13:04 -0400555 int allOK = 1, i;
556 uint64_t firstBlock, lastBlock;
557 BSDData bsdDisklabel;
srs5694fed16d02010-01-27 23:03:40 -0500558 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400559
560 // First, do a test to see if writing will be possible later....
srs5694fed16d02010-01-27 23:03:40 -0500561 err = myDisk.OpenForWrite(deviceFilename);
562 if ((err == 0) && (!justLooking)) {
563 cout << "\aNOTE: Write test failed with error number " << errno
564 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
srs56947dbb9322010-01-20 16:56:30 -0500565#ifdef __FreeBSD__
srs5694fed16d02010-01-27 23:03:40 -0500566 cout << "You may be able to enable writes by exiting this program, typing\n"
567 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
568 << "program.\n";
srs56947dbb9322010-01-20 16:56:30 -0500569#endif
srs5694fed16d02010-01-27 23:03:40 -0500570 cout << "\n";
571// justLooking = 1;
srs56945d58fe02010-01-03 20:57:08 -0500572 } // if
srs5694546a9c72010-01-26 16:00:26 -0500573 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400574
srs5694546a9c72010-01-26 16:00:26 -0500575// if ((fd = open(deviceFilename, O_RDONLY)) != -1) {
576 if (myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400577 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500578 diskSize = myDisk.DiskSize(&err);
579 blockSize = (uint32_t) myDisk.GetBlockSize();
580 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500581 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500582 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400583
srs5694ba00fed2010-01-12 18:18:36 -0500584 whichWasUsed = UseWhichPartitions();
585 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400586 case use_mbr:
587 XFormPartitions();
588 break;
589 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500590 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400591// bsdDisklabel.DisplayBSDData();
592 ClearGPTData();
593 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
594 XFormDisklabel(&bsdDisklabel, 0);
595 break;
596 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500597 mbrState = protectiveMBR.GetValidity();
598 if ((mbrState == invalid) || (mbrState == mbr))
599 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400600 break;
601 case use_new:
602 ClearGPTData();
603 protectiveMBR.MakeProtectiveMBR();
604 break;
srs56943c0af382010-01-15 19:19:18 -0500605 case use_abort:
606 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500607 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500608 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400609 } // switch
610
611 // Now find the first and last sectors used by partitions...
612 if (allOK) {
613 firstBlock = mainHeader.backupLBA; // start high
614 lastBlock = 0; // start low
615 for (i = 0; i < mainHeader.numParts; i++) {
616 if ((partitions[i].GetFirstLBA() < firstBlock) &&
617 (partitions[i].GetFirstLBA() > 0))
618 firstBlock = partitions[i].GetFirstLBA();
619 if (partitions[i].GetLastLBA() > lastBlock)
620 lastBlock = partitions[i].GetLastLBA();
621 } // for
srs56943c0af382010-01-15 19:19:18 -0500622 CheckGPTSize();
srs5694e4ac11e2009-08-31 10:13:04 -0400623 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400624 } else {
625 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500626 cerr << "Problem opening " << deviceFilename << " for reading! Error is "
627 << errno << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400628 if (errno == EACCES) { // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -0500629 cerr << "You must run this program as root or use sudo!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400630 } // if
631 } // if/else
632 return (allOK);
633} // GPTData::LoadPartitions()
634
635// Loads the GPT, as much as possible. Returns 1 if this seems to have
636// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500637int GPTData::ForceLoadGPTData(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400638 int allOK = 1, validHeaders;
srs56940a697312010-01-28 21:10:52 -0500639 uint64_t seekTo;
srs5694fed16d02010-01-27 23:03:40 -0500640 uint8_t* storage;
srs5694e4ac11e2009-08-31 10:13:04 -0400641 uint32_t newCRC, sizeOfParts;
642
643 // Seek to and read the main GPT header
srs5694546a9c72010-01-26 16:00:26 -0500644 if (myDisk.Seek(1)) {
645 if (myDisk.Read(&mainHeader, 512) != 512) { // read main GPT header
srs5694fed16d02010-01-27 23:03:40 -0500646 cerr << "Warning! Error " << errno << " reading main GPT header!\n";
srs5694546a9c72010-01-26 16:00:26 -0500647 } // if read not OK
648 } else allOK = 0; // if/else seek OK
srs5694e4ac11e2009-08-31 10:13:04 -0400649 mainCrcOk = CheckHeaderCRC(&mainHeader);
650 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
651 ReverseHeaderBytes(&mainHeader);
652
srs56943f2fe992009-11-24 18:28:18 -0500653 // Load backup header, check its CRC, and store the results of the
654 // check for future reference. Load backup header using pointer in main
655 // header if possible; but if main header has a CRC error, or if it
656 // points to beyond the end of the disk, load the last sector of the
657 // disk instead.
658 if (mainCrcOk) {
659 if (mainHeader.backupLBA < diskSize) {
srs5694546a9c72010-01-26 16:00:26 -0500660 seekTo = mainHeader.backupLBA;
srs56943f2fe992009-11-24 18:28:18 -0500661 } else {
srs5694546a9c72010-01-26 16:00:26 -0500662 seekTo = diskSize - UINT64_C(1);
srs5694fed16d02010-01-27 23:03:40 -0500663 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
664 << "secondary header from the last sector of the disk! You should use 'v' to\n"
665 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
666 << "the disk.\n";
srs56943f2fe992009-11-24 18:28:18 -0500667 } // else
668 } else {
srs5694546a9c72010-01-26 16:00:26 -0500669 seekTo = diskSize - UINT64_C(1);
srs56943f2fe992009-11-24 18:28:18 -0500670 } // if/else (mainCrcOk)
671
srs5694546a9c72010-01-26 16:00:26 -0500672 if (myDisk.Seek(seekTo)) {
673 if (myDisk.Read(&secondHeader, 512) != 512) { // read secondary GPT header
srs5694fed16d02010-01-27 23:03:40 -0500674 cerr << "Warning! Error " << errno << " reading secondary GPT header!\n";
srs56945d58fe02010-01-03 20:57:08 -0500675 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400676 secondCrcOk = CheckHeaderCRC(&secondHeader);
677 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
678 ReverseHeaderBytes(&secondHeader);
679 } else {
680 allOK = 0;
681 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -0500682 cerr << "Unable to seek to secondary GPT header at sector "
683 << (diskSize - (UINT64_C(1))) << "!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400684 } // if/else lseek
685
686 // Return valid headers code: 0 = both headers bad; 1 = main header
687 // good, backup bad; 2 = backup header good, main header bad;
688 // 3 = both headers good. Note these codes refer to valid GPT
689 // signatures and version numbers; more subtle problems will elude
690 // this check!
691 validHeaders = CheckHeaderValidity();
692
693 // Read partitions (from primary array)
694 if (validHeaders > 0) { // if at least one header is OK....
695 // GPT appears to be valid....
696 state = gpt_valid;
697
698 // We're calling the GPT valid, but there's a possibility that one
699 // of the two headers is corrupt. If so, use the one that seems to
700 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500701 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500702 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
703 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400704 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500705 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400706 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500707 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500708 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
709 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500710 RebuildMainHeader();
711 state = gpt_corrupt;
712 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400713 } // if/else/if
714
srs5694546a9c72010-01-26 16:00:26 -0500715 // Figure out which partition table to load....
716 // Load the main partition table, since either its header's CRC is OK or the
717 // backup header's CRC is not OK....
718 if (mainCrcOk || !secondCrcOk) {
719 if (LoadMainTable() == 0)
720 allOK = 0;
721 } else { // bad main header CRC and backup header CRC is OK
722 state = gpt_corrupt;
723 if (LoadSecondTableAsMain()) {
srs5694fed16d02010-01-27 23:03:40 -0500724 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500725 } else { // backup table bad, bad main header CRC, but try main table in desperation....
726 if (LoadMainTable() == 0) {
727 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500728 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500729 } // if
730 } // if/else (LoadSecondTableAsMain())
731 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400732
733 // Load backup partition table into temporary storage to check
734 // its CRC and store the results, then discard this temporary
735 // storage, since we don't use it in any but recovery operations
srs5694546a9c72010-01-26 16:00:26 -0500736 seekTo = secondHeader.partitionEntriesLBA;
737 if ((myDisk.Seek(seekTo)) && (secondCrcOk)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400738 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -0500739 storage = (uint8_t*) malloc(sizeOfParts);
srs5694546a9c72010-01-26 16:00:26 -0500740 if (myDisk.Read(storage, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500741 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500742 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400743 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
744 free(storage);
745 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
746 } // if
747
srs5694546a9c72010-01-26 16:00:26 -0500748 // Problem with main partition table; if backup is OK, use it instead....
749 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
750 state = gpt_corrupt;
751 allOK = allOK && LoadSecondTableAsMain();
srs5694fed16d02010-01-27 23:03:40 -0500752 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
753 << "partition table\ninstead of main partition table!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500754 } // if
755
srs5694e4ac11e2009-08-31 10:13:04 -0400756 // Check for valid CRCs and warn if there are problems
757 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
758 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500759 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400760 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500761 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400762 } else {
763 state = gpt_invalid;
764 } // if/else
765 return allOK;
766} // GPTData::ForceLoadGPTData()
767
srs5694247657a2009-11-26 18:36:12 -0500768// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400769// main GPT header in memory MUST be valid for this call to do anything
770// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500771// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400772int GPTData::LoadMainTable(void) {
srs5694546a9c72010-01-26 16:00:26 -0500773 int fd, retval = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400774 uint32_t newCRC, sizeOfParts;
775
srs5694546a9c72010-01-26 16:00:26 -0500776 if (myDisk.OpenForRead(device)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400777 // Set internal data structures for number of partitions on the disk
778 SetGPTSize(mainHeader.numParts);
779
780 // Load main partition table, and record whether its CRC
781 // matches the stored value
srs5694546a9c72010-01-26 16:00:26 -0500782 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
783 retval = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400784 sizeOfParts = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694546a9c72010-01-26 16:00:26 -0500785 if (myDisk.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500786 cerr << "Warning! Error " << errno << " when loading the main partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500787 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500788 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400789 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
790 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
791 if (IsLittleEndian() == 0)
792 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500793 } else retval = 0; // if open for read....
srs5694e4ac11e2009-08-31 10:13:04 -0400794 return retval;
795} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400796
797// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500798// table. Used in repair functions, and when starting up if the main
799// partition table is damaged.
800// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
801int GPTData::LoadSecondTableAsMain(void) {
802 uint64_t seekTo;
srs5694e7b4ff92009-08-18 13:16:10 -0400803 uint32_t sizeOfParts, newCRC;
srs5694546a9c72010-01-26 16:00:26 -0500804 int retval = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400805
srs5694546a9c72010-01-26 16:00:26 -0500806 if (myDisk.OpenForRead(device)) {
807 seekTo = secondHeader.partitionEntriesLBA;
808 retval = myDisk.Seek(seekTo);
809 if (retval == 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400810 SetGPTSize(secondHeader.numParts);
811 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694546a9c72010-01-26 16:00:26 -0500812 if (myDisk.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500813 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500814 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500815 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400816 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
817 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs5694e4ac11e2009-08-31 10:13:04 -0400818 mainPartsCrcOk = secondPartsCrcOk;
srs56942a9f5da2009-08-26 00:48:01 -0400819 if (IsLittleEndian() == 0)
820 ReversePartitionBytes();
srs5694e7b4ff92009-08-18 13:16:10 -0400821 if (!secondPartsCrcOk) {
srs5694fed16d02010-01-27 23:03:40 -0500822 cout << "Caution! After loading backup partitions, the CRC still doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400823 } // if
824 } else {
srs5694fed16d02010-01-27 23:03:40 -0500825 cerr << "Error! Couldn't seek to backup partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400826 } // if/else
827 } else {
srs5694fed16d02010-01-27 23:03:40 -0500828 cerr << "Error! Couldn't open device " << device
829 << " when recovering backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500830 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400831 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500832 return retval;
srs5694e7b4ff92009-08-18 13:16:10 -0400833} // GPTData::LoadSecondTableAsMain()
834
srs5694e7b4ff92009-08-18 13:16:10 -0400835// Writes GPT (and protective MBR) to disk. Returns 1 on successful
836// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500837int GPTData::SaveGPTData(int quiet) {
srs5694978041c2009-09-21 20:51:47 -0400838 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400839 char answer, line[256];
srs5694e7b4ff92009-08-18 13:16:10 -0400840 uint64_t secondTable;
srs56942a9f5da2009-08-26 00:48:01 -0400841 uint32_t numParts;
srs56940a697312010-01-28 21:10:52 -0500842 uint64_t offset;
srs5694e7b4ff92009-08-18 13:16:10 -0400843
srs5694fed16d02010-01-27 23:03:40 -0500844 if (device == "") {
845 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400846 } // if
847
848 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500849
850 // This test should only fail on read-only disks....
851 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500852 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500853 allOK = 0;
854 } // if
855
srs5694e7b4ff92009-08-18 13:16:10 -0400856 // Is there enough space to hold the GPT headers and partition tables,
857 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400858 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400859 allOK = 0;
860 } // if
861
862 // Check that disk is really big enough to handle this...
863 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500864 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
865 << "problem (or it might not). Aborting!\n(Disk size is "
866 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400867 allOK = 0;
868 } // if
srs5694247657a2009-11-26 18:36:12 -0500869 // Check that second header is properly placed. Warn and ask if this should
870 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500871 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500872 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
873 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500874 if (GetYN() == 'Y') {
875 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500876 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500877 } else {
srs5694fed16d02010-01-27 23:03:40 -0500878 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500879 } // if correction requested
880 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400881
882 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400883 if (FindOverlaps() > 0) {
884 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500885 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400886 } // if
887
888 // Check for mismatched MBR and GPT data, but let it pass if found
889 // (function displays warning message)
890 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400891
srs56942a9f5da2009-08-26 00:48:01 -0400892 // Pull out some data that's needed before doing byte-order reversal on
893 // big-endian systems....
894 numParts = mainHeader.numParts;
895 secondTable = secondHeader.partitionEntriesLBA;
896 if (IsLittleEndian() == 0) {
897 // Reverse partition bytes first, since that function requires non-reversed
898 // data from the main header....
899 ReversePartitionBytes();
900 ReverseHeaderBytes(&mainHeader);
901 ReverseHeaderBytes(&secondHeader);
902 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400903 RecomputeCRCs();
904
srs5694ba00fed2010-01-12 18:18:36 -0500905 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500906 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
907 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500908 answer = GetYN();
909 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500910 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400911 } else {
912 allOK = 0;
913 } // if/else
914 } // if
915
916 // Do it!
917 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500918 // First, write the protective MBR...
919 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400920
srs5694546a9c72010-01-26 16:00:26 -0500921 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400922 // Now write the main GPT header...
srs5694546a9c72010-01-26 16:00:26 -0500923 if (myDisk.Seek(1) == 1) {
924 if (myDisk.Write(&mainHeader, 512) != 512)
925 allOK = 0;
926 } else allOK = 0; // if (myDisk.Seek()...)
srs5694e7b4ff92009-08-18 13:16:10 -0400927
928 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400929 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500930 offset = mainHeader.partitionEntriesLBA;
931 if (myDisk.Seek(offset)) {
932 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
933 allOK = 0;
934 } else allOK = 0; // if (myDisk.Seek()...)
srs56941e093722010-01-05 00:14:19 -0500935 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400936
937 // Now seek to near the end to write the secondary GPT....
srs5694e4ac11e2009-08-31 10:13:04 -0400938 if (allOK) {
srs56940a697312010-01-28 21:10:52 -0500939 offset = (uint64_t) secondTable;
srs5694546a9c72010-01-26 16:00:26 -0500940 if (myDisk.Seek(offset) != 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400941 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500942 cerr << "Unable to seek to end of disk! Perhaps the 'e' option on the experts' menu\n"
943 << "will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400944 } // if
945 } // if
946
947 // Now write the secondary partition tables....
srs56941e093722010-01-05 00:14:19 -0500948 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500949 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -0400950 allOK = 0;
srs56941e093722010-01-05 00:14:19 -0500951 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400952
953 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500954 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500955 offset = mainHeader.backupLBA;
956 if (myDisk.Seek(offset)) {
957 if (myDisk.Write(&secondHeader, 512) == -1)
srs56941e093722010-01-05 00:14:19 -0500958 allOK = 0;
srs5694546a9c72010-01-26 16:00:26 -0500959 } else allOK = 0; // if (myDisk.Seek()...)
srs56941e093722010-01-05 00:14:19 -0500960 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400961
962 // re-read the partition table
963 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500964 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } // if
966
967 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500968 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400969 } else {
srs5694fed16d02010-01-27 23:03:40 -0500970 cerr << "Warning! An error was reported when writing the partition table! This error\n"
971 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
972 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400973 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500974 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400975 } else {
srs5694fed16d02010-01-27 23:03:40 -0500976 cerr << "Unable to open device " << device << " for writing! Errno is "
977 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400978 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400979 } // if/else
980 } else {
srs5694fed16d02010-01-27 23:03:40 -0500981 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400982 } // if
983
srs56942a9f5da2009-08-26 00:48:01 -0400984 if (IsLittleEndian() == 0) {
985 // Reverse (normalize) header bytes first, since ReversePartitionBytes()
986 // requires non-reversed data in mainHeader...
987 ReverseHeaderBytes(&mainHeader);
988 ReverseHeaderBytes(&secondHeader);
989 ReversePartitionBytes();
990 } // if
991
srs5694e7b4ff92009-08-18 13:16:10 -0400992 return (allOK);
993} // GPTData::SaveGPTData()
994
995// Save GPT data to a backup file. This function does much less error
996// checking than SaveGPTData(). It can therefore preserve many types of
997// corruption for later analysis; however, it preserves only the MBR,
998// the main GPT header, the backup GPT header, and the main partition
999// table; it discards the backup partition table, since it should be
1000// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001001int GPTData::SaveGPTBackup(const string & filename) {
1002 int allOK = 1;
srs56942a9f5da2009-08-26 00:48:01 -04001003 uint32_t numParts;
srs5694546a9c72010-01-26 16:00:26 -05001004 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001005
srs5694546a9c72010-01-26 16:00:26 -05001006 if (backupFile.OpenForWrite(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001007 // Reverse the byte order, if necessary....
1008 numParts = mainHeader.numParts;
1009 if (IsLittleEndian() == 0) {
1010 ReversePartitionBytes();
1011 ReverseHeaderBytes(&mainHeader);
1012 ReverseHeaderBytes(&secondHeader);
1013 } // if
1014
srs5694978041c2009-09-21 20:51:47 -04001015 // Recomputing the CRCs is likely to alter them, which could be bad
1016 // if the intent is to save a potentially bad GPT for later analysis;
1017 // but if we don't do this, we get bogus errors when we load the
1018 // backup. I'm favoring misses over false alarms....
1019 RecomputeCRCs();
1020
srs56942a9f5da2009-08-26 00:48:01 -04001021 // Now write the protective MBR...
srs5694546a9c72010-01-26 16:00:26 -05001022 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001023
1024 // Now write the main GPT header...
1025 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001026 // MBR write closed disk, so re-open and seek to end....
1027 backupFile.OpenForWrite();
1028 backupFile.Seek(1);
1029 if (backupFile.Write(&mainHeader, 512) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001030 allOK = 0;
1031
1032 // Now write the secondary GPT header...
1033 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001034 if (backupFile.Write(&secondHeader, 512) == -1)
srs5694e4ac11e2009-08-31 10:13:04 -04001035 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001036
1037 // Now write the main partition tables...
1038 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001039 if (backupFile.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001040 allOK = 0;
1041 } // if
1042
1043 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001044 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001045 } else {
srs5694fed16d02010-01-27 23:03:40 -05001046 cerr << "Warning! An error was reported when writing the backup file.\n"
1047 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001048 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001049 backupFile.Close();
srs56942a9f5da2009-08-26 00:48:01 -04001050
1051 // Now reverse the byte-order reversal, if necessary....
1052 if (IsLittleEndian() == 0) {
1053 ReverseHeaderBytes(&mainHeader);
1054 ReverseHeaderBytes(&secondHeader);
1055 ReversePartitionBytes();
1056 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001057 } else {
srs5694fed16d02010-01-27 23:03:40 -05001058 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001059 allOK = 0;
1060 } // if/else
1061 return allOK;
1062} // GPTData::SaveGPTBackup()
1063
1064// Load GPT data from a backup file created by SaveGPTBackup(). This function
1065// does minimal error checking. It returns 1 if it completed successfully,
1066// 0 if there was a problem. In the latter case, it creates a new empty
1067// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001068int GPTData::LoadGPTBackup(const string & filename) {
1069 int allOK = 1, val;
srs5694e7b4ff92009-08-18 13:16:10 -04001070 uint32_t numParts, sizeOfEntries, sizeOfParts, newCRC;
srs56942a9f5da2009-08-26 00:48:01 -04001071 int littleEndian = 1;
srs5694546a9c72010-01-26 16:00:26 -05001072 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001073
srs5694546a9c72010-01-26 16:00:26 -05001074 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001075 if (IsLittleEndian() == 0)
1076 littleEndian = 0;
1077
srs5694e7b4ff92009-08-18 13:16:10 -04001078 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001079 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001080
1081 // Load the main GPT header, check its vaility, and set the GPT
1082 // size based on the data
srs5694546a9c72010-01-26 16:00:26 -05001083 if (backupFile.Read(&mainHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001084 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001085 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001086 mainCrcOk = CheckHeaderCRC(&mainHeader);
1087
srs56942a9f5da2009-08-26 00:48:01 -04001088 // Reverse byte order, if necessary
1089 if (littleEndian == 0) {
1090 ReverseHeaderBytes(&mainHeader);
1091 } // if
1092
srs5694e7b4ff92009-08-18 13:16:10 -04001093 // Load the backup GPT header in much the same way as the main
1094 // GPT header....
srs5694546a9c72010-01-26 16:00:26 -05001095 if (backupFile.Read(&secondHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001096 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001097 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001098 secondCrcOk = CheckHeaderCRC(&secondHeader);
1099
srs56942a9f5da2009-08-26 00:48:01 -04001100 // Reverse byte order, if necessary
1101 if (littleEndian == 0) {
1102 ReverseHeaderBytes(&secondHeader);
1103 } // if
1104
srs5694e7b4ff92009-08-18 13:16:10 -04001105 // Return valid headers code: 0 = both headers bad; 1 = main header
1106 // good, backup bad; 2 = backup header good, main header bad;
1107 // 3 = both headers good. Note these codes refer to valid GPT
1108 // signatures and version numbers; more subtle problems will elude
1109 // this check!
1110 if ((val = CheckHeaderValidity()) > 0) {
1111 if (val == 2) { // only backup header seems to be good
1112 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001113 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001114 } else { // main header is OK
1115 numParts = mainHeader.numParts;
1116 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1117 } // if/else
1118
1119 SetGPTSize(numParts);
1120
1121 // If current disk size doesn't match that of backup....
1122 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001123 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1124 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001125 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001126 } // if
1127
1128 // Load main partition table, and record whether its CRC
1129 // matches the stored value
1130 sizeOfParts = numParts * sizeOfEntries;
srs5694546a9c72010-01-26 16:00:26 -05001131 if (backupFile.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -05001132 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001133 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001134
1135 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
1136 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
1137 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -04001138 // Reverse byte order, if necessary
srs5694e4ac11e2009-08-31 10:13:04 -04001139 if (littleEndian == 0) {
1140 ReversePartitionBytes();
1141 } // if
srs56942a9f5da2009-08-26 00:48:01 -04001142
srs5694e7b4ff92009-08-18 13:16:10 -04001143 } else {
1144 allOK = 0;
1145 } // if/else
1146 } else {
1147 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001148 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001149 } // if/else
1150
1151 // Something went badly wrong, so blank out partitions
1152 if (allOK == 0) {
1153 ClearGPTData();
1154 protectiveMBR.MakeProtectiveMBR();
1155 } // if
1156 return allOK;
1157} // GPTData::LoadGPTBackup()
1158
srs5694e4ac11e2009-08-31 10:13:04 -04001159// Tell user whether Apple Partition Map (APM) was discovered....
1160void GPTData::ShowAPMState(void) {
1161 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001162 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001163 else
srs5694fed16d02010-01-27 23:03:40 -05001164 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001165} // GPTData::ShowAPMState()
1166
1167// Tell user about the state of the GPT data....
1168void GPTData::ShowGPTState(void) {
1169 switch (state) {
1170 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001171 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001172 break;
1173 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001174 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001175 break;
1176 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001177 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001178 break;
1179 default:
srs5694fed16d02010-01-27 23:03:40 -05001180 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001181 break;
1182 } // switch
1183} // GPTData::ShowGPTState()
1184
1185// Display the basic GPT data
1186void GPTData::DisplayGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001187 int i;
srs5694fed16d02010-01-27 23:03:40 -05001188// char tempStr[255];
srs5694e4ac11e2009-08-31 10:13:04 -04001189 uint64_t temp, totalFree;
1190
srs5694fed16d02010-01-27 23:03:40 -05001191 cout << "Disk " << device << ": " << diskSize << " sectors, "
1192 << BytesToSI(diskSize * blockSize) << "\n";
1193 cout << "Logical sector size: " << blockSize << " bytes\n";
1194 cout << "Disk identifier (GUID): " << GUIDToStr(mainHeader.diskGUID) << "\n";
1195 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1196 cout << "First usable sector is " << mainHeader.firstUsableLBA
1197 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001198 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001199 cout << "Total free space is " << totalFree << " sectors ("
1200 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1201 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001202 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001203 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001204 } // for
1205} // GPTData::DisplayGPTData()
1206
1207// Get partition number from user and then call ShowPartDetails(partNum)
1208// to show its detailed information
1209void GPTData::ShowDetails(void) {
1210 int partNum;
1211 uint32_t low, high;
1212
1213 if (GetPartRange(&low, &high) > 0) {
1214 partNum = GetPartNum();
1215 ShowPartDetails(partNum);
1216 } else {
srs5694fed16d02010-01-27 23:03:40 -05001217 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001218 } // if/else
1219} // GPTData::ShowDetails()
1220
1221// Show detailed information on the specified partition
1222void GPTData::ShowPartDetails(uint32_t partNum) {
1223 if (partitions[partNum].GetFirstLBA() != 0) {
1224 partitions[partNum].ShowDetails(blockSize);
1225 } else {
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001227 } // if
1228} // GPTData::ShowPartDetails()
1229
1230/*********************************************************************
1231 * *
1232 * Begin functions that obtain information from the users, and often *
1233 * do something with that information (call other functions) *
1234 * *
1235 *********************************************************************/
1236
1237// Prompts user for partition number and returns the result.
1238uint32_t GPTData::GetPartNum(void) {
1239 uint32_t partNum;
1240 uint32_t low, high;
1241 char prompt[255];
1242
1243 if (GetPartRange(&low, &high) > 0) {
1244 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1245 partNum = GetNumber(low + 1, high + 1, low, prompt);
1246 } else partNum = 1;
1247 return (partNum - 1);
1248} // GPTData::GetPartNum()
1249
1250// What it says: Resize the partition table. (Default is 128 entries.)
1251void GPTData::ResizePartitionTable(void) {
1252 int newSize;
1253 char prompt[255];
1254 uint32_t curLow, curHigh;
1255
srs5694fed16d02010-01-27 23:03:40 -05001256 cout << "Current partition table size is " << mainHeader.numParts << ".\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001257 GetPartRange(&curLow, &curHigh);
1258 curHigh++; // since GetPartRange() returns numbers starting from 0...
1259 // There's no point in having fewer than four partitions....
1260 if (curHigh < 4)
1261 curHigh = 4;
1262 sprintf(prompt, "Enter new size (%d up, default %d): ", (int) curHigh,
1263 (int) NUM_GPT_ENTRIES);
1264 newSize = GetNumber(4, 65535, 128, prompt);
1265 if (newSize < 128) {
srs5694fed16d02010-01-27 23:03:40 -05001266 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
1267 << "which works out to 128 entries. In practice, smaller tables seem to\n"
1268 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
1269 << "the resize, but you may want to reconsider this action and undo it.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001270 } // if
1271 SetGPTSize(newSize);
1272} // GPTData::ResizePartitionTable()
1273
1274// Interactively create a partition
1275void GPTData::CreatePartition(void) {
1276 uint64_t firstBlock, firstInLargest, lastBlock, sector;
1277 char prompt[255];
1278 int partNum, firstFreePart = 0;
1279
1280 // Find first free partition...
1281 while (partitions[firstFreePart].GetFirstLBA() != 0) {
1282 firstFreePart++;
1283 } // while
1284
1285 if (((firstBlock = FindFirstAvailable()) != 0) &&
1286 (firstFreePart < mainHeader.numParts)) {
1287 lastBlock = FindLastAvailable(firstBlock);
1288 firstInLargest = FindFirstInLargest();
1289
1290 // Get partition number....
1291 do {
1292 sprintf(prompt, "Partition number (%d-%d, default %d): ", firstFreePart + 1,
1293 mainHeader.numParts, firstFreePart + 1);
1294 partNum = GetNumber(firstFreePart + 1, mainHeader.numParts,
1295 firstFreePart + 1, prompt) - 1;
1296 if (partitions[partNum].GetFirstLBA() != 0)
srs5694fed16d02010-01-27 23:03:40 -05001297 cout << "partition " << partNum + 1 << " is in use.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001298 } while (partitions[partNum].GetFirstLBA() != 0);
1299
1300 // Get first block for new partition...
srs56945d58fe02010-01-03 20:57:08 -05001301 sprintf(prompt, "First sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1302 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1303 (unsigned long long) firstInLargest);
srs5694e4ac11e2009-08-31 10:13:04 -04001304 do {
1305 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt);
1306 } while (IsFree(sector) == 0);
srs56941d1448a2009-12-31 21:20:19 -05001307 Align(&sector); // Align sector to correct multiple
srs5694e4ac11e2009-08-31 10:13:04 -04001308 firstBlock = sector;
1309
1310 // Get last block for new partitions...
1311 lastBlock = FindLastInFree(firstBlock);
srs56945d58fe02010-01-03 20:57:08 -05001312 sprintf(prompt, "Last sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1313 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1314 (unsigned long long) lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001315 do {
1316 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, prompt);
1317 } while (IsFree(sector) == 0);
1318 lastBlock = sector;
1319
srs5694ba00fed2010-01-12 18:18:36 -05001320 firstFreePart = CreatePartition(partNum, firstBlock, lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001321 partitions[partNum].ChangeType();
srs5694fed16d02010-01-27 23:03:40 -05001322 partitions[partNum].SetName(partitions[partNum].GetNameType());
srs5694ba00fed2010-01-12 18:18:36 -05001323 } else {
srs5694fed16d02010-01-27 23:03:40 -05001324 cout << "No free sectors available\n";
srs5694ba00fed2010-01-12 18:18:36 -05001325 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001326} // GPTData::CreatePartition()
1327
1328// Interactively delete a partition (duh!)
1329void GPTData::DeletePartition(void) {
1330 int partNum;
1331 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001332 char prompt[255];
1333
1334 if (GetPartRange(&low, &high) > 0) {
1335 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1336 partNum = GetNumber(low + 1, high + 1, low, prompt);
srs5694ba00fed2010-01-12 18:18:36 -05001337 DeletePartition(partNum - 1);
srs5694e4ac11e2009-08-31 10:13:04 -04001338 } else {
srs5694fed16d02010-01-27 23:03:40 -05001339 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001340 } // if/else
1341} // GPTData::DeletePartition()
1342
1343// Prompt user for a partition number, then change its type code
1344// using ChangeGPTType(struct GPTPartition*) function.
1345void GPTData::ChangePartType(void) {
1346 int partNum;
1347 uint32_t low, high;
1348
1349 if (GetPartRange(&low, &high) > 0) {
1350 partNum = GetPartNum();
1351 partitions[partNum].ChangeType();
1352 } else {
srs5694fed16d02010-01-27 23:03:40 -05001353 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001354 } // if/else
1355} // GPTData::ChangePartType()
1356
1357// Partition attributes seem to be rarely used, but I want a way to
1358// adjust them for completeness....
1359void GPTData::SetAttributes(uint32_t partNum) {
1360 Attributes theAttr;
1361
1362 theAttr.SetAttributes(partitions[partNum].GetAttributes());
1363 theAttr.DisplayAttributes();
1364 theAttr.ChangeAttributes();
1365 partitions[partNum].SetAttributes(theAttr.GetAttributes());
1366} // GPTData::SetAttributes()
1367
srs5694c0ca8f82009-08-20 21:35:25 -04001368// This function destroys the on-disk GPT structures. Returns 1 if the
1369// user confirms destruction, 0 if the user aborts.
srs5694978041c2009-09-21 20:51:47 -04001370// If prompt == 0, don't ask user about proceeding and do NOT wipe out
1371// MBR. (Set prompt == 0 when doing a GPT-to-MBR conversion.)
srs5694ba00fed2010-01-12 18:18:36 -05001372// If prompt == -1, don't ask user about proceeding and DO wipe out
1373// MBR.
srs5694978041c2009-09-21 20:51:47 -04001374int GPTData::DestroyGPT(int prompt) {
srs56941e093722010-01-05 00:14:19 -05001375 int fd, i, sum, tableSize;
srs5694fed16d02010-01-27 23:03:40 -05001376 uint8_t blankSector[512], goOn = 'Y', blank = 'N';
1377 uint8_t* emptyTable;
srs5694c0ca8f82009-08-20 21:35:25 -04001378
1379 for (i = 0; i < 512; i++) {
srs5694fed16d02010-01-27 23:03:40 -05001380 blankSector[i] = 0;
srs5694c0ca8f82009-08-20 21:35:25 -04001381 } // for
1382
srs5694ba00fed2010-01-12 18:18:36 -05001383 if (((apmFound) || (bsdFound)) && (prompt > 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001384 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
1385 << "damage any APM or BSD partitions on this disk!\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001386 } // if APM or BSD
srs5694ba00fed2010-01-12 18:18:36 -05001387 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001388 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
srs5694978041c2009-09-21 20:51:47 -04001389 goOn = GetYN();
1390 } // if
srs5694c0ca8f82009-08-20 21:35:25 -04001391 if (goOn == 'Y') {
srs5694546a9c72010-01-26 16:00:26 -05001392 if (myDisk.OpenForWrite(device)) {
1393 myDisk.Seek(mainHeader.currentLBA); // seek to GPT header
1394 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001395 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001396 } // if
srs5694546a9c72010-01-26 16:00:26 -05001397 myDisk.Seek(mainHeader.partitionEntriesLBA); // seek to partition table
srs56941e093722010-01-05 00:14:19 -05001398 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -05001399 emptyTable = (uint8_t*) malloc(tableSize);
srs56941e093722010-01-05 00:14:19 -05001400 for (i = 0; i < tableSize; i++)
srs5694fed16d02010-01-27 23:03:40 -05001401 emptyTable[i] = 0;
srs5694546a9c72010-01-26 16:00:26 -05001402 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001403 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001404 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001405 myDisk.Seek(secondHeader.partitionEntriesLBA); // seek to partition table
1406 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001407 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001408 cerr << "Warning! GPT backup partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001409 myDisk.Seek(secondHeader.currentLBA); // seek to GPT header
1410 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001411 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001412 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001413 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001414 cout << "Blank out MBR? ";
srs5694978041c2009-09-21 20:51:47 -04001415 blank = GetYN();
srs5694ba00fed2010-01-12 18:18:36 -05001416 } // if
srs5694978041c2009-09-21 20:51:47 -04001417 // Note on below: Touch the MBR only if the user wants it completely
1418 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
1419 // the MBR, but this could wipe out a valid MBR that the program
1420 // had subsequently discarded (say, if it conflicted with older GPT
1421 // structures).
srs5694ba00fed2010-01-12 18:18:36 -05001422 if ((blank == 'Y') || (prompt < 0)) {
srs5694546a9c72010-01-26 16:00:26 -05001423 myDisk.Seek(0);
1424 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001425 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
srs56945d58fe02010-01-03 20:57:08 -05001426 } // if
srs5694978041c2009-09-21 20:51:47 -04001427 } else {
srs5694fed16d02010-01-27 23:03:40 -05001428 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
1429 << "with fdisk or another tool.\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001430 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001431 myDisk.DiskSync();
1432 myDisk.Close();
srs5694fed16d02010-01-27 23:03:40 -05001433 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1434 << "other utilities. Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001435 } else {
srs5694fed16d02010-01-27 23:03:40 -05001436 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001437 } // if/else (fd != -1)
1438 } // if (goOn == 'Y')
1439 return (goOn == 'Y');
1440} // GPTData::DestroyGPT()
1441
srs5694e4ac11e2009-08-31 10:13:04 -04001442/**************************************************************************
1443 * *
1444 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1445 * (some of these functions may require user interaction) *
1446 * *
1447 **************************************************************************/
1448
1449// Examines the MBR & GPT data, and perhaps asks the user questions, to
1450// determine which set of data to use: the MBR (use_mbr), the GPT (use_gpt),
1451// or create a new set of partitions (use_new)
1452WhichToUse GPTData::UseWhichPartitions(void) {
1453 WhichToUse which = use_new;
1454 MBRValidity mbrState;
1455 int answer;
1456
1457 mbrState = protectiveMBR.GetValidity();
1458
1459 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001460 cout << "\n***************************************************************\n"
1461 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001462 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001463 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1464 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001465 } // if
srs5694fed16d02010-01-27 23:03:40 -05001466 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001467 which = use_mbr;
1468 } // if
1469
1470 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001471 cout << "\n**********************************************************************\n"
1472 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1473 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001474 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001475 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1476 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1477 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001478 } // if
srs5694fed16d02010-01-27 23:03:40 -05001479 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001480 which = use_bsd;
1481 } // if
1482
1483 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001484 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001485 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001486 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001487 } // if
1488 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001489 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001490 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001491 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001492 } // if
1493 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001494 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001495 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001496 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001497 } // if
1498 if ((state == gpt_valid) && (mbrState == mbr)) {
srs56943c0af382010-01-15 19:19:18 -05001499 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -05001500 cout << "Found valid MBR and GPT. Which do you want to use?\n";
1501 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001502 if (answer == 1) {
1503 which = use_mbr;
1504 } else if (answer == 2) {
1505 which = use_gpt;
srs5694fed16d02010-01-27 23:03:40 -05001506 cout << "Using GPT and creating fresh protective MBR.\n";
srs56943c0af382010-01-15 19:19:18 -05001507 } else which = use_new;
1508 } else which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001509 } // if
1510
1511 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
1512 // problems)
1513 if (state == gpt_corrupt) {
srs56943c0af382010-01-15 19:19:18 -05001514 if (beQuiet) {
1515 which = use_abort;
1516 } else {
1517 if ((mbrState == mbr) || (mbrState == hybrid)) {
srs5694fed16d02010-01-27 23:03:40 -05001518 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
1519 << "GPT MAY permit recovery of GPT data.)\n";
1520 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001521 if (answer == 1) {
1522 which = use_mbr;
srs56943c0af382010-01-15 19:19:18 -05001523 } else if (answer == 2) {
1524 which = use_gpt;
1525 } else which = use_new;
1526 } else if (mbrState == invalid) {
srs5694fed16d02010-01-27 23:03:40 -05001527 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
1528 << "GPT MAY permit recovery of GPT data.)\n";
1529 answer = GetNumber(1, 2, 1, " 1 - GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001530 if (answer == 1) {
1531 which = use_gpt;
1532 } else which = use_new;
1533 } else { // corrupt GPT, MBR indicates it's a GPT disk....
srs5694fed16d02010-01-27 23:03:40 -05001534 cout << "\a\a****************************************************************************\n"
1535 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1536 << "verification and recovery are STRONGLY recommended.\n"
1537 << "****************************************************************************\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001538 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001539 } // if/else/else
1540 } // else (beQuiet)
srs5694e4ac11e2009-08-31 10:13:04 -04001541 } // if (corrupt GPT)
1542
1543 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001544 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001545
1546 return which;
1547} // UseWhichPartitions()
1548
1549// Convert MBR partition table into GPT form
1550int GPTData::XFormPartitions(void) {
1551 int i, numToConvert;
1552 uint8_t origType;
1553 struct newGUID;
srs5694e4ac11e2009-08-31 10:13:04 -04001554
1555 // Clear out old data & prepare basics....
1556 ClearGPTData();
1557
1558 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001559 if (mainHeader.numParts > (MAX_MBR_PARTS))
1560 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001561 else
1562 numToConvert = mainHeader.numParts;
1563
1564 for (i = 0; i < numToConvert; i++) {
1565 origType = protectiveMBR.GetType(i);
1566 // don't waste CPU time trying to convert extended, hybrid protective, or
1567 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001568 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs5694e4ac11e2009-08-31 10:13:04 -04001569 (origType != 0x00) && (origType != 0xEE))
1570 partitions[i] = protectiveMBR.AsGPT(i);
1571 } // for
1572
1573 // Convert MBR into protective MBR
1574 protectiveMBR.MakeProtectiveMBR();
1575
1576 // Record that all original CRCs were OK so as not to raise flags
1577 // when doing a disk verification
1578 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1579
1580 return (1);
1581} // GPTData::XFormPartitions()
1582
1583// Transforms BSD disklabel on the specified partition (numbered from 0).
1584// If an invalid partition number is given, the program prompts for one.
1585// Returns the number of new partitions created.
1586int GPTData::XFormDisklabel(int i) {
1587 uint32_t low, high, partNum, startPart;
1588 uint16_t hexCode;
1589 int goOn = 1, numDone = 0;
1590 BSDData disklabel;
1591
1592 if (GetPartRange(&low, &high) != 0) {
1593 if ((i < low) || (i > high))
1594 partNum = GetPartNum();
1595 else
1596 partNum = (uint32_t) i;
1597
1598 // Find the partition after the last used one
1599 startPart = high + 1;
1600
1601 // Now see if the specified partition has a BSD type code....
1602 hexCode = partitions[partNum].GetHexType();
1603 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
srs5694fed16d02010-01-27 23:03:40 -05001604 cout << "Specified partition doesn't have a disklabel partition type "
1605 << "code.\nContinue anyway? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001606 goOn = (GetYN() == 'Y');
1607 } // if
1608
1609 // If all is OK, read the disklabel and convert it.
1610 if (goOn) {
srs56940a697312010-01-28 21:10:52 -05001611 goOn = disklabel.ReadBSDData(device, partitions[partNum].GetFirstLBA(),
srs5694e4ac11e2009-08-31 10:13:04 -04001612 partitions[partNum].GetLastLBA());
1613 if ((goOn) && (disklabel.IsDisklabel())) {
1614 numDone = XFormDisklabel(&disklabel, startPart);
1615 if (numDone == 1)
srs5694fed16d02010-01-27 23:03:40 -05001616 cout << "Converted " << numDone << " BSD partition.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001617 else
srs5694fed16d02010-01-27 23:03:40 -05001618 cout << "Converted " << numDone << " BSD partitions.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001619 } else {
srs5694fed16d02010-01-27 23:03:40 -05001620 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001621 } // if/else
1622 } // if
1623 if (numDone > 0) { // converted partitions; delete carrier
1624 partitions[partNum].BlankPartition();
1625 } // if
1626 } else {
srs5694fed16d02010-01-27 23:03:40 -05001627 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001628 } // if/else
1629 return numDone;
1630} // GPTData::XFormDisklable(int i)
1631
1632// Transform the partitions on an already-loaded BSD disklabel...
1633int GPTData::XFormDisklabel(BSDData* disklabel, int startPart) {
1634 int i, numDone = 0;
1635
1636 if ((disklabel->IsDisklabel()) && (startPart >= 0) &&
1637 (startPart < mainHeader.numParts)) {
1638 for (i = 0; i < disklabel->GetNumParts(); i++) {
1639 partitions[i + startPart] = disklabel->AsGPT(i);
1640 if (partitions[i + startPart].GetFirstLBA() != UINT64_C(0))
1641 numDone++;
1642 } // for
1643 } // if
1644
1645 // Record that all original CRCs were OK so as not to raise flags
1646 // when doing a disk verification
1647 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1648
1649 return numDone;
1650} // GPTData::XFormDisklabel(BSDData* disklabel)
1651
srs5694978041c2009-09-21 20:51:47 -04001652// Add one GPT partition to MBR. Used by XFormToMBR() and MakeHybrid()
1653// functions. Returns 1 if operation was successful.
1654int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1655 int allOK = 1, typeCode, bootable;
1656 uint64_t length;
1657 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001658 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001659
srs5694fed16d02010-01-27 23:03:40 -05001660 cout.setf(ios::uppercase);
1661 cout.fill('0');
1662
srs5694978041c2009-09-21 20:51:47 -04001663 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001664 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001665 allOK = 0;
1666 } // if
1667 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001668 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001669 allOK = 0;
1670 } // if
1671 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001672 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001673 allOK = 0;
1674 } // if
1675 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1676 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1677 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001678 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1679 << " some OSes may\nreact strangely.\n";
srs5694978041c2009-09-21 20:51:47 -04001680 } // if partition ends past 32-bit (usually 2TiB) boundary
1681 do {
srs5694fed16d02010-01-27 23:03:40 -05001682 cout << "Enter an MBR hex code (default " << hex;
1683 cout.width(2);
1684 cout << typeHelper.GUIDToID(partitions[gptPart].GetType()) / 256 << "): ";
srs56945d58fe02010-01-03 20:57:08 -05001685 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001686 if (line[0] == '\n')
1687 typeCode = partitions[gptPart].GetHexType() / 256;
srs5694fed16d02010-01-27 23:03:40 -05001688 else
1689 sscanf(line, "%x", &typeCode);
srs5694978041c2009-09-21 20:51:47 -04001690 } while ((typeCode <= 0) || (typeCode > 255));
srs5694fed16d02010-01-27 23:03:40 -05001691 cout << "Set the bootable flag? ";
srs5694978041c2009-09-21 20:51:47 -04001692 bootable = (GetYN() == 'Y');
1693 length = partitions[gptPart].GetLengthLBA();
1694 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1695 (uint32_t) length, typeCode, bootable);
1696 } else { // partition out of range
srs5694fed16d02010-01-27 23:03:40 -05001697 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1698 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001699 allOK = 0;
1700 } // if/else
srs5694fed16d02010-01-27 23:03:40 -05001701 cout.fill(' ');
srs5694978041c2009-09-21 20:51:47 -04001702 return allOK;
1703} // GPTData::OnePartToMBR()
1704
1705// Convert the GPT to MBR form. This function is necessarily limited; it
1706// handles at most four partitions and creates layouts that ignore CHS
1707// geometries. Returns the number of converted partitions; if this value
1708// is over 0, the calling function should call DestroyGPT() to destroy
1709// the GPT data, and then exit.
1710int GPTData::XFormToMBR(void) {
1711 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001712 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001713 int i, j, numParts, numConverted = 0;
1714 uint32_t partNums[4];
1715
1716 // Get the numbers of up to four partitions to add to the
1717 // hybrid MBR....
1718 numParts = CountParts();
srs5694fed16d02010-01-27 23:03:40 -05001719 cout << "Counted " << numParts << " partitions.\n";
srs5694978041c2009-09-21 20:51:47 -04001720
1721 // Prepare the MBR for conversion (empty it of existing partitions).
1722 protectiveMBR.EmptyMBR(0);
1723 protectiveMBR.SetDiskSize(diskSize);
1724
1725 if (numParts > 4) { // Over four partitions; engage in triage
srs5694fed16d02010-01-27 23:03:40 -05001726 cout << "Type from one to four GPT partition numbers, separated by spaces, to be\n"
1727 << "used in the MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001728 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001729 numParts = sscanf(line, "%d %d %d %d", &partNums[0], &partNums[1],
1730 &partNums[2], &partNums[3]);
1731 } else { // Four or fewer partitions; convert them all
1732 i = j = 0;
1733 while ((j < numParts) && (i < mainHeader.numParts)) {
1734 if (partitions[i].GetFirstLBA() > 0) { // if GPT part. is defined
1735 partNums[j++] = ++i; // flag it for conversion
1736 } else i++;
1737 } // while
1738 } // if/else
1739
1740 for (i = 0; i < numParts; i++) {
1741 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001742 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001743 numConverted += OnePartToMBR(j, i);
1744 } // for
srs5694fed16d02010-01-27 23:03:40 -05001745 cout << "MBR writing returned " << protectiveMBR.WriteMBRData(&myDisk) << "\n";
srs5694978041c2009-09-21 20:51:47 -04001746 return numConverted;
1747} // GPTData::XFormToMBR()
1748
srs5694e4ac11e2009-08-31 10:13:04 -04001749// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
1750// OSes that don't understand GPT.
1751void GPTData::MakeHybrid(void) {
1752 uint32_t partNums[3];
1753 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001754 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001755 int numParts, numConverted = 0, i, j, typeCode, mbrNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001756 char fillItUp = 'M'; // fill extra partition entries? (Yes/No/Maybe)
srs5694978041c2009-09-21 20:51:47 -04001757 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
srs5694e4ac11e2009-08-31 10:13:04 -04001758
srs5694fed16d02010-01-27 23:03:40 -05001759 cout << "\nWARNING! Hybrid MBRs are flaky and potentially dangerous! If you decide not\n"
1760 << "to use one, just hit the Enter key at the below prompt and your MBR\n"
1761 << "partition table will be untouched.\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -04001762
1763 // Now get the numbers of up to three partitions to add to the
1764 // hybrid MBR....
srs5694fed16d02010-01-27 23:03:40 -05001765 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
1766 << "added to the hybrid MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001767 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001768 numParts = sscanf(line, "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
1769
1770 if (numParts > 0) {
1771 // Blank out the protective MBR, but leave the boot loader code
1772 // alone....
1773 protectiveMBR.EmptyMBR(0);
1774 protectiveMBR.SetDiskSize(diskSize);
srs5694fed16d02010-01-27 23:03:40 -05001775 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001776 eeFirst = GetYN();
1777 } // if
1778
1779 for (i = 0; i < numParts; i++) {
1780 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001781 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001782 if (eeFirst == 'Y')
1783 mbrNum = i + 1;
1784 else
1785 mbrNum = i;
1786 numConverted += OnePartToMBR(j, mbrNum);
srs5694e4ac11e2009-08-31 10:13:04 -04001787 } // for
1788
srs5694978041c2009-09-21 20:51:47 -04001789 if ((numParts > 0) && (numConverted > 0)) { // User opted to create a hybrid MBR....
srs5694e4ac11e2009-08-31 10:13:04 -04001790 // Create EFI protective partition that covers the start of the disk.
1791 // If this location (covering the main GPT data structures) is omitted,
1792 // Linux won't find any partitions on the disk. Note that this is
1793 // NUMBERED AFTER the hybrid partitions, contrary to what the
1794 // gptsync utility does. This is because Windows seems to choke on
1795 // disks with a 0xEE partition in the first slot and subsequent
1796 // additional partitions, unless it boots from the disk.
1797 if (eeFirst == 'Y')
1798 mbrNum = 0;
1799 else
1800 mbrNum = numParts;
1801 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), 0xEE);
srs5694978041c2009-09-21 20:51:47 -04001802 protectiveMBR.SetHybrid();
srs5694e4ac11e2009-08-31 10:13:04 -04001803
1804 // ... and for good measure, if there are any partition spaces left,
1805 // optionally create another protective EFI partition to cover as much
1806 // space as possible....
1807 for (i = 0; i < 4; i++) {
1808 if (protectiveMBR.GetType(i) == 0x00) { // unused entry....
1809 if (fillItUp == 'M') {
srs5694fed16d02010-01-27 23:03:40 -05001810 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001811 fillItUp = GetYN();
1812 typeCode = 0x00; // use this to flag a need to get type code
1813 } // if
1814 if (fillItUp == 'Y') {
1815 while ((typeCode <= 0) || (typeCode > 255)) {
srs5694fed16d02010-01-27 23:03:40 -05001816 cout << "Enter an MBR hex code (EE is EFI GPT, but may confuse MacOS): ";
srs5694e4ac11e2009-08-31 10:13:04 -04001817 // Comment on above: Mac OS treats disks with more than one
1818 // 0xEE MBR partition as MBR disks, not as GPT disks.
srs56945d58fe02010-01-03 20:57:08 -05001819 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001820 sscanf(line, "%x", &typeCode);
1821 if (line[0] == '\n')
1822 typeCode = 0;
1823 } // while
1824 protectiveMBR.MakeBiggestPart(i, typeCode); // make a partition
1825 } // if (fillItUp == 'Y')
1826 } // if unused entry
1827 } // for (i = 0; i < 4; i++)
1828 } // if (numParts > 0)
1829} // GPTData::MakeHybrid()
1830
1831/**********************************************************************
1832 * *
1833 * Functions that adjust GPT data structures WITHOUT user interaction *
1834 * (they may display information for the user's benefit, though) *
1835 * *
1836 **********************************************************************/
1837
1838// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001839// necessary, copies data if it already exists. Returns 1 if all goes
1840// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001841int GPTData::SetGPTSize(uint32_t numEntries) {
1842 struct GPTPart* newParts;
1843 struct GPTPart* trash;
1844 uint32_t i, high, copyNum;
1845 int allOK = 1;
1846
1847 // First, adjust numEntries upward, if necessary, to get a number
1848 // that fills the allocated sectors
1849 i = blockSize / GPT_SIZE;
1850 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001851 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001852 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001853 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001854 } // if
1855
srs5694247657a2009-11-26 18:36:12 -05001856 // Do the work only if the # of partitions is changing. Along with being
1857 // efficient, this prevents mucking the with location of the secondary
1858 // partition table, which causes problems when loading data from a RAID
1859 // array that's been expanded because this function is called when loading
1860 // data.
srs5694546a9c72010-01-26 16:00:26 -05001861 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1862 || (partitions == NULL)) {
srs5694247657a2009-11-26 18:36:12 -05001863 newParts = (GPTPart*) calloc(numEntries, sizeof (GPTPart));
1864 if (newParts != NULL) {
1865 if (partitions != NULL) { // existing partitions; copy them over
1866 GetPartRange(&i, &high);
1867 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001868 cout << "The highest-numbered partition is " << high + 1
1869 << ", which is greater than the requested\n"
1870 << "partition table size of " << numEntries
1871 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001872 allOK = 0;
1873 } else { // go ahead with copy
1874 if (numEntries < mainHeader.numParts)
1875 copyNum = numEntries;
1876 else
1877 copyNum = mainHeader.numParts;
1878 for (i = 0; i < copyNum; i++) {
1879 newParts[i] = partitions[i];
1880 } // for
1881 trash = partitions;
1882 partitions = newParts;
1883 free(trash);
1884 } // if
1885 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001886 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001887 } // if/else existing partitions
1888 mainHeader.numParts = numEntries;
1889 secondHeader.numParts = numEntries;
1890 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1891 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1892 MoveSecondHeaderToEnd();
1893 if (diskSize > 0)
1894 CheckGPTSize();
1895 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001896 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001897 allOK = 0;
1898 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001899 } // if/else
1900 return (allOK);
1901} // GPTData::SetGPTSize()
1902
1903// Blank the partition array
1904void GPTData::BlankPartitions(void) {
1905 uint32_t i;
1906
1907 for (i = 0; i < mainHeader.numParts; i++) {
1908 partitions[i].BlankPartition();
1909 } // for
1910} // GPTData::BlankPartitions()
1911
srs5694ba00fed2010-01-12 18:18:36 -05001912// Delete a partition by number. Returns 1 if successful,
1913// 0 if there was a problem. Returns 1 if partition was in
1914// range, 0 if it was out of range.
1915int GPTData::DeletePartition(uint32_t partNum) {
1916 uint64_t startSector, length;
1917 uint32_t low, high, numParts, retval = 1;;
1918
1919 numParts = GetPartRange(&low, &high);
1920 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1921 // In case there's a protective MBR, look for & delete matching
1922 // MBR partition....
1923 startSector = partitions[partNum].GetFirstLBA();
1924 length = partitions[partNum].GetLengthLBA();
1925 protectiveMBR.DeleteByLocation(startSector, length);
1926
1927 // Now delete the GPT partition
1928 partitions[partNum].BlankPartition();
1929 } else {
srs5694fed16d02010-01-27 23:03:40 -05001930 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001931 retval = 0;
1932 } // if/else
1933 return retval;
1934} // GPTData::DeletePartition(uint32_t partNum)
1935
1936// Non-interactively create a partition. Note that this function is overloaded
1937// with another of the same name but different parameters; that one prompts
1938// the user for data. This one returns 1 if the operation was successful, 0
1939// if a problem was discovered.
1940int GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
1941 int retval = 1; // assume there'll be no problems
1942
1943 if (IsFreePartNum(partNum)) {
1944 Align(&startSector); // Align sector to correct multiple
1945 if (IsFree(startSector) && (startSector <= endSector)) {
1946 if (FindLastInFree(startSector) >= endSector) {
1947 partitions[partNum].SetFirstLBA(startSector);
1948 partitions[partNum].SetLastLBA(endSector);
1949 partitions[partNum].SetType(0x0700);
1950 partitions[partNum].SetUniqueGUID(1);
1951 } else retval = 0; // if free space until endSector
1952 } else retval = 0; // if startSector is free
1953 } else retval = 0; // if legal partition number
1954 return retval;
1955} // GPTData::CreatePartition(partNum, startSector, endSector)
1956
srs5694e4ac11e2009-08-31 10:13:04 -04001957// Sort the GPT entries, eliminating gaps and making for a logical
1958// ordering. Relies on QuickSortGPT() for the bulk of the work
1959void GPTData::SortGPT(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001960 GPTPart temp;
srs5694546a9c72010-01-26 16:00:26 -05001961 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001962
1963 // First, find the last partition with data, so as not to
1964 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001965 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001966
1967 // Now swap empties with the last partitions, to simplify the logic
1968 // in the Quicksort function....
1969 i = 0;
1970 while (i < lastPart) {
1971 if (partitions[i].GetFirstLBA() == 0) {
1972 temp = partitions[i];
1973 partitions[i] = partitions[lastPart];
1974 partitions[lastPart] = temp;
srs5694546a9c72010-01-26 16:00:26 -05001975 do {
1976 lastPart--;
1977 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001978 } // if
1979 i++;
1980 } // while
1981
srs5694546a9c72010-01-26 16:00:26 -05001982 // If there are more empties than partitions in the range from 0 to lastPart,
1983 // the above leaves lastPart set too high, so we've got to adjust it to
1984 // prevent empties from migrating to the top of the list....
1985 GetPartRange(&firstPart, &lastPart);
1986
srs5694e4ac11e2009-08-31 10:13:04 -04001987 // Now call the recursive quick sort routine to do the real work....
1988 QuickSortGPT(partitions, 0, lastPart);
1989} // GPTData::SortGPT()
1990
1991// Set up data structures for entirely new set of partitions on the
1992// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001993// Note that this function does NOT clear the protectiveMBR data
1994// structure, since it may hold the original MBR partitions if the
1995// program was launched on an MBR disk, and those may need to be
1996// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001997int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001998 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001999
2000 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05002001 if (partitions != NULL)
2002 free(partitions);
srs5694e4ac11e2009-08-31 10:13:04 -04002003 partitions = NULL;
2004 SetGPTSize(NUM_GPT_ENTRIES);
2005
2006 // Now initialize a bunch of stuff that's static....
2007 mainHeader.signature = GPT_SIGNATURE;
2008 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04002009 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04002010 mainHeader.reserved = 0;
2011 mainHeader.currentLBA = UINT64_C(1);
2012 mainHeader.partitionEntriesLBA = (uint64_t) 2;
2013 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
2014 for (i = 0; i < GPT_RESERVED; i++) {
2015 mainHeader.reserved2[i] = '\0';
2016 } // for
2017
2018 // Now some semi-static items (computed based on end of disk)
2019 mainHeader.backupLBA = diskSize - UINT64_C(1);
2020 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2021
2022 // Set a unique GUID for the disk, based on random numbers
2023 // rand() is only 32 bits, so multiply together to fill a 64-bit value
2024 mainHeader.diskGUID.data1 = (uint64_t) rand() * (uint64_t) rand();
2025 mainHeader.diskGUID.data2 = (uint64_t) rand() * (uint64_t) rand();
2026
2027 // Copy main header to backup header
2028 RebuildSecondHeader();
2029
2030 // Blank out the partitions array....
2031 BlankPartitions();
2032
2033 // Flag all CRCs as being OK....
2034 mainCrcOk = 1;
2035 secondCrcOk = 1;
2036 mainPartsCrcOk = 1;
2037 secondPartsCrcOk = 1;
2038
2039 return (goOn);
2040} // GPTData::ClearGPTData()
2041
srs5694247657a2009-11-26 18:36:12 -05002042// Set the location of the second GPT header data to the end of the disk.
2043// Used internally and called by the 'e' option on the recovery &
2044// transformation menu, to help users of RAID arrays who add disk space
2045// to their arrays.
2046void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05002047 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2048 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2049 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2050} // GPTData::FixSecondHeaderLocation()
2051
srs56940a697312010-01-28 21:10:52 -05002052int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05002053 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05002054
2055 if (!IsFreePartNum(partNum)) {
2056 partitions[partNum].SetName(theName);
2057 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05002058
2059 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04002060} // GPTData::SetName
2061
2062// Set the disk GUID to the specified value. Note that the header CRCs must
2063// be recomputed after calling this function.
2064void GPTData::SetDiskGUID(GUIDData newGUID) {
2065 mainHeader.diskGUID = newGUID;
2066 secondHeader.diskGUID = newGUID;
2067} // SetDiskGUID()
2068
2069// Set the unique GUID of the specified partition. Returns 1 on
2070// successful completion, 0 if there were problems (invalid
2071// partition number).
2072int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2073 int retval = 0;
2074
2075 if (pn < mainHeader.numParts) {
2076 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
2077 partitions[pn].SetUniqueGUID(theGUID);
2078 retval = 1;
2079 } // if
2080 } // if
2081 return retval;
2082} // GPTData::SetPartitionGUID()
2083
srs5694ba00fed2010-01-12 18:18:36 -05002084// Change partition type code non-interactively. Returns 1 if
2085// successful, 0 if not....
2086int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
2087 int retval = 1;
2088
2089 if (!IsFreePartNum(partNum)) {
2090 partitions[partNum].SetType(hexCode);
2091 } else retval = 0;
2092 return retval;
2093} // GPTData::ChangePartType()
2094
srs56941d1448a2009-12-31 21:20:19 -05002095// Adjust sector number so that it falls on a sector boundary that's a
2096// multiple of sectorAlignment. This is done to improve the performance
2097// of Western Digital Advanced Format disks and disks with similar
2098// technology from other companies, which use 4096-byte sectors
2099// internally although they translate to 512-byte sectors for the
2100// benefit of the OS. If partitions aren't properly aligned on these
2101// disks, some filesystem data structures can span multiple physical
2102// sectors, degrading performance. This function should be called
2103// only on the FIRST sector of the partition, not the last!
2104// This function returns 1 if the alignment was altered, 0 if it
2105// was unchanged.
2106int GPTData::Align(uint64_t* sector) {
2107 int retval = 0, sectorOK = 0;
2108 uint64_t earlier, later, testSector, original;
2109
2110 if ((*sector % sectorAlignment) != 0) {
2111 original = *sector;
2112 retval = 1;
2113 earlier = (*sector / sectorAlignment) * sectorAlignment;
2114 later = earlier + (uint64_t) sectorAlignment;
2115
2116 // Check to see that every sector between the earlier one and the
2117 // requested one is clear, and that it's not too early....
2118 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05002119 sectorOK = 1;
2120 testSector = earlier;
2121 do {
2122 sectorOK = IsFree(testSector++);
2123 } while ((sectorOK == 1) && (testSector < *sector));
2124 if (sectorOK == 1) {
2125 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05002126 } // if
2127 } // if firstUsableLBA check
2128
2129 // If couldn't move the sector earlier, try to move it later instead....
2130 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2131 sectorOK = 1;
2132 testSector = later;
2133 do {
2134 sectorOK = IsFree(testSector--);
2135 } while ((sectorOK == 1) && (testSector > *sector));
2136 if (sectorOK == 1) {
2137 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05002138 } // if
2139 } // if
2140
2141 // If sector was changed successfully, inform the user of this fact.
2142 // Otherwise, notify the user that it couldn't be done....
2143 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05002144 cout << "Information: Moved requested sector from " << original << " to "
2145 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05002146 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05002147 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05002148 } else {
srs5694fed16d02010-01-27 23:03:40 -05002149 cout << "Information: Sector not aligned on " << sectorAlignment
2150 << "-sector boundary and could not be moved.\n"
2151 << "If you're using a Western Digital Advanced Format or similar disk with\n"
2152 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05002153 retval = 0;
2154 } // if/else
2155 } // if
2156 return retval;
2157} // GPTData::Align()
2158
srs5694e4ac11e2009-08-31 10:13:04 -04002159/********************************************************
2160 * *
2161 * Functions that return data about GPT data structures *
2162 * (most of these are inline in gpt.h) *
2163 * *
2164 ********************************************************/
2165
2166// Find the low and high used partition numbers (numbered from 0).
2167// Return value is the number of partitions found. Note that the
2168// *low and *high values are both set to 0 when no partitions
2169// are found, as well as when a single partition in the first
2170// position exists. Thus, the return value is the only way to
2171// tell when no partitions exist.
2172int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2173 uint32_t i;
2174 int numFound = 0;
2175
2176 *low = mainHeader.numParts + 1; // code for "not found"
2177 *high = 0;
2178 if (mainHeader.numParts > 0) { // only try if partition table exists...
2179 for (i = 0; i < mainHeader.numParts; i++) {
2180 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
2181 *high = i; // since we're counting up, set the high value
2182 // Set the low value only if it's not yet found...
2183 if (*low == (mainHeader.numParts + 1)) *low = i;
2184 numFound++;
2185 } // if
2186 } // for
2187 } // if
2188
2189 // Above will leave *low pointing to its "not found" value if no partitions
2190 // are defined, so reset to 0 if this is the case....
2191 if (*low == (mainHeader.numParts + 1))
2192 *low = 0;
2193 return numFound;
2194} // GPTData::GetPartRange()
2195
srs5694978041c2009-09-21 20:51:47 -04002196// Returns the number of defined partitions.
2197uint32_t GPTData::CountParts(void) {
2198 int i, counted = 0;
2199
2200 for (i = 0; i < mainHeader.numParts; i++) {
2201 if (partitions[i].GetFirstLBA() > 0)
2202 counted++;
2203 } // for
2204 return counted;
2205} // GPTData::CountParts()
2206
srs5694e4ac11e2009-08-31 10:13:04 -04002207/****************************************************
2208 * *
2209 * Functions that return data about disk free space *
2210 * *
2211 ****************************************************/
2212
2213// Find the first available block after the starting point; returns 0 if
2214// there are no available blocks left
2215uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2216 uint64_t first;
2217 uint32_t i;
2218 int firstMoved = 0;
2219
2220 // Begin from the specified starting point or from the first usable
2221 // LBA, whichever is greater...
2222 if (start < mainHeader.firstUsableLBA)
2223 first = mainHeader.firstUsableLBA;
2224 else
2225 first = start;
2226
2227 // ...now search through all partitions; if first is within an
2228 // existing partition, move it to the next sector after that
2229 // partition and repeat. If first was moved, set firstMoved
2230 // flag; repeat until firstMoved is not set, so as to catch
2231 // cases where partitions are out of sequential order....
2232 do {
2233 firstMoved = 0;
2234 for (i = 0; i < mainHeader.numParts; i++) {
2235 if ((first >= partitions[i].GetFirstLBA()) &&
2236 (first <= partitions[i].GetLastLBA())) { // in existing part.
2237 first = partitions[i].GetLastLBA() + 1;
2238 firstMoved = 1;
2239 } // if
2240 } // for
2241 } while (firstMoved == 1);
2242 if (first > mainHeader.lastUsableLBA)
2243 first = 0;
2244 return (first);
2245} // GPTData::FindFirstAvailable()
2246
2247// Finds the first available sector in the largest block of unallocated
2248// space on the disk. Returns 0 if there are no available blocks left
2249uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002250 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002251
2252 start = 0;
2253 do {
2254 firstBlock = FindFirstAvailable(start);
2255 if (firstBlock != UINT32_C(0)) { // something's free...
2256 lastBlock = FindLastInFree(firstBlock);
2257 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2258 if (segmentSize > selectedSize) {
2259 selectedSize = segmentSize;
2260 selectedSegment = firstBlock;
2261 } // if
2262 start = lastBlock + 1;
2263 } // if
2264 } while (firstBlock != 0);
2265 return selectedSegment;
2266} // GPTData::FindFirstInLargest()
2267
2268// Find the last available block on the disk at or after the start
2269// block. Returns 0 if there are no available partitions after
2270// (or including) start.
2271uint64_t GPTData::FindLastAvailable(uint64_t start) {
2272 uint64_t last;
2273 uint32_t i;
2274 int lastMoved = 0;
2275
2276 // Start by assuming the last usable LBA is available....
2277 last = mainHeader.lastUsableLBA;
2278
2279 // ...now, similar to algorithm in FindFirstAvailable(), search
2280 // through all partitions, moving last when it's in an existing
2281 // partition. Set the lastMoved flag so we repeat to catch cases
2282 // where partitions are out of logical order.
2283 do {
2284 lastMoved = 0;
2285 for (i = 0; i < mainHeader.numParts; i++) {
2286 if ((last >= partitions[i].GetFirstLBA()) &&
2287 (last <= partitions[i].GetLastLBA())) { // in existing part.
2288 last = partitions[i].GetFirstLBA() - 1;
2289 lastMoved = 1;
2290 } // if
2291 } // for
2292 } while (lastMoved == 1);
2293 if (last < mainHeader.firstUsableLBA)
2294 last = 0;
2295 return (last);
2296} // GPTData::FindLastAvailable()
2297
2298// Find the last available block in the free space pointed to by start.
2299uint64_t GPTData::FindLastInFree(uint64_t start) {
2300 uint64_t nearestStart;
2301 uint32_t i;
2302
2303 nearestStart = mainHeader.lastUsableLBA;
2304 for (i = 0; i < mainHeader.numParts; i++) {
2305 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2306 (partitions[i].GetFirstLBA() > start)) {
2307 nearestStart = partitions[i].GetFirstLBA() - 1;
2308 } // if
2309 } // for
2310 return (nearestStart);
2311} // GPTData::FindLastInFree()
2312
2313// Finds the total number of free blocks, the number of segments in which
2314// they reside, and the size of the largest of those segments
2315uint64_t GPTData::FindFreeBlocks(int *numSegments, uint64_t *largestSegment) {
2316 uint64_t start = UINT64_C(0); // starting point for each search
2317 uint64_t totalFound = UINT64_C(0); // running total
2318 uint64_t firstBlock; // first block in a segment
2319 uint64_t lastBlock; // last block in a segment
2320 uint64_t segmentSize; // size of segment in blocks
2321 int num = 0;
2322
2323 *largestSegment = UINT64_C(0);
2324 do {
2325 firstBlock = FindFirstAvailable(start);
2326 if (firstBlock != UINT64_C(0)) { // something's free...
2327 lastBlock = FindLastInFree(firstBlock);
2328 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2329 if (segmentSize > *largestSegment) {
2330 *largestSegment = segmentSize;
2331 } // if
2332 totalFound += segmentSize;
2333 num++;
2334 start = lastBlock + 1;
2335 } // if
2336 } while (firstBlock != 0);
2337 *numSegments = num;
2338 return totalFound;
2339} // GPTData::FindFreeBlocks()
2340
2341// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2342int GPTData::IsFree(uint64_t sector) {
2343 int isFree = 1;
2344 uint32_t i;
2345
2346 for (i = 0; i < mainHeader.numParts; i++) {
2347 if ((sector >= partitions[i].GetFirstLBA()) &&
2348 (sector <= partitions[i].GetLastLBA())) {
2349 isFree = 0;
2350 } // if
2351 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002352 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002353 (sector > mainHeader.lastUsableLBA)) {
2354 isFree = 0;
2355 } // if
2356 return (isFree);
2357} // GPTData::IsFree()
2358
srs5694ba00fed2010-01-12 18:18:36 -05002359// Returns 1 if partNum is unused.
2360int GPTData::IsFreePartNum(uint32_t partNum) {
2361 int retval = 1;
2362
2363 if ((partNum >= 0) && (partNum < mainHeader.numParts)) {
2364 if ((partitions[partNum].GetFirstLBA() != UINT64_C(0)) ||
2365 (partitions[partNum].GetLastLBA() != UINT64_C(0))) {
2366 retval = 0;
2367 } // if partition is in use
2368 } else retval = 0;
2369
2370 return retval;
2371} // GPTData::IsFreePartNum()
2372
srs5694e4ac11e2009-08-31 10:13:04 -04002373/********************************
2374 * *
2375 * Endianness support functions *
2376 * *
2377 ********************************/
2378
srs56942a9f5da2009-08-26 00:48:01 -04002379void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002380 ReverseBytes(&header->signature, 8);
2381 ReverseBytes(&header->revision, 4);
2382 ReverseBytes(&header->headerSize, 4);
2383 ReverseBytes(&header->headerCRC, 4);
2384 ReverseBytes(&header->reserved, 4);
2385 ReverseBytes(&header->currentLBA, 8);
2386 ReverseBytes(&header->backupLBA, 8);
2387 ReverseBytes(&header->firstUsableLBA, 8);
2388 ReverseBytes(&header->lastUsableLBA, 8);
2389 ReverseBytes(&header->partitionEntriesLBA, 8);
2390 ReverseBytes(&header->numParts, 4);
2391 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2392 ReverseBytes(&header->partitionEntriesCRC, 4);
2393 ReverseBytes(&header->reserved2, GPT_RESERVED);
2394 ReverseBytes(&header->diskGUID.data1, 8);
2395 ReverseBytes(&header->diskGUID.data2, 8);
srs56942a9f5da2009-08-26 00:48:01 -04002396} // GPTData::ReverseHeaderBytes()
2397
2398// IMPORTANT NOTE: This function requires non-reversed mainHeader
2399// structure!
2400void GPTData::ReversePartitionBytes() {
2401 uint32_t i;
2402
2403 // Check GPT signature on big-endian systems; this will mismatch
2404 // if the function is called out of order. Unfortunately, it'll also
2405 // mismatch if there's data corruption.
2406 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002407 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2408 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002409 } // if signature mismatch....
2410 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002411 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002412 } // for
2413} // GPTData::ReversePartitionBytes()
2414
2415/******************************************
2416 * *
2417 * Additional non-class support functions *
2418 * *
2419 ******************************************/
2420
srs5694e7b4ff92009-08-18 13:16:10 -04002421// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2422// never fail these tests, but the struct types may fail depending on compile options.
2423// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2424// sizes.
2425int SizesOK(void) {
2426 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002427
2428 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002429 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002430 allOK = 0;
2431 } // if
2432 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002433 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002434 allOK = 0;
2435 } // if
2436 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002437 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002438 allOK = 0;
2439 } // if
2440 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002441 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002442 allOK = 0;
2443 } // if
2444 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002445 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002446 allOK = 0;
2447 } // if
srs5694978041c2009-09-21 20:51:47 -04002448 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002449 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002450 allOK = 0;
2451 } // if
2452 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002453 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002454 allOK = 0;
2455 } // if
srs5694221e0872009-08-29 15:00:31 -04002456 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002457 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002458 allOK = 0;
2459 } // if
srs5694fed16d02010-01-27 23:03:40 -05002460 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002461 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002462 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2463 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002464 } // if
2465 return (allOK);
2466} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002467