blob: a2e216f5efa6fdabc2426e2adf763a57a8f43ee7 [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) {
srs5694cb76c672010-02-11 22:22:22 -050085 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040086} // 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) {
srs5694e321d442010-01-29 17:44:04 -050099 int problems = 0;
100 uint32_t i, numSegments;
101 uint64_t totalFree, largestSegment;
102 char siTotal[255], siLargest[255];
srs5694e4ac11e2009-08-31 10:13:04 -0400103
104 // First, check for CRC errors in the GPT data....
105 if (!mainCrcOk) {
106 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500107 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
108 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
109 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
110 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400111 } // if
112 if (!mainPartsCrcOk) {
113 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500114 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
115 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
116 << "transformation menu). This report may be a false alarm if you've already\n"
117 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400118 } // if
119 if (!secondCrcOk) {
120 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500121 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
122 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
123 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
124 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400125 } // if
126 if (!secondPartsCrcOk) {
127 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500128 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
129 << "be corrupt. This program will automatically create a new backup partition\n"
130 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400131 } // if
132
srs5694978041c2009-09-21 20:51:47 -0400133 // Now check that the main and backup headers both point to themselves....
134 if (mainHeader.currentLBA != 1) {
135 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500136 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
137 << "is being automatically corrected, but it may be a symptom of more serious\n"
138 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400139 mainHeader.currentLBA = 1;
140 } // if
141 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
142 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500143 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
144 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
145 << "option on the experts' menu to adjust the secondary header's and partition\n"
146 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400147 } // if
148
149 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400150 if (mainHeader.currentLBA != secondHeader.backupLBA) {
151 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500152 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
153 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
154 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400155 } // if
156 if (mainHeader.backupLBA != secondHeader.currentLBA) {
157 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500158 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
159 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
160 << secondHeader.currentLBA << ").\n"
161 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
166 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
167 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400168 } // if
169 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
170 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500171 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
172 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
173 << secondHeader.lastUsableLBA << ")\n"
174 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400175 } // if
srs56946699b012010-02-04 00:55:30 -0500176 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400177 problems++;
srs56946699b012010-02-04 00:55:30 -0500178 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500179 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500180 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500181 << "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...
srs5694cb76c672010-02-11 22:22:22 -0500345// Note: Must be called with header in LITTLE-ENDIAN
346// (x86, x86-64, etc.) byte order.
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
srs56946699b012010-02-04 00:55:30 -0500370// Recompute all the CRCs. Must be called before saving if any changes have
371// been made. Must be called on platform-ordered data (this function reverses
372// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400373void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400374 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400375 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400376
377 // Initialize CRC functions...
378 chksum_crc32gentab();
379
srs56946699b012010-02-04 00:55:30 -0500380 // Save some key data from header before reversing byte order....
381 trueNumParts = mainHeader.numParts;
srs5694978041c2009-09-21 20:51:47 -0400382 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500383
384 if ((littleEndian = IsLittleEndian()) == 0) {
385 ReversePartitionBytes();
386 ReverseHeaderBytes(&mainHeader);
387 ReverseHeaderBytes(&secondHeader);
388 } // if
389/* if ((littleEndian = IsLittleEndian()) == 0) {
390 ReverseBytes(&trueNumParts, 4);
391 ReverseBytes(&hSize, 4);
392 } // if */
srs56942a9f5da2009-08-26 00:48:01 -0400393
srs5694e7b4ff92009-08-18 13:16:10 -0400394 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400395 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400396 mainHeader.partitionEntriesCRC = crc;
397 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400398 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400399 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
400 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400401 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400402
403 // Zero out GPT tables' own CRCs (required for correct computation)
404 mainHeader.headerCRC = 0;
405 secondHeader.headerCRC = 0;
406
407 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400408 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400409 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400410 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400411 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400412 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400413 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400414 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400415 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500416
417 if ((littleEndian = IsLittleEndian()) == 0) {
418 ReverseHeaderBytes(&mainHeader);
419 ReverseHeaderBytes(&secondHeader);
420 ReversePartitionBytes();
421 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400422} // GPTData::RecomputeCRCs()
423
srs5694e7b4ff92009-08-18 13:16:10 -0400424// Rebuild the main GPT header, using the secondary header as a model.
425// Typically called when the main header has been found to be corrupt.
426void GPTData::RebuildMainHeader(void) {
427 int i;
428
429 mainHeader.signature = GPT_SIGNATURE;
430 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400431 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400432 mainHeader.headerCRC = UINT32_C(0);
433 mainHeader.reserved = secondHeader.reserved;
434 mainHeader.currentLBA = secondHeader.backupLBA;
435 mainHeader.backupLBA = secondHeader.currentLBA;
436 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
437 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500438 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400439 mainHeader.partitionEntriesLBA = UINT64_C(2);
440 mainHeader.numParts = secondHeader.numParts;
441 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
442 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
443 for (i = 0 ; i < GPT_RESERVED; i++)
444 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500445 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400446} // GPTData::RebuildMainHeader()
447
448// Rebuild the secondary GPT header, using the main header as a model.
449void GPTData::RebuildSecondHeader(void) {
450 int i;
451
452 secondHeader.signature = GPT_SIGNATURE;
453 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400454 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400455 secondHeader.headerCRC = UINT32_C(0);
456 secondHeader.reserved = mainHeader.reserved;
457 secondHeader.currentLBA = mainHeader.backupLBA;
458 secondHeader.backupLBA = mainHeader.currentLBA;
459 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
460 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500461 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400462 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
463 secondHeader.numParts = mainHeader.numParts;
464 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
465 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
466 for (i = 0 ; i < GPT_RESERVED; i++)
467 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500468 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400469} // GPTData::RebuildSecondHeader()
470
471// Search for hybrid MBR entries that have no corresponding GPT partition.
472// Returns number of such mismatches found
473int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500474 int i, found, numFound = 0;
475 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400476 uint64_t mbrFirst, mbrLast;
477
478 for (i = 0; i < 4; i++) {
479 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
480 j = 0;
481 found = 0;
482 do {
483 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
484 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
485 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
486 (partitions[j].GetLastLBA() == mbrLast))
487 found = 1;
488 j++;
489 } while ((!found) && (j < mainHeader.numParts));
490 if (!found) {
491 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500492 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
493 << i + 1 << ", of type 0x";
494 cout.fill('0');
495 cout.setf(ios::uppercase);
496 cout.width(2);
497 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
498 << "has no corresponding GPT partition! You may continue, but this condition\n"
499 << "might cause data loss in the future!\a\n" << dec;
500 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400501 } // if
502 } // if
503 } // for
504 return numFound;
505} // GPTData::FindHybridMismatches
506
507// Find overlapping partitions and warn user about them. Returns number of
508// overlapping partitions.
509int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500510 int problems = 0;
511 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400512
513 for (i = 1; i < mainHeader.numParts; i++) {
514 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500515 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400516 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500517 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
518 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
519 << " to " << partitions[i].GetLastLBA() << "\n";
520 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
521 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400522 } // if
523 } // for j...
524 } // for i...
525 return problems;
526} // GPTData::FindOverlaps()
527
528/******************************************************************
529 * *
530 * Begin functions that load data from disk or save data to disk. *
531 * *
532 ******************************************************************/
533
534// Scan for partition data. This function loads the MBR data (regular MBR or
535// protective MBR) and loads BSD disklabel data (which is probably invalid).
536// It also looks for APM data, forces a load of GPT data, and summarizes
537// the results.
srs5694546a9c72010-01-26 16:00:26 -0500538void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400539 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400540
541 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500542 protectiveMBR.ReadMBRData(&myDisk);
543 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400544
545 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500546 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500547
548 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500549 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500550 protectiveMBR.ShowState();
551 bsdDisklabel.ShowState();
552 ShowAPMState(); // Show whether there's an Apple Partition Map present
553 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500554 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500555 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400556
557 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500558 cout << "\n*******************************************************************\n"
559 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500560 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500561 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500562 } // if
srs5694fed16d02010-01-27 23:03:40 -0500563 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400564 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400565} // GPTData::PartitionScan()
566
567// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500568int GPTData::LoadPartitions(const string & deviceFilename) {
srs5694e321d442010-01-29 17:44:04 -0500569 int err, allOK = 1;
570 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -0400571 uint64_t firstBlock, lastBlock;
572 BSDData bsdDisklabel;
srs5694fed16d02010-01-27 23:03:40 -0500573 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400574
575 // First, do a test to see if writing will be possible later....
srs5694fed16d02010-01-27 23:03:40 -0500576 err = myDisk.OpenForWrite(deviceFilename);
577 if ((err == 0) && (!justLooking)) {
578 cout << "\aNOTE: Write test failed with error number " << errno
579 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
srs56947dbb9322010-01-20 16:56:30 -0500580#ifdef __FreeBSD__
srs5694fed16d02010-01-27 23:03:40 -0500581 cout << "You may be able to enable writes by exiting this program, typing\n"
582 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
583 << "program.\n";
srs56947dbb9322010-01-20 16:56:30 -0500584#endif
srs5694fed16d02010-01-27 23:03:40 -0500585 cout << "\n";
srs56945d58fe02010-01-03 20:57:08 -0500586 } // if
srs5694546a9c72010-01-26 16:00:26 -0500587 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400588
srs5694546a9c72010-01-26 16:00:26 -0500589 if (myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400590 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500591 diskSize = myDisk.DiskSize(&err);
592 blockSize = (uint32_t) myDisk.GetBlockSize();
593 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500594 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500595 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400596
srs5694ba00fed2010-01-12 18:18:36 -0500597 whichWasUsed = UseWhichPartitions();
598 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400599 case use_mbr:
600 XFormPartitions();
601 break;
602 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500603 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400604// bsdDisklabel.DisplayBSDData();
605 ClearGPTData();
606 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
607 XFormDisklabel(&bsdDisklabel, 0);
608 break;
609 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500610 mbrState = protectiveMBR.GetValidity();
611 if ((mbrState == invalid) || (mbrState == mbr))
612 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400613 break;
614 case use_new:
615 ClearGPTData();
616 protectiveMBR.MakeProtectiveMBR();
617 break;
srs56943c0af382010-01-15 19:19:18 -0500618 case use_abort:
619 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500620 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500621 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400622 } // switch
623
624 // Now find the first and last sectors used by partitions...
625 if (allOK) {
626 firstBlock = mainHeader.backupLBA; // start high
627 lastBlock = 0; // start low
628 for (i = 0; i < mainHeader.numParts; i++) {
629 if ((partitions[i].GetFirstLBA() < firstBlock) &&
630 (partitions[i].GetFirstLBA() > 0))
631 firstBlock = partitions[i].GetFirstLBA();
632 if (partitions[i].GetLastLBA() > lastBlock)
633 lastBlock = partitions[i].GetLastLBA();
634 } // for
srs56943c0af382010-01-15 19:19:18 -0500635 CheckGPTSize();
srs5694e4ac11e2009-08-31 10:13:04 -0400636 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400637 } else {
638 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500639 cerr << "Problem opening " << deviceFilename << " for reading! Error is "
640 << errno << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400641 if (errno == EACCES) { // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -0500642 cerr << "You must run this program as root or use sudo!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400643 } // if
644 } // if/else
645 return (allOK);
646} // GPTData::LoadPartitions()
647
648// Loads the GPT, as much as possible. Returns 1 if this seems to have
649// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500650int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500651 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400652
srs5694cb76c672010-02-11 22:22:22 -0500653 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400654
srs5694cb76c672010-02-11 22:22:22 -0500655 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
656 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
657 } else {
658 if (mainHeader.backupLBA >= diskSize)
srs5694fed16d02010-01-27 23:03:40 -0500659 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
660 << "secondary header from the last sector of the disk! You should use 'v' to\n"
661 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
662 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500663 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
664 } // if/else
665 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400666 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400667
668 // Return valid headers code: 0 = both headers bad; 1 = main header
669 // good, backup bad; 2 = backup header good, main header bad;
670 // 3 = both headers good. Note these codes refer to valid GPT
671 // signatures and version numbers; more subtle problems will elude
672 // this check!
673 validHeaders = CheckHeaderValidity();
674
675 // Read partitions (from primary array)
676 if (validHeaders > 0) { // if at least one header is OK....
677 // GPT appears to be valid....
678 state = gpt_valid;
679
680 // We're calling the GPT valid, but there's a possibility that one
681 // of the two headers is corrupt. If so, use the one that seems to
682 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500683 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500684 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
685 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400686 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500687 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400688 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500689 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500690 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
691 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500692 RebuildMainHeader();
693 state = gpt_corrupt;
694 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400695 } // if/else/if
696
srs5694546a9c72010-01-26 16:00:26 -0500697 // Figure out which partition table to load....
698 // Load the main partition table, since either its header's CRC is OK or the
699 // backup header's CRC is not OK....
700 if (mainCrcOk || !secondCrcOk) {
701 if (LoadMainTable() == 0)
702 allOK = 0;
703 } else { // bad main header CRC and backup header CRC is OK
704 state = gpt_corrupt;
705 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500706 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500707 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500708 } else { // backup table bad, bad main header CRC, but try main table in desperation....
709 if (LoadMainTable() == 0) {
710 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500711 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500712 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500713 } // if
714 } // if/else (LoadSecondTableAsMain())
715 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400716
srs5694cb76c672010-02-11 22:22:22 -0500717 if (loadedTable == 1)
718 secondPartsCrcOk = CheckTable(&secondHeader);
719 else if (loadedTable == 2)
720 mainPartsCrcOk = CheckTable(&mainHeader);
721 else
722 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400723
srs5694546a9c72010-01-26 16:00:26 -0500724 // Problem with main partition table; if backup is OK, use it instead....
725 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
726 state = gpt_corrupt;
727 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500728 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500729 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
730 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500731 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500732
srs5694e4ac11e2009-08-31 10:13:04 -0400733 // Check for valid CRCs and warn if there are problems
734 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
735 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500736 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400737 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500738 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400739 } else {
740 state = gpt_invalid;
741 } // if/else
742 return allOK;
743} // GPTData::ForceLoadGPTData()
744
srs5694247657a2009-11-26 18:36:12 -0500745// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400746// main GPT header in memory MUST be valid for this call to do anything
747// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500748// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400749int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500750 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400751} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400752
753// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500754// table. Used in repair functions, and when starting up if the main
755// partition table is damaged.
756// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
757int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500758 return LoadPartitionTable(secondHeader, myDisk);
759} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400760
srs5694cb76c672010-02-11 22:22:22 -0500761// Load a single GPT header (main or backup) from the specified disk device and
762// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
763// value appropriately.
764// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
765// failure.
766int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
767 int allOK = 1;
768
769 disk.Seek(sector);
770 if (disk.Read(header, 512) != 512) {
771 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
772 allOK = 0;
773 } // if
774 *crcOk = CheckHeaderCRC(header);
775
776 // Reverse byte order, if necessary
777 if (IsLittleEndian() == 0) {
778 ReverseHeaderBytes(header);
779 } // if
780 return allOK;
781} // GPTData::LoadHeader
782
783// Load a partition table (either main or secondary) from the specified disk,
784// using header as a reference for what to load. If sector != 0 (the default
785// is 0), loads from the specified sector; otherwise loads from the sector
786// indicated in header.
787// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
788int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
789 uint32_t sizeOfParts, newCRC;
790 int retval;
791
792 if (disk.OpenForRead()) {
793 if (sector == 0) {
794 retval = disk.Seek(header.partitionEntriesLBA);
795 } else {
796 retval = disk.Seek(sector);
797 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500798 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500799 SetGPTSize(header.numParts);
800 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
801 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500802 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500803 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500804 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400805 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500806 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400807 if (IsLittleEndian() == 0)
808 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500809 if (!mainPartsCrcOk) {
810 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400811 } // if
812 } else {
srs5694cb76c672010-02-11 22:22:22 -0500813 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400814 } // if/else
815 } else {
srs5694fed16d02010-01-27 23:03:40 -0500816 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500817 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500818 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400819 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500820 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500821} // GPTData::LoadPartitionsTable()
822
823// Check the partition table pointed to by header, but don't keep it
824// around.
825// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
826int GPTData::CheckTable(struct GPTHeader *header) {
827 uint32_t sizeOfParts, newCRC;
828 uint8_t *storage;
829 int newCrcOk = 0;
830
831 // Load backup partition table into temporary storage to check
832 // its CRC and store the results, then discard this temporary
833 // storage, since we don't use it in any but recovery operations
834 if (myDisk.Seek(header->partitionEntriesLBA)) {
835 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
836 storage = new uint8_t[sizeOfParts];
837 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
838 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
839 } else {
840 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
841 newCrcOk = (newCRC == header->partitionEntriesCRC);
842 } // if/else
843 delete[] storage;
844 } // if
845 return newCrcOk;
846} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400847
srs5694e7b4ff92009-08-18 13:16:10 -0400848// Writes GPT (and protective MBR) to disk. Returns 1 on successful
849// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500850int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500851 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500852 char answer;
srs5694cb76c672010-02-11 22:22:22 -0500853// uint64_t secondTable;
srs56942a9f5da2009-08-26 00:48:01 -0400854 uint32_t numParts;
srs5694e7b4ff92009-08-18 13:16:10 -0400855
srs56946699b012010-02-04 00:55:30 -0500856 littleEndian = IsLittleEndian();
857
srs5694fed16d02010-01-27 23:03:40 -0500858 if (device == "") {
859 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400860 } // if
861
862 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500863
864 // This test should only fail on read-only disks....
865 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500866 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500867 allOK = 0;
868 } // if
869
srs5694e7b4ff92009-08-18 13:16:10 -0400870 // Is there enough space to hold the GPT headers and partition tables,
871 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400872 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400873 allOK = 0;
874 } // if
875
876 // Check that disk is really big enough to handle this...
877 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500878 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
879 << "problem (or it might not). Aborting!\n(Disk size is "
880 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400881 allOK = 0;
882 } // if
srs5694247657a2009-11-26 18:36:12 -0500883 // Check that second header is properly placed. Warn and ask if this should
884 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500885 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500886 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
887 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500888 if (GetYN() == 'Y') {
889 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500890 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500891 } else {
srs5694fed16d02010-01-27 23:03:40 -0500892 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500893 } // if correction requested
894 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400895
896 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400897 if (FindOverlaps() > 0) {
898 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500899 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400900 } // if
901
902 // Check for mismatched MBR and GPT data, but let it pass if found
903 // (function displays warning message)
904 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400905
srs56942a9f5da2009-08-26 00:48:01 -0400906 // Pull out some data that's needed before doing byte-order reversal on
907 // big-endian systems....
908 numParts = mainHeader.numParts;
srs5694cb76c672010-02-11 22:22:22 -0500909
srs5694e7b4ff92009-08-18 13:16:10 -0400910 RecomputeCRCs();
911
srs5694ba00fed2010-01-12 18:18:36 -0500912 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500913 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
914 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500915 answer = GetYN();
916 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500917 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400918 } else {
919 allOK = 0;
920 } // if/else
921 } // if
922
923 // Do it!
924 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500925 // First, write the protective MBR...
926 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400927
srs5694546a9c72010-01-26 16:00:26 -0500928 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400929 // Now write the main GPT header...
srs5694cb76c672010-02-11 22:22:22 -0500930 allOK = SaveHeader(&mainHeader, myDisk, 1);
srs5694e7b4ff92009-08-18 13:16:10 -0400931
932 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400933 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500934 allOK = SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
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....
srs5694cb76c672010-02-11 22:22:22 -0500938 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
939 if (!allOK)
940 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
941 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400942
943 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500944 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500945 allOK = SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
srs56946699b012010-02-04 00:55:30 -0500946 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400947
948 // re-read the partition table
949 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500950 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400951 } // if
952
953 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500954 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400955 } else {
srs5694fed16d02010-01-27 23:03:40 -0500956 cerr << "Warning! An error was reported when writing the partition table! This error\n"
957 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
958 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400959 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500960 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400961 } else {
srs5694fed16d02010-01-27 23:03:40 -0500962 cerr << "Unable to open device " << device << " for writing! Errno is "
963 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400964 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } // if/else
966 } else {
srs5694fed16d02010-01-27 23:03:40 -0500967 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400968 } // if
969
970 return (allOK);
971} // GPTData::SaveGPTData()
972
973// Save GPT data to a backup file. This function does much less error
974// checking than SaveGPTData(). It can therefore preserve many types of
975// corruption for later analysis; however, it preserves only the MBR,
976// the main GPT header, the backup GPT header, and the main partition
977// table; it discards the backup partition table, since it should be
978// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500979int GPTData::SaveGPTBackup(const string & filename) {
980 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500981 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400982
srs5694546a9c72010-01-26 16:00:26 -0500983 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500984 // Recomputing the CRCs is likely to alter them, which could be bad
985 // if the intent is to save a potentially bad GPT for later analysis;
986 // but if we don't do this, we get bogus errors when we load the
987 // backup. I'm favoring misses over false alarms....
988 RecomputeCRCs();
989
srs5694546a9c72010-01-26 16:00:26 -0500990 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400991
srs5694cb76c672010-02-11 22:22:22 -0500992 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500993 // MBR write closed disk, so re-open and seek to end....
994 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500995 allOK = SaveHeader(&mainHeader, backupFile, 1);
996 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400997
srs5694e7b4ff92009-08-18 13:16:10 -0400998 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -0500999 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001000
srs5694cb76c672010-02-11 22:22:22 -05001001 if (allOK)
1002 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001003
1004 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001005 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001006 } else {
srs5694fed16d02010-01-27 23:03:40 -05001007 cerr << "Warning! An error was reported when writing the backup file.\n"
1008 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001009 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001010 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001011 } else {
srs5694fed16d02010-01-27 23:03:40 -05001012 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001013 allOK = 0;
1014 } // if/else
1015 return allOK;
1016} // GPTData::SaveGPTBackup()
1017
srs5694cb76c672010-02-11 22:22:22 -05001018// Write a GPT header (main or backup) to the specified sector. Used by both
1019// the SaveGPTData() and SaveGPTBackup() functions.
1020// Should be passed an architecture-appropriate header (DO NOT call
1021// ReverseHeaderBytes() on the header before calling this function)
1022// Returns 1 on success, 0 on failure
1023int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1024 int littleEndian, allOK = 1;
1025
1026 littleEndian = IsLittleEndian();
1027 if (!littleEndian)
1028 ReverseHeaderBytes(header);
1029 if (disk.Seek(sector)) {
1030 if (disk.Write(header, 512) == -1)
1031 allOK = 0;
1032 } else allOK = 0; // if (disk.Seek()...)
1033 if (!littleEndian)
1034 ReverseHeaderBytes(header);
1035 return allOK;
1036} // GPTData::SaveHeader()
1037
1038// Save the partitions to the specified sector. Used by both the SaveGPTData()
1039// and SaveGPTBackup() functions.
1040// Should be passed an architecture-appropriate header (DO NOT call
1041// ReverseHeaderBytes() on the header before calling this function)
1042// Returns 1 on success, 0 on failure
1043int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1044 int littleEndian, allOK = 1;
1045
1046 littleEndian = IsLittleEndian();
1047 if (disk.Seek(sector)) {
1048 if (!littleEndian)
1049 ReversePartitionBytes();
1050 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1051 allOK = 0;
1052 if (!littleEndian)
1053 ReversePartitionBytes();
1054 } else allOK = 0; // if (myDisk.Seek()...)
1055 return allOK;
1056} // GPTData::SavePartitionTable()
1057
srs5694e7b4ff92009-08-18 13:16:10 -04001058// Load GPT data from a backup file created by SaveGPTBackup(). This function
1059// does minimal error checking. It returns 1 if it completed successfully,
1060// 0 if there was a problem. In the latter case, it creates a new empty
1061// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001062int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001063 int allOK = 1, val, err;
1064 uint32_t numParts, sizeOfEntries;
1065 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001066 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001067
srs5694546a9c72010-01-26 16:00:26 -05001068 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001069 if (IsLittleEndian() == 0)
1070 littleEndian = 0;
1071
srs5694e7b4ff92009-08-18 13:16:10 -04001072 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001073 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001074
srs5694cb76c672010-02-11 22:22:22 -05001075 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001076
srs5694cb76c672010-02-11 22:22:22 -05001077 // Check backup file size and rebuild second header if file is right
1078 // size to be direct dd copy of MBR, main header, and main partition
1079 // table; if other size, treat it like a GPT fdisk-generated backup
1080 // file
1081 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1082 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1083 if (shortBackup) {
1084 RebuildSecondHeader();
1085 secondCrcOk = mainCrcOk;
1086 } else {
1087 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1088 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001089
srs5694e7b4ff92009-08-18 13:16:10 -04001090 // Return valid headers code: 0 = both headers bad; 1 = main header
1091 // good, backup bad; 2 = backup header good, main header bad;
1092 // 3 = both headers good. Note these codes refer to valid GPT
1093 // signatures and version numbers; more subtle problems will elude
1094 // this check!
1095 if ((val = CheckHeaderValidity()) > 0) {
1096 if (val == 2) { // only backup header seems to be good
1097 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001098 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001099 } else { // main header is OK
1100 numParts = mainHeader.numParts;
1101 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1102 } // if/else
1103
1104 SetGPTSize(numParts);
1105
srs5694e7b4ff92009-08-18 13:16:10 -04001106 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001107 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1108 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001109 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001110 } // if
1111
srs5694cb76c672010-02-11 22:22:22 -05001112 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1113 cerr << "Warning! Read error " << errno
1114 << " loading partition table; strange behavior now likely!\n";
srs56942a9f5da2009-08-26 00:48:01 -04001115
srs5694e7b4ff92009-08-18 13:16:10 -04001116 } else {
1117 allOK = 0;
1118 } // if/else
1119 } else {
1120 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001121 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001122 } // if/else
1123
1124 // Something went badly wrong, so blank out partitions
1125 if (allOK == 0) {
1126 ClearGPTData();
1127 protectiveMBR.MakeProtectiveMBR();
1128 } // if
1129 return allOK;
1130} // GPTData::LoadGPTBackup()
1131
srs5694e4ac11e2009-08-31 10:13:04 -04001132// Tell user whether Apple Partition Map (APM) was discovered....
1133void GPTData::ShowAPMState(void) {
1134 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001135 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001136 else
srs5694fed16d02010-01-27 23:03:40 -05001137 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001138} // GPTData::ShowAPMState()
1139
1140// Tell user about the state of the GPT data....
1141void GPTData::ShowGPTState(void) {
1142 switch (state) {
1143 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001144 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001145 break;
1146 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001147 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001148 break;
1149 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001150 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001151 break;
1152 default:
srs5694fed16d02010-01-27 23:03:40 -05001153 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001154 break;
1155 } // switch
1156} // GPTData::ShowGPTState()
1157
1158// Display the basic GPT data
1159void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001160 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001161 uint64_t temp, totalFree;
1162
srs5694fed16d02010-01-27 23:03:40 -05001163 cout << "Disk " << device << ": " << diskSize << " sectors, "
1164 << BytesToSI(diskSize * blockSize) << "\n";
1165 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001166 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001167 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1168 cout << "First usable sector is " << mainHeader.firstUsableLBA
1169 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001170 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001171 cout << "Total free space is " << totalFree << " sectors ("
1172 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1173 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001174 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001175 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001176 } // for
1177} // GPTData::DisplayGPTData()
1178
1179// Get partition number from user and then call ShowPartDetails(partNum)
1180// to show its detailed information
1181void GPTData::ShowDetails(void) {
1182 int partNum;
1183 uint32_t low, high;
1184
1185 if (GetPartRange(&low, &high) > 0) {
1186 partNum = GetPartNum();
1187 ShowPartDetails(partNum);
1188 } else {
srs5694fed16d02010-01-27 23:03:40 -05001189 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001190 } // if/else
1191} // GPTData::ShowDetails()
1192
1193// Show detailed information on the specified partition
1194void GPTData::ShowPartDetails(uint32_t partNum) {
1195 if (partitions[partNum].GetFirstLBA() != 0) {
1196 partitions[partNum].ShowDetails(blockSize);
1197 } else {
srs5694fed16d02010-01-27 23:03:40 -05001198 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001199 } // if
1200} // GPTData::ShowPartDetails()
1201
1202/*********************************************************************
1203 * *
1204 * Begin functions that obtain information from the users, and often *
1205 * do something with that information (call other functions) *
1206 * *
1207 *********************************************************************/
1208
1209// Prompts user for partition number and returns the result.
1210uint32_t GPTData::GetPartNum(void) {
1211 uint32_t partNum;
1212 uint32_t low, high;
1213 char prompt[255];
1214
1215 if (GetPartRange(&low, &high) > 0) {
1216 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1217 partNum = GetNumber(low + 1, high + 1, low, prompt);
1218 } else partNum = 1;
1219 return (partNum - 1);
1220} // GPTData::GetPartNum()
1221
1222// What it says: Resize the partition table. (Default is 128 entries.)
1223void GPTData::ResizePartitionTable(void) {
1224 int newSize;
1225 char prompt[255];
1226 uint32_t curLow, curHigh;
1227
srs5694fed16d02010-01-27 23:03:40 -05001228 cout << "Current partition table size is " << mainHeader.numParts << ".\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001229 GetPartRange(&curLow, &curHigh);
1230 curHigh++; // since GetPartRange() returns numbers starting from 0...
1231 // There's no point in having fewer than four partitions....
1232 if (curHigh < 4)
1233 curHigh = 4;
1234 sprintf(prompt, "Enter new size (%d up, default %d): ", (int) curHigh,
1235 (int) NUM_GPT_ENTRIES);
1236 newSize = GetNumber(4, 65535, 128, prompt);
1237 if (newSize < 128) {
srs5694fed16d02010-01-27 23:03:40 -05001238 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
1239 << "which works out to 128 entries. In practice, smaller tables seem to\n"
1240 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
1241 << "the resize, but you may want to reconsider this action and undo it.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001242 } // if
1243 SetGPTSize(newSize);
1244} // GPTData::ResizePartitionTable()
1245
1246// Interactively create a partition
1247void GPTData::CreatePartition(void) {
1248 uint64_t firstBlock, firstInLargest, lastBlock, sector;
srs5694e321d442010-01-29 17:44:04 -05001249 uint32_t firstFreePart = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001250 char prompt[255];
srs5694e321d442010-01-29 17:44:04 -05001251 int partNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001252
1253 // Find first free partition...
1254 while (partitions[firstFreePart].GetFirstLBA() != 0) {
1255 firstFreePart++;
1256 } // while
1257
1258 if (((firstBlock = FindFirstAvailable()) != 0) &&
1259 (firstFreePart < mainHeader.numParts)) {
srs5694cb76c672010-02-11 22:22:22 -05001260 lastBlock = FindLastAvailable();
srs5694e4ac11e2009-08-31 10:13:04 -04001261 firstInLargest = FindFirstInLargest();
1262
1263 // Get partition number....
1264 do {
1265 sprintf(prompt, "Partition number (%d-%d, default %d): ", firstFreePart + 1,
1266 mainHeader.numParts, firstFreePart + 1);
1267 partNum = GetNumber(firstFreePart + 1, mainHeader.numParts,
1268 firstFreePart + 1, prompt) - 1;
1269 if (partitions[partNum].GetFirstLBA() != 0)
srs5694fed16d02010-01-27 23:03:40 -05001270 cout << "partition " << partNum + 1 << " is in use.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001271 } while (partitions[partNum].GetFirstLBA() != 0);
1272
1273 // Get first block for new partition...
srs56945d58fe02010-01-03 20:57:08 -05001274 sprintf(prompt, "First sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1275 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1276 (unsigned long long) firstInLargest);
srs5694e4ac11e2009-08-31 10:13:04 -04001277 do {
1278 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt);
1279 } while (IsFree(sector) == 0);
srs56941d1448a2009-12-31 21:20:19 -05001280 Align(&sector); // Align sector to correct multiple
srs5694e4ac11e2009-08-31 10:13:04 -04001281 firstBlock = sector;
1282
1283 // Get last block for new partitions...
1284 lastBlock = FindLastInFree(firstBlock);
srs56945d58fe02010-01-03 20:57:08 -05001285 sprintf(prompt, "Last sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1286 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1287 (unsigned long long) lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001288 do {
1289 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, prompt);
1290 } while (IsFree(sector) == 0);
1291 lastBlock = sector;
1292
srs5694ba00fed2010-01-12 18:18:36 -05001293 firstFreePart = CreatePartition(partNum, firstBlock, lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001294 partitions[partNum].ChangeType();
srs56946699b012010-02-04 00:55:30 -05001295 partitions[partNum].SetDefaultDescription();
srs5694ba00fed2010-01-12 18:18:36 -05001296 } else {
srs5694fed16d02010-01-27 23:03:40 -05001297 cout << "No free sectors available\n";
srs5694ba00fed2010-01-12 18:18:36 -05001298 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001299} // GPTData::CreatePartition()
1300
1301// Interactively delete a partition (duh!)
1302void GPTData::DeletePartition(void) {
1303 int partNum;
1304 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001305 char prompt[255];
1306
1307 if (GetPartRange(&low, &high) > 0) {
1308 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1309 partNum = GetNumber(low + 1, high + 1, low, prompt);
srs5694ba00fed2010-01-12 18:18:36 -05001310 DeletePartition(partNum - 1);
srs5694e4ac11e2009-08-31 10:13:04 -04001311 } else {
srs5694fed16d02010-01-27 23:03:40 -05001312 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001313 } // if/else
1314} // GPTData::DeletePartition()
1315
1316// Prompt user for a partition number, then change its type code
1317// using ChangeGPTType(struct GPTPartition*) function.
1318void GPTData::ChangePartType(void) {
1319 int partNum;
1320 uint32_t low, high;
1321
1322 if (GetPartRange(&low, &high) > 0) {
1323 partNum = GetPartNum();
1324 partitions[partNum].ChangeType();
1325 } else {
srs5694fed16d02010-01-27 23:03:40 -05001326 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001327 } // if/else
1328} // GPTData::ChangePartType()
1329
1330// Partition attributes seem to be rarely used, but I want a way to
1331// adjust them for completeness....
1332void GPTData::SetAttributes(uint32_t partNum) {
1333 Attributes theAttr;
1334
1335 theAttr.SetAttributes(partitions[partNum].GetAttributes());
1336 theAttr.DisplayAttributes();
1337 theAttr.ChangeAttributes();
1338 partitions[partNum].SetAttributes(theAttr.GetAttributes());
1339} // GPTData::SetAttributes()
1340
srs5694c0ca8f82009-08-20 21:35:25 -04001341// This function destroys the on-disk GPT structures. Returns 1 if the
1342// user confirms destruction, 0 if the user aborts.
srs5694978041c2009-09-21 20:51:47 -04001343// If prompt == 0, don't ask user about proceeding and do NOT wipe out
1344// MBR. (Set prompt == 0 when doing a GPT-to-MBR conversion.)
srs5694ba00fed2010-01-12 18:18:36 -05001345// If prompt == -1, don't ask user about proceeding and DO wipe out
1346// MBR.
srs5694978041c2009-09-21 20:51:47 -04001347int GPTData::DestroyGPT(int prompt) {
srs5694e321d442010-01-29 17:44:04 -05001348 int i, sum, tableSize;
srs5694fed16d02010-01-27 23:03:40 -05001349 uint8_t blankSector[512], goOn = 'Y', blank = 'N';
1350 uint8_t* emptyTable;
srs5694c0ca8f82009-08-20 21:35:25 -04001351
1352 for (i = 0; i < 512; i++) {
srs5694fed16d02010-01-27 23:03:40 -05001353 blankSector[i] = 0;
srs5694c0ca8f82009-08-20 21:35:25 -04001354 } // for
1355
srs5694ba00fed2010-01-12 18:18:36 -05001356 if (((apmFound) || (bsdFound)) && (prompt > 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001357 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
1358 << "damage any APM or BSD partitions on this disk!\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001359 } // if APM or BSD
srs5694ba00fed2010-01-12 18:18:36 -05001360 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001361 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
srs5694978041c2009-09-21 20:51:47 -04001362 goOn = GetYN();
1363 } // if
srs5694c0ca8f82009-08-20 21:35:25 -04001364 if (goOn == 'Y') {
srs5694546a9c72010-01-26 16:00:26 -05001365 if (myDisk.OpenForWrite(device)) {
1366 myDisk.Seek(mainHeader.currentLBA); // seek to GPT header
1367 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001368 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001369 } // if
srs5694546a9c72010-01-26 16:00:26 -05001370 myDisk.Seek(mainHeader.partitionEntriesLBA); // seek to partition table
srs56941e093722010-01-05 00:14:19 -05001371 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -05001372 emptyTable = new uint8_t[tableSize];
srs56941e093722010-01-05 00:14:19 -05001373 for (i = 0; i < tableSize; i++)
srs5694fed16d02010-01-27 23:03:40 -05001374 emptyTable[i] = 0;
srs5694546a9c72010-01-26 16:00:26 -05001375 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001376 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001377 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001378 myDisk.Seek(secondHeader.partitionEntriesLBA); // seek to partition table
1379 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001380 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001381 cerr << "Warning! GPT backup partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001382 myDisk.Seek(secondHeader.currentLBA); // seek to GPT header
1383 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001384 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001385 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001386 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001387 cout << "Blank out MBR? ";
srs5694978041c2009-09-21 20:51:47 -04001388 blank = GetYN();
srs5694ba00fed2010-01-12 18:18:36 -05001389 } // if
srs5694978041c2009-09-21 20:51:47 -04001390 // Note on below: Touch the MBR only if the user wants it completely
1391 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
1392 // the MBR, but this could wipe out a valid MBR that the program
1393 // had subsequently discarded (say, if it conflicted with older GPT
1394 // structures).
srs5694ba00fed2010-01-12 18:18:36 -05001395 if ((blank == 'Y') || (prompt < 0)) {
srs5694546a9c72010-01-26 16:00:26 -05001396 myDisk.Seek(0);
1397 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001398 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
srs56945d58fe02010-01-03 20:57:08 -05001399 } // if
srs5694978041c2009-09-21 20:51:47 -04001400 } else {
srs5694fed16d02010-01-27 23:03:40 -05001401 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
1402 << "with fdisk or another tool.\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001403 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001404 myDisk.DiskSync();
1405 myDisk.Close();
srs5694fed16d02010-01-27 23:03:40 -05001406 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1407 << "other utilities. Program will now terminate.\n";
srs5694cb76c672010-02-11 22:22:22 -05001408 delete[] emptyTable;
srs5694c0ca8f82009-08-20 21:35:25 -04001409 } else {
srs5694fed16d02010-01-27 23:03:40 -05001410 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001411 } // if/else (fd != -1)
1412 } // if (goOn == 'Y')
1413 return (goOn == 'Y');
1414} // GPTData::DestroyGPT()
1415
srs5694e4ac11e2009-08-31 10:13:04 -04001416/**************************************************************************
1417 * *
1418 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1419 * (some of these functions may require user interaction) *
1420 * *
1421 **************************************************************************/
1422
1423// Examines the MBR & GPT data, and perhaps asks the user questions, to
1424// determine which set of data to use: the MBR (use_mbr), the GPT (use_gpt),
1425// or create a new set of partitions (use_new)
1426WhichToUse GPTData::UseWhichPartitions(void) {
1427 WhichToUse which = use_new;
1428 MBRValidity mbrState;
1429 int answer;
1430
1431 mbrState = protectiveMBR.GetValidity();
1432
1433 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001434 cout << "\n***************************************************************\n"
1435 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001436 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001437 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1438 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001439 } // if
srs5694fed16d02010-01-27 23:03:40 -05001440 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001441 which = use_mbr;
1442 } // if
1443
1444 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001445 cout << "\n**********************************************************************\n"
1446 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1447 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001448 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001449 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1450 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1451 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001452 } // if
srs5694fed16d02010-01-27 23:03:40 -05001453 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001454 which = use_bsd;
1455 } // if
1456
1457 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001458 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001459 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001460 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001461 } // if
1462 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001463 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001464 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001465 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001466 } // if
1467 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001468 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001469 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001470 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001471 } // if
1472 if ((state == gpt_valid) && (mbrState == mbr)) {
srs56943c0af382010-01-15 19:19:18 -05001473 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -05001474 cout << "Found valid MBR and GPT. Which do you want to use?\n";
1475 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001476 if (answer == 1) {
1477 which = use_mbr;
1478 } else if (answer == 2) {
1479 which = use_gpt;
srs5694fed16d02010-01-27 23:03:40 -05001480 cout << "Using GPT and creating fresh protective MBR.\n";
srs56943c0af382010-01-15 19:19:18 -05001481 } else which = use_new;
1482 } else which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001483 } // if
1484
1485 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
1486 // problems)
1487 if (state == gpt_corrupt) {
srs56943c0af382010-01-15 19:19:18 -05001488 if (beQuiet) {
1489 which = use_abort;
1490 } else {
1491 if ((mbrState == mbr) || (mbrState == hybrid)) {
srs5694fed16d02010-01-27 23:03:40 -05001492 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
1493 << "GPT MAY permit recovery of GPT data.)\n";
1494 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001495 if (answer == 1) {
1496 which = use_mbr;
srs56943c0af382010-01-15 19:19:18 -05001497 } else if (answer == 2) {
1498 which = use_gpt;
1499 } else which = use_new;
1500 } else if (mbrState == invalid) {
srs5694fed16d02010-01-27 23:03:40 -05001501 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
1502 << "GPT MAY permit recovery of GPT data.)\n";
1503 answer = GetNumber(1, 2, 1, " 1 - GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001504 if (answer == 1) {
1505 which = use_gpt;
1506 } else which = use_new;
1507 } else { // corrupt GPT, MBR indicates it's a GPT disk....
srs5694fed16d02010-01-27 23:03:40 -05001508 cout << "\a\a****************************************************************************\n"
1509 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1510 << "verification and recovery are STRONGLY recommended.\n"
1511 << "****************************************************************************\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001512 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001513 } // if/else/else
1514 } // else (beQuiet)
srs5694e4ac11e2009-08-31 10:13:04 -04001515 } // if (corrupt GPT)
1516
1517 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001518 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001519
1520 return which;
1521} // UseWhichPartitions()
1522
1523// Convert MBR partition table into GPT form
1524int GPTData::XFormPartitions(void) {
1525 int i, numToConvert;
1526 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001527
1528 // Clear out old data & prepare basics....
1529 ClearGPTData();
1530
1531 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001532 if (mainHeader.numParts > (MAX_MBR_PARTS))
1533 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001534 else
1535 numToConvert = mainHeader.numParts;
1536
1537 for (i = 0; i < numToConvert; i++) {
1538 origType = protectiveMBR.GetType(i);
1539 // don't waste CPU time trying to convert extended, hybrid protective, or
1540 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001541 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001542 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001543 partitions[i] = protectiveMBR.AsGPT(i);
1544 } // for
1545
1546 // Convert MBR into protective MBR
1547 protectiveMBR.MakeProtectiveMBR();
1548
1549 // Record that all original CRCs were OK so as not to raise flags
1550 // when doing a disk verification
1551 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1552
1553 return (1);
1554} // GPTData::XFormPartitions()
1555
1556// Transforms BSD disklabel on the specified partition (numbered from 0).
1557// If an invalid partition number is given, the program prompts for one.
srs56946699b012010-02-04 00:55:30 -05001558// (Default for i is -1; called without an option, it therefore prompts.)
srs5694e4ac11e2009-08-31 10:13:04 -04001559// Returns the number of new partitions created.
1560int GPTData::XFormDisklabel(int i) {
1561 uint32_t low, high, partNum, startPart;
1562 uint16_t hexCode;
1563 int goOn = 1, numDone = 0;
1564 BSDData disklabel;
1565
1566 if (GetPartRange(&low, &high) != 0) {
srs5694e321d442010-01-29 17:44:04 -05001567 if ((i < (int) low) || (i > (int) high))
srs5694e4ac11e2009-08-31 10:13:04 -04001568 partNum = GetPartNum();
1569 else
1570 partNum = (uint32_t) i;
1571
1572 // Find the partition after the last used one
1573 startPart = high + 1;
1574
1575 // Now see if the specified partition has a BSD type code....
1576 hexCode = partitions[partNum].GetHexType();
1577 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
srs5694fed16d02010-01-27 23:03:40 -05001578 cout << "Specified partition doesn't have a disklabel partition type "
1579 << "code.\nContinue anyway? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001580 goOn = (GetYN() == 'Y');
1581 } // if
1582
1583 // If all is OK, read the disklabel and convert it.
1584 if (goOn) {
srs5694e321d442010-01-29 17:44:04 -05001585 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
srs5694e4ac11e2009-08-31 10:13:04 -04001586 partitions[partNum].GetLastLBA());
1587 if ((goOn) && (disklabel.IsDisklabel())) {
1588 numDone = XFormDisklabel(&disklabel, startPart);
1589 if (numDone == 1)
srs5694fed16d02010-01-27 23:03:40 -05001590 cout << "Converted " << numDone << " BSD partition.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001591 else
srs5694fed16d02010-01-27 23:03:40 -05001592 cout << "Converted " << numDone << " BSD partitions.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001593 } else {
srs5694fed16d02010-01-27 23:03:40 -05001594 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001595 } // if/else
1596 } // if
1597 if (numDone > 0) { // converted partitions; delete carrier
1598 partitions[partNum].BlankPartition();
1599 } // if
1600 } else {
srs5694fed16d02010-01-27 23:03:40 -05001601 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001602 } // if/else
1603 return numDone;
1604} // GPTData::XFormDisklable(int i)
1605
1606// Transform the partitions on an already-loaded BSD disklabel...
srs5694e321d442010-01-29 17:44:04 -05001607int GPTData::XFormDisklabel(BSDData* disklabel, uint32_t startPart) {
srs5694e4ac11e2009-08-31 10:13:04 -04001608 int i, numDone = 0;
1609
1610 if ((disklabel->IsDisklabel()) && (startPart >= 0) &&
srs56946699b012010-02-04 00:55:30 -05001611 (startPart < mainHeader.numParts)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001612 for (i = 0; i < disklabel->GetNumParts(); i++) {
1613 partitions[i + startPart] = disklabel->AsGPT(i);
1614 if (partitions[i + startPart].GetFirstLBA() != UINT64_C(0))
1615 numDone++;
1616 } // for
1617 } // if
1618
1619 // Record that all original CRCs were OK so as not to raise flags
1620 // when doing a disk verification
1621 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1622
1623 return numDone;
1624} // GPTData::XFormDisklabel(BSDData* disklabel)
1625
srs5694978041c2009-09-21 20:51:47 -04001626// Add one GPT partition to MBR. Used by XFormToMBR() and MakeHybrid()
1627// functions. Returns 1 if operation was successful.
1628int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1629 int allOK = 1, typeCode, bootable;
1630 uint64_t length;
1631 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001632 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001633
srs5694fed16d02010-01-27 23:03:40 -05001634 cout.setf(ios::uppercase);
1635 cout.fill('0');
1636
srs5694978041c2009-09-21 20:51:47 -04001637 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001638 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001639 allOK = 0;
1640 } // if
1641 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001642 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001643 allOK = 0;
1644 } // if
1645 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001646 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001647 allOK = 0;
1648 } // if
1649 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1650 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1651 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001652 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1653 << " some OSes may\nreact strangely.\n";
srs5694978041c2009-09-21 20:51:47 -04001654 } // if partition ends past 32-bit (usually 2TiB) boundary
1655 do {
srs5694fed16d02010-01-27 23:03:40 -05001656 cout << "Enter an MBR hex code (default " << hex;
1657 cout.width(2);
srs56946699b012010-02-04 00:55:30 -05001658 cout << partitions[gptPart].GetHexType() / 0x0100 << "): ";
srs56945d58fe02010-01-03 20:57:08 -05001659 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001660 if (line[0] == '\n')
1661 typeCode = partitions[gptPart].GetHexType() / 256;
srs5694fed16d02010-01-27 23:03:40 -05001662 else
1663 sscanf(line, "%x", &typeCode);
srs5694978041c2009-09-21 20:51:47 -04001664 } while ((typeCode <= 0) || (typeCode > 255));
srs5694fed16d02010-01-27 23:03:40 -05001665 cout << "Set the bootable flag? ";
srs5694978041c2009-09-21 20:51:47 -04001666 bootable = (GetYN() == 'Y');
1667 length = partitions[gptPart].GetLengthLBA();
1668 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1669 (uint32_t) length, typeCode, bootable);
1670 } else { // partition out of range
srs5694fed16d02010-01-27 23:03:40 -05001671 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1672 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001673 allOK = 0;
1674 } // if/else
srs5694fed16d02010-01-27 23:03:40 -05001675 cout.fill(' ');
srs5694978041c2009-09-21 20:51:47 -04001676 return allOK;
1677} // GPTData::OnePartToMBR()
1678
1679// Convert the GPT to MBR form. This function is necessarily limited; it
1680// handles at most four partitions and creates layouts that ignore CHS
1681// geometries. Returns the number of converted partitions; if this value
1682// is over 0, the calling function should call DestroyGPT() to destroy
1683// the GPT data, and then exit.
1684int GPTData::XFormToMBR(void) {
1685 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001686 char* junk;
srs5694e321d442010-01-29 17:44:04 -05001687 int j, numParts, numConverted = 0;
1688 uint32_t i, partNums[4];
srs5694978041c2009-09-21 20:51:47 -04001689
1690 // Get the numbers of up to four partitions to add to the
1691 // hybrid MBR....
1692 numParts = CountParts();
srs5694fed16d02010-01-27 23:03:40 -05001693 cout << "Counted " << numParts << " partitions.\n";
srs5694978041c2009-09-21 20:51:47 -04001694
1695 // Prepare the MBR for conversion (empty it of existing partitions).
1696 protectiveMBR.EmptyMBR(0);
1697 protectiveMBR.SetDiskSize(diskSize);
1698
1699 if (numParts > 4) { // Over four partitions; engage in triage
srs5694fed16d02010-01-27 23:03:40 -05001700 cout << "Type from one to four GPT partition numbers, separated by spaces, to be\n"
1701 << "used in the MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001702 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001703 numParts = sscanf(line, "%d %d %d %d", &partNums[0], &partNums[1],
1704 &partNums[2], &partNums[3]);
1705 } else { // Four or fewer partitions; convert them all
1706 i = j = 0;
1707 while ((j < numParts) && (i < mainHeader.numParts)) {
1708 if (partitions[i].GetFirstLBA() > 0) { // if GPT part. is defined
1709 partNums[j++] = ++i; // flag it for conversion
1710 } else i++;
1711 } // while
1712 } // if/else
1713
srs5694e321d442010-01-29 17:44:04 -05001714 for (i = 0; i < (uint32_t) numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001715 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001716 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001717 numConverted += OnePartToMBR(j, i);
1718 } // for
srs5694fed16d02010-01-27 23:03:40 -05001719 cout << "MBR writing returned " << protectiveMBR.WriteMBRData(&myDisk) << "\n";
srs5694978041c2009-09-21 20:51:47 -04001720 return numConverted;
1721} // GPTData::XFormToMBR()
1722
srs5694e4ac11e2009-08-31 10:13:04 -04001723// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
1724// OSes that don't understand GPT.
1725void GPTData::MakeHybrid(void) {
1726 uint32_t partNums[3];
1727 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001728 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001729 int numParts, numConverted = 0, i, j, typeCode, mbrNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001730 char fillItUp = 'M'; // fill extra partition entries? (Yes/No/Maybe)
srs5694978041c2009-09-21 20:51:47 -04001731 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
srs5694e4ac11e2009-08-31 10:13:04 -04001732
srs5694fed16d02010-01-27 23:03:40 -05001733 cout << "\nWARNING! Hybrid MBRs are flaky and potentially dangerous! If you decide not\n"
1734 << "to use one, just hit the Enter key at the below prompt and your MBR\n"
1735 << "partition table will be untouched.\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -04001736
1737 // Now get the numbers of up to three partitions to add to the
1738 // hybrid MBR....
srs5694fed16d02010-01-27 23:03:40 -05001739 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
1740 << "added to the hybrid MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001741 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001742 numParts = sscanf(line, "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
1743
1744 if (numParts > 0) {
1745 // Blank out the protective MBR, but leave the boot loader code
1746 // alone....
1747 protectiveMBR.EmptyMBR(0);
1748 protectiveMBR.SetDiskSize(diskSize);
srs5694fed16d02010-01-27 23:03:40 -05001749 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001750 eeFirst = GetYN();
1751 } // if
1752
1753 for (i = 0; i < numParts; i++) {
1754 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001755 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001756 if (eeFirst == 'Y')
1757 mbrNum = i + 1;
1758 else
1759 mbrNum = i;
1760 numConverted += OnePartToMBR(j, mbrNum);
srs5694e4ac11e2009-08-31 10:13:04 -04001761 } // for
1762
srs5694978041c2009-09-21 20:51:47 -04001763 if ((numParts > 0) && (numConverted > 0)) { // User opted to create a hybrid MBR....
srs5694e4ac11e2009-08-31 10:13:04 -04001764 // Create EFI protective partition that covers the start of the disk.
1765 // If this location (covering the main GPT data structures) is omitted,
1766 // Linux won't find any partitions on the disk. Note that this is
1767 // NUMBERED AFTER the hybrid partitions, contrary to what the
1768 // gptsync utility does. This is because Windows seems to choke on
1769 // disks with a 0xEE partition in the first slot and subsequent
1770 // additional partitions, unless it boots from the disk.
1771 if (eeFirst == 'Y')
1772 mbrNum = 0;
1773 else
1774 mbrNum = numParts;
1775 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), 0xEE);
srs5694978041c2009-09-21 20:51:47 -04001776 protectiveMBR.SetHybrid();
srs5694e4ac11e2009-08-31 10:13:04 -04001777
1778 // ... and for good measure, if there are any partition spaces left,
1779 // optionally create another protective EFI partition to cover as much
1780 // space as possible....
1781 for (i = 0; i < 4; i++) {
1782 if (protectiveMBR.GetType(i) == 0x00) { // unused entry....
1783 if (fillItUp == 'M') {
srs5694fed16d02010-01-27 23:03:40 -05001784 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001785 fillItUp = GetYN();
1786 typeCode = 0x00; // use this to flag a need to get type code
1787 } // if
1788 if (fillItUp == 'Y') {
1789 while ((typeCode <= 0) || (typeCode > 255)) {
srs5694fed16d02010-01-27 23:03:40 -05001790 cout << "Enter an MBR hex code (EE is EFI GPT, but may confuse MacOS): ";
srs5694e4ac11e2009-08-31 10:13:04 -04001791 // Comment on above: Mac OS treats disks with more than one
1792 // 0xEE MBR partition as MBR disks, not as GPT disks.
srs56945d58fe02010-01-03 20:57:08 -05001793 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001794 sscanf(line, "%x", &typeCode);
1795 if (line[0] == '\n')
1796 typeCode = 0;
1797 } // while
1798 protectiveMBR.MakeBiggestPart(i, typeCode); // make a partition
1799 } // if (fillItUp == 'Y')
1800 } // if unused entry
1801 } // for (i = 0; i < 4; i++)
1802 } // if (numParts > 0)
1803} // GPTData::MakeHybrid()
1804
1805/**********************************************************************
1806 * *
1807 * Functions that adjust GPT data structures WITHOUT user interaction *
1808 * (they may display information for the user's benefit, though) *
1809 * *
1810 **********************************************************************/
1811
1812// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001813// necessary, copies data if it already exists. Returns 1 if all goes
1814// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001815int GPTData::SetGPTSize(uint32_t numEntries) {
1816 struct GPTPart* newParts;
1817 struct GPTPart* trash;
1818 uint32_t i, high, copyNum;
1819 int allOK = 1;
1820
1821 // First, adjust numEntries upward, if necessary, to get a number
1822 // that fills the allocated sectors
1823 i = blockSize / GPT_SIZE;
1824 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001825 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001826 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001827 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001828 } // if
1829
srs5694247657a2009-11-26 18:36:12 -05001830 // Do the work only if the # of partitions is changing. Along with being
1831 // efficient, this prevents mucking the with location of the secondary
1832 // partition table, which causes problems when loading data from a RAID
1833 // array that's been expanded because this function is called when loading
1834 // data.
srs5694546a9c72010-01-26 16:00:26 -05001835 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1836 || (partitions == NULL)) {
srs5694cb76c672010-02-11 22:22:22 -05001837 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001838 if (newParts != NULL) {
1839 if (partitions != NULL) { // existing partitions; copy them over
1840 GetPartRange(&i, &high);
1841 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001842 cout << "The highest-numbered partition is " << high + 1
1843 << ", which is greater than the requested\n"
1844 << "partition table size of " << numEntries
1845 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001846 allOK = 0;
1847 } else { // go ahead with copy
1848 if (numEntries < mainHeader.numParts)
1849 copyNum = numEntries;
1850 else
1851 copyNum = mainHeader.numParts;
1852 for (i = 0; i < copyNum; i++) {
1853 newParts[i] = partitions[i];
1854 } // for
1855 trash = partitions;
1856 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001857 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001858 } // if
1859 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001860 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001861 } // if/else existing partitions
1862 mainHeader.numParts = numEntries;
1863 secondHeader.numParts = numEntries;
1864 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1865 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1866 MoveSecondHeaderToEnd();
1867 if (diskSize > 0)
1868 CheckGPTSize();
1869 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001870 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001871 allOK = 0;
1872 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001873 } // if/else
1874 return (allOK);
1875} // GPTData::SetGPTSize()
1876
1877// Blank the partition array
1878void GPTData::BlankPartitions(void) {
1879 uint32_t i;
1880
1881 for (i = 0; i < mainHeader.numParts; i++) {
1882 partitions[i].BlankPartition();
1883 } // for
1884} // GPTData::BlankPartitions()
1885
srs5694ba00fed2010-01-12 18:18:36 -05001886// Delete a partition by number. Returns 1 if successful,
1887// 0 if there was a problem. Returns 1 if partition was in
1888// range, 0 if it was out of range.
1889int GPTData::DeletePartition(uint32_t partNum) {
1890 uint64_t startSector, length;
1891 uint32_t low, high, numParts, retval = 1;;
1892
1893 numParts = GetPartRange(&low, &high);
1894 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1895 // In case there's a protective MBR, look for & delete matching
1896 // MBR partition....
1897 startSector = partitions[partNum].GetFirstLBA();
1898 length = partitions[partNum].GetLengthLBA();
1899 protectiveMBR.DeleteByLocation(startSector, length);
1900
1901 // Now delete the GPT partition
1902 partitions[partNum].BlankPartition();
1903 } else {
srs5694fed16d02010-01-27 23:03:40 -05001904 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001905 retval = 0;
1906 } // if/else
1907 return retval;
1908} // GPTData::DeletePartition(uint32_t partNum)
1909
1910// Non-interactively create a partition. Note that this function is overloaded
1911// with another of the same name but different parameters; that one prompts
1912// the user for data. This one returns 1 if the operation was successful, 0
1913// if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001914uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001915 int retval = 1; // assume there'll be no problems
1916
1917 if (IsFreePartNum(partNum)) {
1918 Align(&startSector); // Align sector to correct multiple
1919 if (IsFree(startSector) && (startSector <= endSector)) {
1920 if (FindLastInFree(startSector) >= endSector) {
1921 partitions[partNum].SetFirstLBA(startSector);
1922 partitions[partNum].SetLastLBA(endSector);
1923 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001924 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001925 } else retval = 0; // if free space until endSector
1926 } else retval = 0; // if startSector is free
1927 } else retval = 0; // if legal partition number
1928 return retval;
1929} // GPTData::CreatePartition(partNum, startSector, endSector)
1930
srs5694e4ac11e2009-08-31 10:13:04 -04001931// Sort the GPT entries, eliminating gaps and making for a logical
1932// ordering. Relies on QuickSortGPT() for the bulk of the work
1933void GPTData::SortGPT(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001934 GPTPart temp;
srs5694546a9c72010-01-26 16:00:26 -05001935 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001936
1937 // First, find the last partition with data, so as not to
1938 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001939 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001940
1941 // Now swap empties with the last partitions, to simplify the logic
1942 // in the Quicksort function....
1943 i = 0;
1944 while (i < lastPart) {
1945 if (partitions[i].GetFirstLBA() == 0) {
1946 temp = partitions[i];
1947 partitions[i] = partitions[lastPart];
1948 partitions[lastPart] = temp;
srs5694546a9c72010-01-26 16:00:26 -05001949 do {
1950 lastPart--;
1951 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001952 } // if
1953 i++;
1954 } // while
1955
srs5694546a9c72010-01-26 16:00:26 -05001956 // If there are more empties than partitions in the range from 0 to lastPart,
1957 // the above leaves lastPart set too high, so we've got to adjust it to
1958 // prevent empties from migrating to the top of the list....
1959 GetPartRange(&firstPart, &lastPart);
1960
srs5694e4ac11e2009-08-31 10:13:04 -04001961 // Now call the recursive quick sort routine to do the real work....
1962 QuickSortGPT(partitions, 0, lastPart);
1963} // GPTData::SortGPT()
1964
1965// Set up data structures for entirely new set of partitions on the
1966// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001967// Note that this function does NOT clear the protectiveMBR data
1968// structure, since it may hold the original MBR partitions if the
1969// program was launched on an MBR disk, and those may need to be
1970// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001971int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001972 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001973
1974 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001975 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001976 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001977 partitions = NULL;
1978 SetGPTSize(NUM_GPT_ENTRIES);
1979
1980 // Now initialize a bunch of stuff that's static....
1981 mainHeader.signature = GPT_SIGNATURE;
1982 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001983 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001984 mainHeader.reserved = 0;
1985 mainHeader.currentLBA = UINT64_C(1);
1986 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1987 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1988 for (i = 0; i < GPT_RESERVED; i++) {
1989 mainHeader.reserved2[i] = '\0';
1990 } // for
1991
1992 // Now some semi-static items (computed based on end of disk)
1993 mainHeader.backupLBA = diskSize - UINT64_C(1);
1994 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1995
1996 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001997 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001998
1999 // Copy main header to backup header
2000 RebuildSecondHeader();
2001
2002 // Blank out the partitions array....
2003 BlankPartitions();
2004
2005 // Flag all CRCs as being OK....
2006 mainCrcOk = 1;
2007 secondCrcOk = 1;
2008 mainPartsCrcOk = 1;
2009 secondPartsCrcOk = 1;
2010
2011 return (goOn);
2012} // GPTData::ClearGPTData()
2013
srs5694247657a2009-11-26 18:36:12 -05002014// Set the location of the second GPT header data to the end of the disk.
2015// Used internally and called by the 'e' option on the recovery &
2016// transformation menu, to help users of RAID arrays who add disk space
2017// to their arrays.
2018void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05002019 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2020 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2021 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2022} // GPTData::FixSecondHeaderLocation()
2023
srs56940a697312010-01-28 21:10:52 -05002024int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05002025 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05002026
2027 if (!IsFreePartNum(partNum)) {
2028 partitions[partNum].SetName(theName);
2029 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05002030
2031 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04002032} // GPTData::SetName
2033
2034// Set the disk GUID to the specified value. Note that the header CRCs must
2035// be recomputed after calling this function.
2036void GPTData::SetDiskGUID(GUIDData newGUID) {
2037 mainHeader.diskGUID = newGUID;
2038 secondHeader.diskGUID = newGUID;
2039} // SetDiskGUID()
2040
2041// Set the unique GUID of the specified partition. Returns 1 on
2042// successful completion, 0 if there were problems (invalid
2043// partition number).
2044int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2045 int retval = 0;
2046
2047 if (pn < mainHeader.numParts) {
2048 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
2049 partitions[pn].SetUniqueGUID(theGUID);
2050 retval = 1;
2051 } // if
2052 } // if
2053 return retval;
2054} // GPTData::SetPartitionGUID()
2055
srs5694ba00fed2010-01-12 18:18:36 -05002056// Change partition type code non-interactively. Returns 1 if
2057// successful, 0 if not....
2058int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
2059 int retval = 1;
2060
2061 if (!IsFreePartNum(partNum)) {
2062 partitions[partNum].SetType(hexCode);
2063 } else retval = 0;
2064 return retval;
2065} // GPTData::ChangePartType()
2066
srs56941d1448a2009-12-31 21:20:19 -05002067// Adjust sector number so that it falls on a sector boundary that's a
2068// multiple of sectorAlignment. This is done to improve the performance
2069// of Western Digital Advanced Format disks and disks with similar
2070// technology from other companies, which use 4096-byte sectors
2071// internally although they translate to 512-byte sectors for the
2072// benefit of the OS. If partitions aren't properly aligned on these
2073// disks, some filesystem data structures can span multiple physical
2074// sectors, degrading performance. This function should be called
2075// only on the FIRST sector of the partition, not the last!
2076// This function returns 1 if the alignment was altered, 0 if it
2077// was unchanged.
2078int GPTData::Align(uint64_t* sector) {
2079 int retval = 0, sectorOK = 0;
2080 uint64_t earlier, later, testSector, original;
2081
2082 if ((*sector % sectorAlignment) != 0) {
2083 original = *sector;
2084 retval = 1;
2085 earlier = (*sector / sectorAlignment) * sectorAlignment;
2086 later = earlier + (uint64_t) sectorAlignment;
2087
2088 // Check to see that every sector between the earlier one and the
2089 // requested one is clear, and that it's not too early....
2090 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05002091 sectorOK = 1;
2092 testSector = earlier;
2093 do {
2094 sectorOK = IsFree(testSector++);
2095 } while ((sectorOK == 1) && (testSector < *sector));
2096 if (sectorOK == 1) {
2097 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05002098 } // if
2099 } // if firstUsableLBA check
2100
2101 // If couldn't move the sector earlier, try to move it later instead....
2102 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2103 sectorOK = 1;
2104 testSector = later;
2105 do {
2106 sectorOK = IsFree(testSector--);
2107 } while ((sectorOK == 1) && (testSector > *sector));
2108 if (sectorOK == 1) {
2109 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05002110 } // if
2111 } // if
2112
2113 // If sector was changed successfully, inform the user of this fact.
2114 // Otherwise, notify the user that it couldn't be done....
2115 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05002116 cout << "Information: Moved requested sector from " << original << " to "
2117 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05002118 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05002119 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05002120 } else {
srs5694fed16d02010-01-27 23:03:40 -05002121 cout << "Information: Sector not aligned on " << sectorAlignment
2122 << "-sector boundary and could not be moved.\n"
2123 << "If you're using a Western Digital Advanced Format or similar disk with\n"
2124 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05002125 retval = 0;
2126 } // if/else
2127 } // if
2128 return retval;
2129} // GPTData::Align()
2130
srs5694e4ac11e2009-08-31 10:13:04 -04002131/********************************************************
2132 * *
2133 * Functions that return data about GPT data structures *
2134 * (most of these are inline in gpt.h) *
2135 * *
2136 ********************************************************/
2137
2138// Find the low and high used partition numbers (numbered from 0).
2139// Return value is the number of partitions found. Note that the
2140// *low and *high values are both set to 0 when no partitions
2141// are found, as well as when a single partition in the first
2142// position exists. Thus, the return value is the only way to
2143// tell when no partitions exist.
2144int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2145 uint32_t i;
2146 int numFound = 0;
2147
2148 *low = mainHeader.numParts + 1; // code for "not found"
2149 *high = 0;
2150 if (mainHeader.numParts > 0) { // only try if partition table exists...
2151 for (i = 0; i < mainHeader.numParts; i++) {
2152 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
2153 *high = i; // since we're counting up, set the high value
2154 // Set the low value only if it's not yet found...
2155 if (*low == (mainHeader.numParts + 1)) *low = i;
2156 numFound++;
2157 } // if
2158 } // for
2159 } // if
2160
2161 // Above will leave *low pointing to its "not found" value if no partitions
2162 // are defined, so reset to 0 if this is the case....
2163 if (*low == (mainHeader.numParts + 1))
2164 *low = 0;
2165 return numFound;
2166} // GPTData::GetPartRange()
2167
srs5694978041c2009-09-21 20:51:47 -04002168// Returns the number of defined partitions.
2169uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002170 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002171
2172 for (i = 0; i < mainHeader.numParts; i++) {
2173 if (partitions[i].GetFirstLBA() > 0)
2174 counted++;
2175 } // for
2176 return counted;
2177} // GPTData::CountParts()
2178
srs5694e4ac11e2009-08-31 10:13:04 -04002179/****************************************************
2180 * *
2181 * Functions that return data about disk free space *
2182 * *
2183 ****************************************************/
2184
2185// Find the first available block after the starting point; returns 0 if
2186// there are no available blocks left
2187uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2188 uint64_t first;
2189 uint32_t i;
2190 int firstMoved = 0;
2191
2192 // Begin from the specified starting point or from the first usable
2193 // LBA, whichever is greater...
2194 if (start < mainHeader.firstUsableLBA)
2195 first = mainHeader.firstUsableLBA;
2196 else
2197 first = start;
2198
2199 // ...now search through all partitions; if first is within an
2200 // existing partition, move it to the next sector after that
2201 // partition and repeat. If first was moved, set firstMoved
2202 // flag; repeat until firstMoved is not set, so as to catch
2203 // cases where partitions are out of sequential order....
2204 do {
2205 firstMoved = 0;
2206 for (i = 0; i < mainHeader.numParts; i++) {
2207 if ((first >= partitions[i].GetFirstLBA()) &&
2208 (first <= partitions[i].GetLastLBA())) { // in existing part.
2209 first = partitions[i].GetLastLBA() + 1;
2210 firstMoved = 1;
2211 } // if
2212 } // for
2213 } while (firstMoved == 1);
2214 if (first > mainHeader.lastUsableLBA)
2215 first = 0;
2216 return (first);
2217} // GPTData::FindFirstAvailable()
2218
2219// Finds the first available sector in the largest block of unallocated
2220// space on the disk. Returns 0 if there are no available blocks left
2221uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002222 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002223
2224 start = 0;
2225 do {
2226 firstBlock = FindFirstAvailable(start);
2227 if (firstBlock != UINT32_C(0)) { // something's free...
2228 lastBlock = FindLastInFree(firstBlock);
2229 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2230 if (segmentSize > selectedSize) {
2231 selectedSize = segmentSize;
2232 selectedSegment = firstBlock;
2233 } // if
2234 start = lastBlock + 1;
2235 } // if
2236 } while (firstBlock != 0);
2237 return selectedSegment;
2238} // GPTData::FindFirstInLargest()
2239
srs5694cb76c672010-02-11 22:22:22 -05002240// Find the last available block on the disk.
2241// Returns 0 if there are no available partitions
2242uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002243 uint64_t last;
2244 uint32_t i;
2245 int lastMoved = 0;
2246
2247 // Start by assuming the last usable LBA is available....
2248 last = mainHeader.lastUsableLBA;
2249
2250 // ...now, similar to algorithm in FindFirstAvailable(), search
2251 // through all partitions, moving last when it's in an existing
2252 // partition. Set the lastMoved flag so we repeat to catch cases
2253 // where partitions are out of logical order.
2254 do {
2255 lastMoved = 0;
2256 for (i = 0; i < mainHeader.numParts; i++) {
2257 if ((last >= partitions[i].GetFirstLBA()) &&
2258 (last <= partitions[i].GetLastLBA())) { // in existing part.
2259 last = partitions[i].GetFirstLBA() - 1;
2260 lastMoved = 1;
2261 } // if
2262 } // for
2263 } while (lastMoved == 1);
2264 if (last < mainHeader.firstUsableLBA)
2265 last = 0;
2266 return (last);
2267} // GPTData::FindLastAvailable()
2268
2269// Find the last available block in the free space pointed to by start.
2270uint64_t GPTData::FindLastInFree(uint64_t start) {
2271 uint64_t nearestStart;
2272 uint32_t i;
2273
2274 nearestStart = mainHeader.lastUsableLBA;
2275 for (i = 0; i < mainHeader.numParts; i++) {
2276 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2277 (partitions[i].GetFirstLBA() > start)) {
2278 nearestStart = partitions[i].GetFirstLBA() - 1;
2279 } // if
2280 } // for
2281 return (nearestStart);
2282} // GPTData::FindLastInFree()
2283
2284// Finds the total number of free blocks, the number of segments in which
2285// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002286uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002287 uint64_t start = UINT64_C(0); // starting point for each search
2288 uint64_t totalFound = UINT64_C(0); // running total
2289 uint64_t firstBlock; // first block in a segment
2290 uint64_t lastBlock; // last block in a segment
2291 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002292 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002293
2294 *largestSegment = UINT64_C(0);
2295 do {
2296 firstBlock = FindFirstAvailable(start);
2297 if (firstBlock != UINT64_C(0)) { // something's free...
2298 lastBlock = FindLastInFree(firstBlock);
2299 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2300 if (segmentSize > *largestSegment) {
2301 *largestSegment = segmentSize;
2302 } // if
2303 totalFound += segmentSize;
2304 num++;
2305 start = lastBlock + 1;
2306 } // if
2307 } while (firstBlock != 0);
2308 *numSegments = num;
2309 return totalFound;
2310} // GPTData::FindFreeBlocks()
2311
2312// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2313int GPTData::IsFree(uint64_t sector) {
2314 int isFree = 1;
2315 uint32_t i;
2316
2317 for (i = 0; i < mainHeader.numParts; i++) {
2318 if ((sector >= partitions[i].GetFirstLBA()) &&
2319 (sector <= partitions[i].GetLastLBA())) {
2320 isFree = 0;
2321 } // if
2322 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002323 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002324 (sector > mainHeader.lastUsableLBA)) {
2325 isFree = 0;
2326 } // if
2327 return (isFree);
2328} // GPTData::IsFree()
2329
srs5694ba00fed2010-01-12 18:18:36 -05002330// Returns 1 if partNum is unused.
2331int GPTData::IsFreePartNum(uint32_t partNum) {
2332 int retval = 1;
2333
2334 if ((partNum >= 0) && (partNum < mainHeader.numParts)) {
2335 if ((partitions[partNum].GetFirstLBA() != UINT64_C(0)) ||
2336 (partitions[partNum].GetLastLBA() != UINT64_C(0))) {
2337 retval = 0;
2338 } // if partition is in use
2339 } else retval = 0;
2340
2341 return retval;
2342} // GPTData::IsFreePartNum()
2343
srs5694e4ac11e2009-08-31 10:13:04 -04002344/********************************
2345 * *
2346 * Endianness support functions *
2347 * *
2348 ********************************/
2349
srs56942a9f5da2009-08-26 00:48:01 -04002350void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002351 ReverseBytes(&header->signature, 8);
2352 ReverseBytes(&header->revision, 4);
2353 ReverseBytes(&header->headerSize, 4);
2354 ReverseBytes(&header->headerCRC, 4);
2355 ReverseBytes(&header->reserved, 4);
2356 ReverseBytes(&header->currentLBA, 8);
2357 ReverseBytes(&header->backupLBA, 8);
2358 ReverseBytes(&header->firstUsableLBA, 8);
2359 ReverseBytes(&header->lastUsableLBA, 8);
2360 ReverseBytes(&header->partitionEntriesLBA, 8);
2361 ReverseBytes(&header->numParts, 4);
2362 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2363 ReverseBytes(&header->partitionEntriesCRC, 4);
2364 ReverseBytes(&header->reserved2, GPT_RESERVED);
srs56946699b012010-02-04 00:55:30 -05002365// header->diskGUID.ReverseGUIDBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002366} // GPTData::ReverseHeaderBytes()
2367
2368// IMPORTANT NOTE: This function requires non-reversed mainHeader
2369// structure!
2370void GPTData::ReversePartitionBytes() {
2371 uint32_t i;
2372
2373 // Check GPT signature on big-endian systems; this will mismatch
2374 // if the function is called out of order. Unfortunately, it'll also
2375 // mismatch if there's data corruption.
2376 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002377 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2378 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002379 } // if signature mismatch....
2380 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002381 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002382 } // for
2383} // GPTData::ReversePartitionBytes()
2384
2385/******************************************
2386 * *
2387 * Additional non-class support functions *
2388 * *
2389 ******************************************/
2390
srs5694e7b4ff92009-08-18 13:16:10 -04002391// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2392// never fail these tests, but the struct types may fail depending on compile options.
2393// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2394// sizes.
2395int SizesOK(void) {
2396 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002397
2398 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002399 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002400 allOK = 0;
2401 } // if
2402 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002403 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002404 allOK = 0;
2405 } // if
2406 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002407 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002408 allOK = 0;
2409 } // if
2410 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002411 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002412 allOK = 0;
2413 } // if
2414 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002415 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002416 allOK = 0;
2417 } // if
srs5694978041c2009-09-21 20:51:47 -04002418 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002419 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002420 allOK = 0;
2421 } // if
2422 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002423 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002424 allOK = 0;
2425 } // if
srs5694221e0872009-08-29 15:00:31 -04002426 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002427 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002428 allOK = 0;
2429 } // if
srs56946699b012010-02-04 00:55:30 -05002430 if (sizeof(GUIDData) != 16) {
2431 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2432 allOK = 0;
2433 } // if
2434 if (sizeof(PartType) != 16) {
2435 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2436 allOK = 0;
2437 } // if
srs5694fed16d02010-01-27 23:03:40 -05002438 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002439 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002440 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2441 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002442 } // if
2443 return (allOK);
2444} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002445