blob: e5c9852c0bfa6d04da5fde4cea3b074ca7986ad7 [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2 data. */
3
srs5694e4ac11e2009-08-31 10:13:04 -04004/* By Rod Smith, initial coding January to February, 2009 */
srs5694e7b4ff92009-08-18 13:16:10 -04005
srs5694221e0872009-08-29 15:00:31 -04006/* This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
7 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
13#include <unistd.h>
14#include <stdlib.h>
15#include <stdint.h>
16#include <fcntl.h>
17#include <string.h>
18#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs5694e7b4ff92009-08-18 13:16:10 -040022#include "crc32.h"
23#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040024#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040025#include "support.h"
26#include "parttypes.h"
27#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050028#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040029
30using namespace std;
31
32/****************************************
33 * *
34 * GPTData class and related structures *
35 * *
36 ****************************************/
37
srs5694e4ac11e2009-08-31 10:13:04 -040038// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040039GPTData::GPTData(void) {
40 blockSize = SECTOR_SIZE; // set a default
41 diskSize = 0;
42 partitions = NULL;
43 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050044 device = "";
srs56945d58fe02010-01-03 20:57:08 -050045 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040046 mainCrcOk = 0;
47 secondCrcOk = 0;
48 mainPartsCrcOk = 0;
49 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040050 apmFound = 0;
51 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050052 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050053 beQuiet = 0;
54 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040055 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050056 mainHeader.numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040057 SetGPTSize(NUM_GPT_ENTRIES);
58} // GPTData default constructor
59
60// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050061GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040062 blockSize = SECTOR_SIZE; // set a default
63 diskSize = 0;
64 partitions = NULL;
65 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050066 device = "";
srs56945d58fe02010-01-03 20:57:08 -050067 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040068 mainCrcOk = 0;
69 secondCrcOk = 0;
70 mainPartsCrcOk = 0;
71 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040072 apmFound = 0;
73 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050074 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050075 beQuiet = 0;
76 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040077 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050078 mainHeader.numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050079 if (!LoadPartitions(filename))
80 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050081} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040082
srs5694e4ac11e2009-08-31 10:13:04 -040083// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040084GPTData::~GPTData(void) {
85 free(partitions);
86} // GPTData destructor
87
srs5694e4ac11e2009-08-31 10:13:04 -040088/*********************************************************************
89 * *
90 * Begin functions that verify data, or that adjust the verification *
91 * information (compute CRCs, rebuild headers) *
92 * *
93 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040094
srs5694e4ac11e2009-08-31 10:13:04 -040095// Perform detailed verification, reporting on any problems found, but
96// do *NOT* recover from these problems. Returns the total number of
97// problems identified.
98int GPTData::Verify(void) {
srs56941d1448a2009-12-31 21:20:19 -050099 int problems = 0, numSegments, i;
100 uint64_t totalFree, largestSegment, firstSector;
srs5694e4ac11e2009-08-31 10:13:04 -0400101 char tempStr[255], siTotal[255], siLargest[255];
102
103 // First, check for CRC errors in the GPT data....
104 if (!mainCrcOk) {
105 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500106 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
107 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
108 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
109 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400110 } // if
111 if (!mainPartsCrcOk) {
112 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500113 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
114 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
115 << "transformation menu). This report may be a false alarm if you've already\n"
116 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400117 } // if
118 if (!secondCrcOk) {
119 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500120 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
121 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
122 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
123 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400124 } // if
125 if (!secondPartsCrcOk) {
126 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500127 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
128 << "be corrupt. This program will automatically create a new backup partition\n"
129 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400130 } // if
131
srs5694978041c2009-09-21 20:51:47 -0400132 // Now check that the main and backup headers both point to themselves....
133 if (mainHeader.currentLBA != 1) {
134 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500135 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
136 << "is being automatically corrected, but it may be a symptom of more serious\n"
137 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400138 mainHeader.currentLBA = 1;
139 } // if
140 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
141 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500142 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
143 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
144 << "option on the experts' menu to adjust the secondary header's and partition\n"
145 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400146 } // if
147
148 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400149 if (mainHeader.currentLBA != secondHeader.backupLBA) {
150 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500151 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
152 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
153 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400154 } // if
155 if (mainHeader.backupLBA != secondHeader.currentLBA) {
156 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500157 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
158 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
159 << secondHeader.currentLBA << ").\n"
160 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400161 } // if
162 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
163 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500164 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
165 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
166 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400167 } // if
168 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
169 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500170 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
171 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
172 << secondHeader.lastUsableLBA << ")\n"
173 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400174 } // if
175 if ((mainHeader.diskGUID.data1 != secondHeader.diskGUID.data1) ||
176 (mainHeader.diskGUID.data2 != secondHeader.diskGUID.data2)) {
177 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500178 cout << "\nProblem: main header's disk GUID (" << GUIDToStr(mainHeader.diskGUID)
179 << ") doesn't\nmatch the backup GPT header's disk GUID ("
180 << GUIDToStr(secondHeader.diskGUID) << ")\n"
181 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
182 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400183 } // if
184 if (mainHeader.numParts != secondHeader.numParts) {
185 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500186 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
187 << ") doesn't\nmatch the backup GPT header's number of partitions ("
188 << secondHeader.numParts << ")\n"
189 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400190 } // if
191 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
192 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500193 cout << "\nProblem: main GPT header's size of partition entries ("
194 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
195 << "match the backup GPT header's size of partition entries ("
196 << secondHeader.sizeOfPartitionEntries << ")\n"
197 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
198 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400199 } // if
200
201 // Now check for a few other miscellaneous problems...
202 // Check that the disk size will hold the data...
203 if (mainHeader.backupLBA > diskSize) {
204 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500205 cout << "\nProblem: Disk is too small to hold all the data!\n"
206 << "(Disk size is " << diskSize << " sectors, needs to be "
207 << mainHeader.backupLBA << " sectors.)\n"
208 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400209 } // if
210
211 // Check for overlapping partitions....
212 problems += FindOverlaps();
213
214 // Check for mismatched MBR and GPT partitions...
215 problems += FindHybridMismatches();
216
217 // Verify that partitions don't run into GPT data areas....
218 problems += CheckGPTSize();
219
srs56941d1448a2009-12-31 21:20:19 -0500220 // Check that partitions are aligned on proper boundaries (for WD Advanced
221 // Format and similar disks)....
222 for (i = 0; i < mainHeader.numParts; i++) {
223 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500224 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
225 << sectorAlignment << "-sector boundary. This may\nresult "
226 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500227 } // if
228 } // for
229
srs5694e4ac11e2009-08-31 10:13:04 -0400230 // Now compute available space, but only if no problems found, since
231 // problems could affect the results
232 if (problems == 0) {
233 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500234 strcpy(siTotal, BytesToSI(totalFree * (uint64_t) blockSize).c_str());
235 strcpy(siLargest, BytesToSI(largestSegment * (uint64_t) blockSize).c_str());
236 cout << "No problems found. " << totalFree << " free sectors ("
237 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
238 << numSegments << "\nsegments, the largest of which is "
239 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
240 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } else {
srs5694fed16d02010-01-27 23:03:40 -0500242 cout << "\nIdentified %d problems!\n", problems;
srs5694e7b4ff92009-08-18 13:16:10 -0400243 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400244
245 return (problems);
246} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400247
248// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400249// do, issues a warning but takes no action. Returns number of problems
250// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400251int GPTData::CheckGPTSize(void) {
252 uint64_t overlap, firstUsedBlock, lastUsedBlock;
253 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400254 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400255
256 // first, locate the first & last used blocks
257 firstUsedBlock = UINT64_MAX;
258 lastUsedBlock = 0;
259 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400260 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400261 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400262 firstUsedBlock = partitions[i].GetFirstLBA();
263 if (partitions[i].GetLastLBA() > lastUsedBlock)
264 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400265 } // for
266
267 // If the disk size is 0 (the default), then it means that various
268 // variables aren't yet set, so the below tests will be useless;
269 // therefore we should skip everything
270 if (diskSize != 0) {
271 if (mainHeader.firstUsableLBA > firstUsedBlock) {
272 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500273 cout << "Warning! Main partition table overlaps the first partition by "
274 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400275 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "Try reducing the partition table size by " << overlap * 4
277 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400278 } else {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400280 } // if/else
281 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400282 } // Problem at start of disk
283 if (mainHeader.lastUsableLBA < lastUsedBlock) {
284 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs5694fed16d02010-01-27 23:03:40 -0500285 cout << "Warning! Secondary partition table overlaps the last partition by "
286 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400287 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500288 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400289 } else {
srs5694fed16d02010-01-27 23:03:40 -0500290 cout << "Try reducing the partition table size by " << overlap * 4
291 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400292 } // if/else
293 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400294 } // Problem at end of disk
295 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400296 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400297} // GPTData::CheckGPTSize()
298
srs5694e7b4ff92009-08-18 13:16:10 -0400299// Check the validity of the GPT header. Returns 1 if the main header
300// is valid, 2 if the backup header is valid, 3 if both are valid, and
301// 0 if neither is valid. Note that this function just checks the GPT
302// signature and revision numbers, not CRCs or other data.
303int GPTData::CheckHeaderValidity(void) {
304 int valid = 3;
305
srs5694fed16d02010-01-27 23:03:40 -0500306 cout.setf(ios::uppercase);
307 cout.fill('0');
308
309 // Note: failed GPT signature checks produce no error message because
310 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400311 if (mainHeader.signature != GPT_SIGNATURE) {
312 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400313 } else if ((mainHeader.revision != 0x00010000) && valid) {
314 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500315 cout << "Unsupported GPT version in main header; read 0x";
316 cout.width(8);
317 cout << hex << mainHeader.revision << ", should be\n0x";
318 cout.width(8);
319 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400320 } // if/else/if
321
322 if (secondHeader.signature != GPT_SIGNATURE) {
323 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } else if ((secondHeader.revision != 0x00010000) && valid) {
325 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500326 cout << "Unsupported GPT version in backup header; read 0x";
327 cout.width(8);
328 cout << hex << secondHeader.revision << ", should be\n0x";
329 cout.width(8);
330 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400331 } // if/else/if
332
srs56942a9f5da2009-08-26 00:48:01 -0400333 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400334 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400335 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400336 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400337 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500338 } // if
srs5694fed16d02010-01-27 23:03:40 -0500339 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400340
srs5694fed16d02010-01-27 23:03:40 -0500341 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400342} // GPTData::CheckHeaderValidity()
343
344// Check the header CRC to see if it's OK...
srs56942a9f5da2009-08-26 00:48:01 -0400345// Note: Must be called BEFORE byte-order reversal on big-endian
346// systems!
srs5694e7b4ff92009-08-18 13:16:10 -0400347int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400348 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400349
srs56942a9f5da2009-08-26 00:48:01 -0400350 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400351 // computation to be valid
352 oldCRC = header->headerCRC;
353 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400354 hSize = header->headerSize;
355
356 // If big-endian system, reverse byte order
357 if (IsLittleEndian() == 0) {
358 ReverseBytes(&oldCRC, 4);
359 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400360
361 // Initialize CRC functions...
362 chksum_crc32gentab();
363
364 // Compute CRC, restore original, and return result of comparison
365 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400366 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400367 return (oldCRC == newCRC);
368} // GPTData::CheckHeaderCRC()
369
srs56942a9f5da2009-08-26 00:48:01 -0400370// Recompute all the CRCs. Must be called before saving (but after reversing
371// byte order on big-endian systems) if any changes have been made.
srs5694e7b4ff92009-08-18 13:16:10 -0400372void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400373 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400374 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400375
376 // Initialize CRC functions...
377 chksum_crc32gentab();
378
srs5694978041c2009-09-21 20:51:47 -0400379 hSize = mainHeader.headerSize;
srs56942a9f5da2009-08-26 00:48:01 -0400380 littleEndian = IsLittleEndian();
381
srs5694e7b4ff92009-08-18 13:16:10 -0400382 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400383 trueNumParts = mainHeader.numParts;
384 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400385 ReverseBytes(&trueNumParts, 4); // unreverse this key piece of data....
srs56942a9f5da2009-08-26 00:48:01 -0400386 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400387 mainHeader.partitionEntriesCRC = crc;
388 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400389 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400390 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
391 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400392 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400393
394 // Zero out GPT tables' own CRCs (required for correct computation)
395 mainHeader.headerCRC = 0;
396 secondHeader.headerCRC = 0;
397
398 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400399 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400400 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400401 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400402 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400403 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400404 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400405 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400406 secondHeader.headerCRC = crc;
407} // GPTData::RecomputeCRCs()
408
srs5694e7b4ff92009-08-18 13:16:10 -0400409// Rebuild the main GPT header, using the secondary header as a model.
410// Typically called when the main header has been found to be corrupt.
411void GPTData::RebuildMainHeader(void) {
412 int i;
413
414 mainHeader.signature = GPT_SIGNATURE;
415 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400416 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400417 mainHeader.headerCRC = UINT32_C(0);
418 mainHeader.reserved = secondHeader.reserved;
419 mainHeader.currentLBA = secondHeader.backupLBA;
420 mainHeader.backupLBA = secondHeader.currentLBA;
421 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
422 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
423 mainHeader.diskGUID.data1 = secondHeader.diskGUID.data1;
424 mainHeader.diskGUID.data2 = secondHeader.diskGUID.data2;
425 mainHeader.partitionEntriesLBA = UINT64_C(2);
426 mainHeader.numParts = secondHeader.numParts;
427 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
428 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
429 for (i = 0 ; i < GPT_RESERVED; i++)
430 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500431 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400432} // GPTData::RebuildMainHeader()
433
434// Rebuild the secondary GPT header, using the main header as a model.
435void GPTData::RebuildSecondHeader(void) {
436 int i;
437
438 secondHeader.signature = GPT_SIGNATURE;
439 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400440 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400441 secondHeader.headerCRC = UINT32_C(0);
442 secondHeader.reserved = mainHeader.reserved;
443 secondHeader.currentLBA = mainHeader.backupLBA;
444 secondHeader.backupLBA = mainHeader.currentLBA;
445 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
446 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
447 secondHeader.diskGUID.data1 = mainHeader.diskGUID.data1;
448 secondHeader.diskGUID.data2 = mainHeader.diskGUID.data2;
449 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
450 secondHeader.numParts = mainHeader.numParts;
451 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
452 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
453 for (i = 0 ; i < GPT_RESERVED; i++)
454 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500455 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400456} // GPTData::RebuildSecondHeader()
457
458// Search for hybrid MBR entries that have no corresponding GPT partition.
459// Returns number of such mismatches found
460int GPTData::FindHybridMismatches(void) {
461 int i, j, found, numFound = 0;
462 uint64_t mbrFirst, mbrLast;
463
464 for (i = 0; i < 4; i++) {
465 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
466 j = 0;
467 found = 0;
468 do {
469 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
470 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
471 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
472 (partitions[j].GetLastLBA() == mbrLast))
473 found = 1;
474 j++;
475 } while ((!found) && (j < mainHeader.numParts));
476 if (!found) {
477 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500478 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
479 << i + 1 << ", of type 0x";
480 cout.fill('0');
481 cout.setf(ios::uppercase);
482 cout.width(2);
483 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
484 << "has no corresponding GPT partition! You may continue, but this condition\n"
485 << "might cause data loss in the future!\a\n" << dec;
486 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400487 } // if
488 } // if
489 } // for
490 return numFound;
491} // GPTData::FindHybridMismatches
492
493// Find overlapping partitions and warn user about them. Returns number of
494// overlapping partitions.
495int GPTData::FindOverlaps(void) {
496 int i, j, problems = 0;
497
498 for (i = 1; i < mainHeader.numParts; i++) {
499 for (j = 0; j < i; j++) {
500 if (partitions[i].DoTheyOverlap(&partitions[j])) {
501 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500502 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
503 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
504 << " to " << partitions[i].GetLastLBA() << "\n";
505 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
506 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400507 } // if
508 } // for j...
509 } // for i...
510 return problems;
511} // GPTData::FindOverlaps()
512
513/******************************************************************
514 * *
515 * Begin functions that load data from disk or save data to disk. *
516 * *
517 ******************************************************************/
518
519// Scan for partition data. This function loads the MBR data (regular MBR or
520// protective MBR) and loads BSD disklabel data (which is probably invalid).
521// It also looks for APM data, forces a load of GPT data, and summarizes
522// the results.
srs5694546a9c72010-01-26 16:00:26 -0500523void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400524 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400525
526 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500527 protectiveMBR.ReadMBRData(&myDisk);
528 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400529
530 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500531 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500532
533 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500534 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500535 protectiveMBR.ShowState();
536 bsdDisklabel.ShowState();
537 ShowAPMState(); // Show whether there's an Apple Partition Map present
538 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500539 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500540 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400541
542 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500543 cout << "\n*******************************************************************\n"
544 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500545 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500546 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500547 } // if
srs5694fed16d02010-01-27 23:03:40 -0500548 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400549 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400550} // GPTData::PartitionScan()
551
552// Read GPT data from a disk.
srs5694fed16d02010-01-27 23:03:40 -0500553int GPTData::LoadPartitions(string deviceFilename) {
554 int err;
srs5694e4ac11e2009-08-31 10:13:04 -0400555 int allOK = 1, i;
556 uint64_t firstBlock, lastBlock;
557 BSDData bsdDisklabel;
srs5694fed16d02010-01-27 23:03:40 -0500558 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400559
560 // First, do a test to see if writing will be possible later....
srs5694fed16d02010-01-27 23:03:40 -0500561 err = myDisk.OpenForWrite(deviceFilename);
562 if ((err == 0) && (!justLooking)) {
563 cout << "\aNOTE: Write test failed with error number " << errno
564 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
srs56947dbb9322010-01-20 16:56:30 -0500565#ifdef __FreeBSD__
srs5694fed16d02010-01-27 23:03:40 -0500566 cout << "You may be able to enable writes by exiting this program, typing\n"
567 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
568 << "program.\n";
srs56947dbb9322010-01-20 16:56:30 -0500569#endif
srs5694fed16d02010-01-27 23:03:40 -0500570 cout << "\n";
571// justLooking = 1;
srs56945d58fe02010-01-03 20:57:08 -0500572 } // if
srs5694546a9c72010-01-26 16:00:26 -0500573 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400574
srs5694546a9c72010-01-26 16:00:26 -0500575// if ((fd = open(deviceFilename, O_RDONLY)) != -1) {
576 if (myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400577 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500578 diskSize = myDisk.DiskSize(&err);
579 blockSize = (uint32_t) myDisk.GetBlockSize();
580 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500581 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500582 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400583
srs5694ba00fed2010-01-12 18:18:36 -0500584 whichWasUsed = UseWhichPartitions();
585 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400586 case use_mbr:
587 XFormPartitions();
588 break;
589 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500590 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400591// bsdDisklabel.DisplayBSDData();
592 ClearGPTData();
593 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
594 XFormDisklabel(&bsdDisklabel, 0);
595 break;
596 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500597 mbrState = protectiveMBR.GetValidity();
598 if ((mbrState == invalid) || (mbrState == mbr))
599 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400600 break;
601 case use_new:
602 ClearGPTData();
603 protectiveMBR.MakeProtectiveMBR();
604 break;
srs56943c0af382010-01-15 19:19:18 -0500605 case use_abort:
606 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500607 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500608 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400609 } // switch
610
611 // Now find the first and last sectors used by partitions...
612 if (allOK) {
613 firstBlock = mainHeader.backupLBA; // start high
614 lastBlock = 0; // start low
615 for (i = 0; i < mainHeader.numParts; i++) {
616 if ((partitions[i].GetFirstLBA() < firstBlock) &&
617 (partitions[i].GetFirstLBA() > 0))
618 firstBlock = partitions[i].GetFirstLBA();
619 if (partitions[i].GetLastLBA() > lastBlock)
620 lastBlock = partitions[i].GetLastLBA();
621 } // for
srs56943c0af382010-01-15 19:19:18 -0500622 CheckGPTSize();
srs5694e4ac11e2009-08-31 10:13:04 -0400623 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400624 } else {
625 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500626 cerr << "Problem opening " << deviceFilename << " for reading! Error is "
627 << errno << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400628 if (errno == EACCES) { // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -0500629 cerr << "You must run this program as root or use sudo!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400630 } // if
631 } // if/else
632 return (allOK);
633} // GPTData::LoadPartitions()
634
635// Loads the GPT, as much as possible. Returns 1 if this seems to have
636// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500637int GPTData::ForceLoadGPTData(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400638 int allOK = 1, validHeaders;
639 off_t seekTo;
srs5694fed16d02010-01-27 23:03:40 -0500640 uint8_t* storage;
srs5694e4ac11e2009-08-31 10:13:04 -0400641 uint32_t newCRC, sizeOfParts;
642
643 // Seek to and read the main GPT header
srs5694546a9c72010-01-26 16:00:26 -0500644 if (myDisk.Seek(1)) {
645 if (myDisk.Read(&mainHeader, 512) != 512) { // read main GPT header
srs5694fed16d02010-01-27 23:03:40 -0500646 cerr << "Warning! Error " << errno << " reading main GPT header!\n";
srs5694546a9c72010-01-26 16:00:26 -0500647 } // if read not OK
648 } else allOK = 0; // if/else seek OK
srs5694e4ac11e2009-08-31 10:13:04 -0400649 mainCrcOk = CheckHeaderCRC(&mainHeader);
650 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
651 ReverseHeaderBytes(&mainHeader);
652
srs56943f2fe992009-11-24 18:28:18 -0500653 // Load backup header, check its CRC, and store the results of the
654 // check for future reference. Load backup header using pointer in main
655 // header if possible; but if main header has a CRC error, or if it
656 // points to beyond the end of the disk, load the last sector of the
657 // disk instead.
658 if (mainCrcOk) {
659 if (mainHeader.backupLBA < diskSize) {
srs5694546a9c72010-01-26 16:00:26 -0500660 seekTo = mainHeader.backupLBA;
srs56943f2fe992009-11-24 18:28:18 -0500661 } else {
srs5694546a9c72010-01-26 16:00:26 -0500662 seekTo = diskSize - UINT64_C(1);
srs5694fed16d02010-01-27 23:03:40 -0500663 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
664 << "secondary header from the last sector of the disk! You should use 'v' to\n"
665 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
666 << "the disk.\n";
srs56943f2fe992009-11-24 18:28:18 -0500667 } // else
668 } else {
srs5694546a9c72010-01-26 16:00:26 -0500669 seekTo = diskSize - UINT64_C(1);
srs56943f2fe992009-11-24 18:28:18 -0500670 } // if/else (mainCrcOk)
671
srs5694546a9c72010-01-26 16:00:26 -0500672 if (myDisk.Seek(seekTo)) {
673 if (myDisk.Read(&secondHeader, 512) != 512) { // read secondary GPT header
srs5694fed16d02010-01-27 23:03:40 -0500674 cerr << "Warning! Error " << errno << " reading secondary GPT header!\n";
srs56945d58fe02010-01-03 20:57:08 -0500675 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400676 secondCrcOk = CheckHeaderCRC(&secondHeader);
677 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
678 ReverseHeaderBytes(&secondHeader);
679 } else {
680 allOK = 0;
681 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -0500682 cerr << "Unable to seek to secondary GPT header at sector "
683 << (diskSize - (UINT64_C(1))) << "!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400684 } // if/else lseek
685
686 // Return valid headers code: 0 = both headers bad; 1 = main header
687 // good, backup bad; 2 = backup header good, main header bad;
688 // 3 = both headers good. Note these codes refer to valid GPT
689 // signatures and version numbers; more subtle problems will elude
690 // this check!
691 validHeaders = CheckHeaderValidity();
692
693 // Read partitions (from primary array)
694 if (validHeaders > 0) { // if at least one header is OK....
695 // GPT appears to be valid....
696 state = gpt_valid;
697
698 // We're calling the GPT valid, but there's a possibility that one
699 // of the two headers is corrupt. If so, use the one that seems to
700 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500701 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500702 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
703 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400704 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500705 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400706 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500707 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500708 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
709 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500710 RebuildMainHeader();
711 state = gpt_corrupt;
712 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400713 } // if/else/if
714
srs5694546a9c72010-01-26 16:00:26 -0500715 // Figure out which partition table to load....
716 // Load the main partition table, since either its header's CRC is OK or the
717 // backup header's CRC is not OK....
718 if (mainCrcOk || !secondCrcOk) {
719 if (LoadMainTable() == 0)
720 allOK = 0;
721 } else { // bad main header CRC and backup header CRC is OK
722 state = gpt_corrupt;
723 if (LoadSecondTableAsMain()) {
srs5694fed16d02010-01-27 23:03:40 -0500724 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500725 } else { // backup table bad, bad main header CRC, but try main table in desperation....
726 if (LoadMainTable() == 0) {
727 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500728 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500729 } // if
730 } // if/else (LoadSecondTableAsMain())
731 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400732
733 // Load backup partition table into temporary storage to check
734 // its CRC and store the results, then discard this temporary
735 // storage, since we don't use it in any but recovery operations
srs5694546a9c72010-01-26 16:00:26 -0500736 seekTo = secondHeader.partitionEntriesLBA;
737 if ((myDisk.Seek(seekTo)) && (secondCrcOk)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400738 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -0500739 storage = (uint8_t*) malloc(sizeOfParts);
srs5694546a9c72010-01-26 16:00:26 -0500740 if (myDisk.Read(storage, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500741 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500742 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400743 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
744 free(storage);
745 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
746 } // if
747
srs5694546a9c72010-01-26 16:00:26 -0500748 // Problem with main partition table; if backup is OK, use it instead....
749 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
750 state = gpt_corrupt;
751 allOK = allOK && LoadSecondTableAsMain();
srs5694fed16d02010-01-27 23:03:40 -0500752 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
753 << "partition table\ninstead of main partition table!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500754 } // if
755
srs5694e4ac11e2009-08-31 10:13:04 -0400756 // Check for valid CRCs and warn if there are problems
757 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
758 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500759 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400760 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500761 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400762 } else {
763 state = gpt_invalid;
764 } // if/else
765 return allOK;
766} // GPTData::ForceLoadGPTData()
767
srs5694247657a2009-11-26 18:36:12 -0500768// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400769// main GPT header in memory MUST be valid for this call to do anything
770// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500771// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400772int GPTData::LoadMainTable(void) {
srs5694546a9c72010-01-26 16:00:26 -0500773 int fd, retval = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400774 uint32_t newCRC, sizeOfParts;
775
srs5694546a9c72010-01-26 16:00:26 -0500776 if (myDisk.OpenForRead(device)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400777 // Set internal data structures for number of partitions on the disk
778 SetGPTSize(mainHeader.numParts);
779
780 // Load main partition table, and record whether its CRC
781 // matches the stored value
srs5694546a9c72010-01-26 16:00:26 -0500782 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
783 retval = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400784 sizeOfParts = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694546a9c72010-01-26 16:00:26 -0500785 if (myDisk.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500786 cerr << "Warning! Error " << errno << " when loading the main partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500787 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500788 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400789 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
790 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
791 if (IsLittleEndian() == 0)
792 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500793 } else retval = 0; // if open for read....
srs5694e4ac11e2009-08-31 10:13:04 -0400794 return retval;
795} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400796
797// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500798// table. Used in repair functions, and when starting up if the main
799// partition table is damaged.
800// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
801int GPTData::LoadSecondTableAsMain(void) {
802 uint64_t seekTo;
srs5694e7b4ff92009-08-18 13:16:10 -0400803 uint32_t sizeOfParts, newCRC;
srs5694546a9c72010-01-26 16:00:26 -0500804 int retval = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400805
srs5694546a9c72010-01-26 16:00:26 -0500806 if (myDisk.OpenForRead(device)) {
807 seekTo = secondHeader.partitionEntriesLBA;
808 retval = myDisk.Seek(seekTo);
809 if (retval == 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400810 SetGPTSize(secondHeader.numParts);
811 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694546a9c72010-01-26 16:00:26 -0500812 if (myDisk.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500813 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500814 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500815 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400816 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
817 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs5694e4ac11e2009-08-31 10:13:04 -0400818 mainPartsCrcOk = secondPartsCrcOk;
srs56942a9f5da2009-08-26 00:48:01 -0400819 if (IsLittleEndian() == 0)
820 ReversePartitionBytes();
srs5694e7b4ff92009-08-18 13:16:10 -0400821 if (!secondPartsCrcOk) {
srs5694fed16d02010-01-27 23:03:40 -0500822 cout << "Caution! After loading backup partitions, the CRC still doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400823 } // if
824 } else {
srs5694fed16d02010-01-27 23:03:40 -0500825 cerr << "Error! Couldn't seek to backup partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400826 } // if/else
827 } else {
srs5694fed16d02010-01-27 23:03:40 -0500828 cerr << "Error! Couldn't open device " << device
829 << " when recovering backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500830 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400831 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500832 return retval;
srs5694e7b4ff92009-08-18 13:16:10 -0400833} // GPTData::LoadSecondTableAsMain()
834
srs5694e7b4ff92009-08-18 13:16:10 -0400835// Writes GPT (and protective MBR) to disk. Returns 1 on successful
836// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500837int GPTData::SaveGPTData(int quiet) {
srs5694978041c2009-09-21 20:51:47 -0400838 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400839 char answer, line[256];
srs5694e7b4ff92009-08-18 13:16:10 -0400840 uint64_t secondTable;
srs56942a9f5da2009-08-26 00:48:01 -0400841 uint32_t numParts;
srs5694e7b4ff92009-08-18 13:16:10 -0400842 off_t offset;
843
srs5694fed16d02010-01-27 23:03:40 -0500844 if (device == "") {
845 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400846 } // if
847
848 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500849
850 // This test should only fail on read-only disks....
851 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500852 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500853 allOK = 0;
854 } // if
855
srs5694e7b4ff92009-08-18 13:16:10 -0400856 // Is there enough space to hold the GPT headers and partition tables,
857 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400858 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400859 allOK = 0;
860 } // if
861
862 // Check that disk is really big enough to handle this...
863 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500864 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
865 << "problem (or it might not). Aborting!\n(Disk size is "
866 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400867 allOK = 0;
868 } // if
srs5694247657a2009-11-26 18:36:12 -0500869 // Check that second header is properly placed. Warn and ask if this should
870 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500871 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500872 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
873 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500874 if (GetYN() == 'Y') {
875 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500876 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500877 } else {
srs5694fed16d02010-01-27 23:03:40 -0500878 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500879 } // if correction requested
880 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400881
882 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400883 if (FindOverlaps() > 0) {
884 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500885 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400886 } // if
887
888 // Check for mismatched MBR and GPT data, but let it pass if found
889 // (function displays warning message)
890 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400891
srs56942a9f5da2009-08-26 00:48:01 -0400892 // Pull out some data that's needed before doing byte-order reversal on
893 // big-endian systems....
894 numParts = mainHeader.numParts;
895 secondTable = secondHeader.partitionEntriesLBA;
896 if (IsLittleEndian() == 0) {
897 // Reverse partition bytes first, since that function requires non-reversed
898 // data from the main header....
899 ReversePartitionBytes();
900 ReverseHeaderBytes(&mainHeader);
901 ReverseHeaderBytes(&secondHeader);
902 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400903 RecomputeCRCs();
904
srs5694ba00fed2010-01-12 18:18:36 -0500905 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500906 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
907 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500908 answer = GetYN();
909 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500910 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400911 } else {
912 allOK = 0;
913 } // if/else
914 } // if
915
916 // Do it!
917 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500918 // First, write the protective MBR...
919 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400920
srs5694546a9c72010-01-26 16:00:26 -0500921 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400922 // Now write the main GPT header...
srs5694546a9c72010-01-26 16:00:26 -0500923 if (myDisk.Seek(1) == 1) {
924 if (myDisk.Write(&mainHeader, 512) != 512)
925 allOK = 0;
926 } else allOK = 0; // if (myDisk.Seek()...)
srs5694e7b4ff92009-08-18 13:16:10 -0400927
928 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400929 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500930 offset = mainHeader.partitionEntriesLBA;
931 if (myDisk.Seek(offset)) {
932 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
933 allOK = 0;
934 } else allOK = 0; // if (myDisk.Seek()...)
srs56941e093722010-01-05 00:14:19 -0500935 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400936
937 // Now seek to near the end to write the secondary GPT....
srs5694e4ac11e2009-08-31 10:13:04 -0400938 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500939 offset = (off_t) secondTable;
940 if (myDisk.Seek(offset) != 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400941 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500942 cerr << "Unable to seek to end of disk! Perhaps the 'e' option on the experts' menu\n"
943 << "will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400944 } // if
945 } // if
946
947 // Now write the secondary partition tables....
srs56941e093722010-01-05 00:14:19 -0500948 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500949 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -0400950 allOK = 0;
srs56941e093722010-01-05 00:14:19 -0500951 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400952
953 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500954 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500955 offset = mainHeader.backupLBA;
956 if (myDisk.Seek(offset)) {
957 if (myDisk.Write(&secondHeader, 512) == -1)
srs56941e093722010-01-05 00:14:19 -0500958 allOK = 0;
srs5694546a9c72010-01-26 16:00:26 -0500959 } else allOK = 0; // if (myDisk.Seek()...)
srs56941e093722010-01-05 00:14:19 -0500960 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400961
962 // re-read the partition table
963 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500964 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } // if
966
967 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500968 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400969 } else {
srs5694fed16d02010-01-27 23:03:40 -0500970 cerr << "Warning! An error was reported when writing the partition table! This error\n"
971 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
972 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400973 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500974 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400975 } else {
srs5694fed16d02010-01-27 23:03:40 -0500976 cerr << "Unable to open device " << device << " for writing! Errno is "
977 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400978 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400979 } // if/else
980 } else {
srs5694fed16d02010-01-27 23:03:40 -0500981 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400982 } // if
983
srs56942a9f5da2009-08-26 00:48:01 -0400984 if (IsLittleEndian() == 0) {
985 // Reverse (normalize) header bytes first, since ReversePartitionBytes()
986 // requires non-reversed data in mainHeader...
987 ReverseHeaderBytes(&mainHeader);
988 ReverseHeaderBytes(&secondHeader);
989 ReversePartitionBytes();
990 } // if
991
srs5694e7b4ff92009-08-18 13:16:10 -0400992 return (allOK);
993} // GPTData::SaveGPTData()
994
995// Save GPT data to a backup file. This function does much less error
996// checking than SaveGPTData(). It can therefore preserve many types of
997// corruption for later analysis; however, it preserves only the MBR,
998// the main GPT header, the backup GPT header, and the main partition
999// table; it discards the backup partition table, since it should be
1000// identical to the main partition table on healthy disks.
srs5694fed16d02010-01-27 23:03:40 -05001001int GPTData::SaveGPTBackup(string filename) {
srs56942a9f5da2009-08-26 00:48:01 -04001002 int fd, allOK = 1;
1003 uint32_t numParts;
srs5694546a9c72010-01-26 16:00:26 -05001004 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001005
srs5694546a9c72010-01-26 16:00:26 -05001006// if ((fd = open(filename, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH)) != -1) {
1007 if (backupFile.OpenForWrite(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001008 // Reverse the byte order, if necessary....
1009 numParts = mainHeader.numParts;
1010 if (IsLittleEndian() == 0) {
1011 ReversePartitionBytes();
1012 ReverseHeaderBytes(&mainHeader);
1013 ReverseHeaderBytes(&secondHeader);
1014 } // if
1015
srs5694978041c2009-09-21 20:51:47 -04001016 // Recomputing the CRCs is likely to alter them, which could be bad
1017 // if the intent is to save a potentially bad GPT for later analysis;
1018 // but if we don't do this, we get bogus errors when we load the
1019 // backup. I'm favoring misses over false alarms....
1020 RecomputeCRCs();
1021
srs56942a9f5da2009-08-26 00:48:01 -04001022 // Now write the protective MBR...
srs5694546a9c72010-01-26 16:00:26 -05001023 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001024
1025 // Now write the main GPT header...
1026 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001027 // MBR write closed disk, so re-open and seek to end....
1028 backupFile.OpenForWrite();
1029 backupFile.Seek(1);
1030 if (backupFile.Write(&mainHeader, 512) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001031 allOK = 0;
1032
1033 // Now write the secondary GPT header...
1034 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001035 if (backupFile.Write(&secondHeader, 512) == -1)
srs5694e4ac11e2009-08-31 10:13:04 -04001036 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001037
1038 // Now write the main partition tables...
1039 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001040 if (backupFile.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001041 allOK = 0;
1042 } // if
1043
1044 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001045 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001046 } else {
srs5694fed16d02010-01-27 23:03:40 -05001047 cerr << "Warning! An error was reported when writing the backup file.\n"
1048 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001049 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001050 backupFile.Close();
srs56942a9f5da2009-08-26 00:48:01 -04001051
1052 // Now reverse the byte-order reversal, if necessary....
1053 if (IsLittleEndian() == 0) {
1054 ReverseHeaderBytes(&mainHeader);
1055 ReverseHeaderBytes(&secondHeader);
1056 ReversePartitionBytes();
1057 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001058 } else {
srs5694fed16d02010-01-27 23:03:40 -05001059 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001060 allOK = 0;
1061 } // if/else
1062 return allOK;
1063} // GPTData::SaveGPTBackup()
1064
1065// Load GPT data from a backup file created by SaveGPTBackup(). This function
1066// does minimal error checking. It returns 1 if it completed successfully,
1067// 0 if there was a problem. In the latter case, it creates a new empty
1068// set of partitions.
srs5694fed16d02010-01-27 23:03:40 -05001069int GPTData::LoadGPTBackup(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -04001070 int fd, allOK = 1, val;
1071 uint32_t numParts, sizeOfEntries, sizeOfParts, newCRC;
srs56942a9f5da2009-08-26 00:48:01 -04001072 int littleEndian = 1;
srs5694546a9c72010-01-26 16:00:26 -05001073 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001074
srs5694546a9c72010-01-26 16:00:26 -05001075// if ((fd = open(filename, O_RDONLY)) != -1) {
1076 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001077 if (IsLittleEndian() == 0)
1078 littleEndian = 0;
1079
srs5694e7b4ff92009-08-18 13:16:10 -04001080 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001081 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001082
1083 // Load the main GPT header, check its vaility, and set the GPT
1084 // size based on the data
srs5694546a9c72010-01-26 16:00:26 -05001085 if (backupFile.Read(&mainHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001086 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001087 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001088 mainCrcOk = CheckHeaderCRC(&mainHeader);
1089
srs56942a9f5da2009-08-26 00:48:01 -04001090 // Reverse byte order, if necessary
1091 if (littleEndian == 0) {
1092 ReverseHeaderBytes(&mainHeader);
1093 } // if
1094
srs5694e7b4ff92009-08-18 13:16:10 -04001095 // Load the backup GPT header in much the same way as the main
1096 // GPT header....
srs5694546a9c72010-01-26 16:00:26 -05001097 if (backupFile.Read(&secondHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001098 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001099 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001100 secondCrcOk = CheckHeaderCRC(&secondHeader);
1101
srs56942a9f5da2009-08-26 00:48:01 -04001102 // Reverse byte order, if necessary
1103 if (littleEndian == 0) {
1104 ReverseHeaderBytes(&secondHeader);
1105 } // if
1106
srs5694e7b4ff92009-08-18 13:16:10 -04001107 // Return valid headers code: 0 = both headers bad; 1 = main header
1108 // good, backup bad; 2 = backup header good, main header bad;
1109 // 3 = both headers good. Note these codes refer to valid GPT
1110 // signatures and version numbers; more subtle problems will elude
1111 // this check!
1112 if ((val = CheckHeaderValidity()) > 0) {
1113 if (val == 2) { // only backup header seems to be good
1114 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001115 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001116 } else { // main header is OK
1117 numParts = mainHeader.numParts;
1118 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1119 } // if/else
1120
1121 SetGPTSize(numParts);
1122
1123 // If current disk size doesn't match that of backup....
1124 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001125 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1126 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001127 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001128 } // if
1129
1130 // Load main partition table, and record whether its CRC
1131 // matches the stored value
1132 sizeOfParts = numParts * sizeOfEntries;
srs5694546a9c72010-01-26 16:00:26 -05001133 if (backupFile.Read(partitions, sizeOfParts) != sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -05001134 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001135 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001136
1137 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
1138 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
1139 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -04001140 // Reverse byte order, if necessary
srs5694e4ac11e2009-08-31 10:13:04 -04001141 if (littleEndian == 0) {
1142 ReversePartitionBytes();
1143 } // if
srs56942a9f5da2009-08-26 00:48:01 -04001144
srs5694e7b4ff92009-08-18 13:16:10 -04001145 } else {
1146 allOK = 0;
1147 } // if/else
1148 } else {
1149 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001150 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001151 } // if/else
1152
1153 // Something went badly wrong, so blank out partitions
1154 if (allOK == 0) {
1155 ClearGPTData();
1156 protectiveMBR.MakeProtectiveMBR();
1157 } // if
1158 return allOK;
1159} // GPTData::LoadGPTBackup()
1160
srs5694e4ac11e2009-08-31 10:13:04 -04001161// Tell user whether Apple Partition Map (APM) was discovered....
1162void GPTData::ShowAPMState(void) {
1163 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001164 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001165 else
srs5694fed16d02010-01-27 23:03:40 -05001166 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001167} // GPTData::ShowAPMState()
1168
1169// Tell user about the state of the GPT data....
1170void GPTData::ShowGPTState(void) {
1171 switch (state) {
1172 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001173 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001174 break;
1175 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001176 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001177 break;
1178 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001179 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001180 break;
1181 default:
srs5694fed16d02010-01-27 23:03:40 -05001182 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001183 break;
1184 } // switch
1185} // GPTData::ShowGPTState()
1186
1187// Display the basic GPT data
1188void GPTData::DisplayGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001189 int i;
srs5694fed16d02010-01-27 23:03:40 -05001190// char tempStr[255];
srs5694e4ac11e2009-08-31 10:13:04 -04001191 uint64_t temp, totalFree;
1192
srs5694fed16d02010-01-27 23:03:40 -05001193 cout << "Disk " << device << ": " << diskSize << " sectors, "
1194 << BytesToSI(diskSize * blockSize) << "\n";
1195 cout << "Logical sector size: " << blockSize << " bytes\n";
1196 cout << "Disk identifier (GUID): " << GUIDToStr(mainHeader.diskGUID) << "\n";
1197 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1198 cout << "First usable sector is " << mainHeader.firstUsableLBA
1199 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001200 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001201 cout << "Total free space is " << totalFree << " sectors ("
1202 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1203 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001204 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001205 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001206 } // for
1207} // GPTData::DisplayGPTData()
1208
1209// Get partition number from user and then call ShowPartDetails(partNum)
1210// to show its detailed information
1211void GPTData::ShowDetails(void) {
1212 int partNum;
1213 uint32_t low, high;
1214
1215 if (GetPartRange(&low, &high) > 0) {
1216 partNum = GetPartNum();
1217 ShowPartDetails(partNum);
1218 } else {
srs5694fed16d02010-01-27 23:03:40 -05001219 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001220 } // if/else
1221} // GPTData::ShowDetails()
1222
1223// Show detailed information on the specified partition
1224void GPTData::ShowPartDetails(uint32_t partNum) {
1225 if (partitions[partNum].GetFirstLBA() != 0) {
1226 partitions[partNum].ShowDetails(blockSize);
1227 } else {
srs5694fed16d02010-01-27 23:03:40 -05001228 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001229 } // if
1230} // GPTData::ShowPartDetails()
1231
1232/*********************************************************************
1233 * *
1234 * Begin functions that obtain information from the users, and often *
1235 * do something with that information (call other functions) *
1236 * *
1237 *********************************************************************/
1238
1239// Prompts user for partition number and returns the result.
1240uint32_t GPTData::GetPartNum(void) {
1241 uint32_t partNum;
1242 uint32_t low, high;
1243 char prompt[255];
1244
1245 if (GetPartRange(&low, &high) > 0) {
1246 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1247 partNum = GetNumber(low + 1, high + 1, low, prompt);
1248 } else partNum = 1;
1249 return (partNum - 1);
1250} // GPTData::GetPartNum()
1251
1252// What it says: Resize the partition table. (Default is 128 entries.)
1253void GPTData::ResizePartitionTable(void) {
1254 int newSize;
1255 char prompt[255];
1256 uint32_t curLow, curHigh;
1257
srs5694fed16d02010-01-27 23:03:40 -05001258 cout << "Current partition table size is " << mainHeader.numParts << ".\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001259 GetPartRange(&curLow, &curHigh);
1260 curHigh++; // since GetPartRange() returns numbers starting from 0...
1261 // There's no point in having fewer than four partitions....
1262 if (curHigh < 4)
1263 curHigh = 4;
1264 sprintf(prompt, "Enter new size (%d up, default %d): ", (int) curHigh,
1265 (int) NUM_GPT_ENTRIES);
1266 newSize = GetNumber(4, 65535, 128, prompt);
1267 if (newSize < 128) {
srs5694fed16d02010-01-27 23:03:40 -05001268 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
1269 << "which works out to 128 entries. In practice, smaller tables seem to\n"
1270 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
1271 << "the resize, but you may want to reconsider this action and undo it.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001272 } // if
1273 SetGPTSize(newSize);
1274} // GPTData::ResizePartitionTable()
1275
1276// Interactively create a partition
1277void GPTData::CreatePartition(void) {
1278 uint64_t firstBlock, firstInLargest, lastBlock, sector;
1279 char prompt[255];
1280 int partNum, firstFreePart = 0;
1281
1282 // Find first free partition...
1283 while (partitions[firstFreePart].GetFirstLBA() != 0) {
1284 firstFreePart++;
1285 } // while
1286
1287 if (((firstBlock = FindFirstAvailable()) != 0) &&
1288 (firstFreePart < mainHeader.numParts)) {
1289 lastBlock = FindLastAvailable(firstBlock);
1290 firstInLargest = FindFirstInLargest();
1291
1292 // Get partition number....
1293 do {
1294 sprintf(prompt, "Partition number (%d-%d, default %d): ", firstFreePart + 1,
1295 mainHeader.numParts, firstFreePart + 1);
1296 partNum = GetNumber(firstFreePart + 1, mainHeader.numParts,
1297 firstFreePart + 1, prompt) - 1;
1298 if (partitions[partNum].GetFirstLBA() != 0)
srs5694fed16d02010-01-27 23:03:40 -05001299 cout << "partition " << partNum + 1 << " is in use.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001300 } while (partitions[partNum].GetFirstLBA() != 0);
1301
1302 // Get first block for new partition...
srs56945d58fe02010-01-03 20:57:08 -05001303 sprintf(prompt, "First sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1304 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1305 (unsigned long long) firstInLargest);
srs5694e4ac11e2009-08-31 10:13:04 -04001306 do {
1307 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt);
1308 } while (IsFree(sector) == 0);
srs56941d1448a2009-12-31 21:20:19 -05001309 Align(&sector); // Align sector to correct multiple
srs5694e4ac11e2009-08-31 10:13:04 -04001310 firstBlock = sector;
1311
1312 // Get last block for new partitions...
1313 lastBlock = FindLastInFree(firstBlock);
srs56945d58fe02010-01-03 20:57:08 -05001314 sprintf(prompt, "Last sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1315 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1316 (unsigned long long) lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001317 do {
1318 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, prompt);
1319 } while (IsFree(sector) == 0);
1320 lastBlock = sector;
1321
srs5694ba00fed2010-01-12 18:18:36 -05001322 firstFreePart = CreatePartition(partNum, firstBlock, lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001323 partitions[partNum].ChangeType();
srs5694fed16d02010-01-27 23:03:40 -05001324 partitions[partNum].SetName(partitions[partNum].GetNameType());
srs5694ba00fed2010-01-12 18:18:36 -05001325 } else {
srs5694fed16d02010-01-27 23:03:40 -05001326 cout << "No free sectors available\n";
srs5694ba00fed2010-01-12 18:18:36 -05001327 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001328} // GPTData::CreatePartition()
1329
1330// Interactively delete a partition (duh!)
1331void GPTData::DeletePartition(void) {
1332 int partNum;
1333 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001334 char prompt[255];
1335
1336 if (GetPartRange(&low, &high) > 0) {
1337 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1338 partNum = GetNumber(low + 1, high + 1, low, prompt);
srs5694ba00fed2010-01-12 18:18:36 -05001339 DeletePartition(partNum - 1);
srs5694e4ac11e2009-08-31 10:13:04 -04001340 } else {
srs5694fed16d02010-01-27 23:03:40 -05001341 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001342 } // if/else
1343} // GPTData::DeletePartition()
1344
1345// Prompt user for a partition number, then change its type code
1346// using ChangeGPTType(struct GPTPartition*) function.
1347void GPTData::ChangePartType(void) {
1348 int partNum;
1349 uint32_t low, high;
1350
1351 if (GetPartRange(&low, &high) > 0) {
1352 partNum = GetPartNum();
1353 partitions[partNum].ChangeType();
1354 } else {
srs5694fed16d02010-01-27 23:03:40 -05001355 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001356 } // if/else
1357} // GPTData::ChangePartType()
1358
1359// Partition attributes seem to be rarely used, but I want a way to
1360// adjust them for completeness....
1361void GPTData::SetAttributes(uint32_t partNum) {
1362 Attributes theAttr;
1363
1364 theAttr.SetAttributes(partitions[partNum].GetAttributes());
1365 theAttr.DisplayAttributes();
1366 theAttr.ChangeAttributes();
1367 partitions[partNum].SetAttributes(theAttr.GetAttributes());
1368} // GPTData::SetAttributes()
1369
srs5694c0ca8f82009-08-20 21:35:25 -04001370// This function destroys the on-disk GPT structures. Returns 1 if the
1371// user confirms destruction, 0 if the user aborts.
srs5694978041c2009-09-21 20:51:47 -04001372// If prompt == 0, don't ask user about proceeding and do NOT wipe out
1373// MBR. (Set prompt == 0 when doing a GPT-to-MBR conversion.)
srs5694ba00fed2010-01-12 18:18:36 -05001374// If prompt == -1, don't ask user about proceeding and DO wipe out
1375// MBR.
srs5694978041c2009-09-21 20:51:47 -04001376int GPTData::DestroyGPT(int prompt) {
srs56941e093722010-01-05 00:14:19 -05001377 int fd, i, sum, tableSize;
srs5694fed16d02010-01-27 23:03:40 -05001378 uint8_t blankSector[512], goOn = 'Y', blank = 'N';
1379 uint8_t* emptyTable;
srs5694c0ca8f82009-08-20 21:35:25 -04001380
1381 for (i = 0; i < 512; i++) {
srs5694fed16d02010-01-27 23:03:40 -05001382 blankSector[i] = 0;
srs5694c0ca8f82009-08-20 21:35:25 -04001383 } // for
1384
srs5694ba00fed2010-01-12 18:18:36 -05001385 if (((apmFound) || (bsdFound)) && (prompt > 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001386 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
1387 << "damage any APM or BSD partitions on this disk!\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001388 } // if APM or BSD
srs5694ba00fed2010-01-12 18:18:36 -05001389 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001390 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
srs5694978041c2009-09-21 20:51:47 -04001391 goOn = GetYN();
1392 } // if
srs5694c0ca8f82009-08-20 21:35:25 -04001393 if (goOn == 'Y') {
srs5694546a9c72010-01-26 16:00:26 -05001394 if (myDisk.OpenForWrite(device)) {
1395 myDisk.Seek(mainHeader.currentLBA); // seek to GPT header
1396 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001397 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001398 } // if
srs5694546a9c72010-01-26 16:00:26 -05001399 myDisk.Seek(mainHeader.partitionEntriesLBA); // seek to partition table
srs56941e093722010-01-05 00:14:19 -05001400 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -05001401 emptyTable = (uint8_t*) malloc(tableSize);
srs56941e093722010-01-05 00:14:19 -05001402 for (i = 0; i < tableSize; i++)
srs5694fed16d02010-01-27 23:03:40 -05001403 emptyTable[i] = 0;
srs5694546a9c72010-01-26 16:00:26 -05001404 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001405 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001406 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001407 myDisk.Seek(secondHeader.partitionEntriesLBA); // seek to partition table
1408 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001409 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001410 cerr << "Warning! GPT backup partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001411 myDisk.Seek(secondHeader.currentLBA); // seek to GPT header
1412 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001413 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001414 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001415 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001416 cout << "Blank out MBR? ";
srs5694978041c2009-09-21 20:51:47 -04001417 blank = GetYN();
srs5694ba00fed2010-01-12 18:18:36 -05001418 } // if
srs5694978041c2009-09-21 20:51:47 -04001419 // Note on below: Touch the MBR only if the user wants it completely
1420 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
1421 // the MBR, but this could wipe out a valid MBR that the program
1422 // had subsequently discarded (say, if it conflicted with older GPT
1423 // structures).
srs5694ba00fed2010-01-12 18:18:36 -05001424 if ((blank == 'Y') || (prompt < 0)) {
srs5694546a9c72010-01-26 16:00:26 -05001425 myDisk.Seek(0);
1426 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001427 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
srs56945d58fe02010-01-03 20:57:08 -05001428 } // if
srs5694978041c2009-09-21 20:51:47 -04001429 } else {
srs5694fed16d02010-01-27 23:03:40 -05001430 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
1431 << "with fdisk or another tool.\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001432 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001433 myDisk.DiskSync();
1434 myDisk.Close();
srs5694fed16d02010-01-27 23:03:40 -05001435 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1436 << "other utilities. Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001437 } else {
srs5694fed16d02010-01-27 23:03:40 -05001438 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001439 } // if/else (fd != -1)
1440 } // if (goOn == 'Y')
1441 return (goOn == 'Y');
1442} // GPTData::DestroyGPT()
1443
srs5694e4ac11e2009-08-31 10:13:04 -04001444/**************************************************************************
1445 * *
1446 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1447 * (some of these functions may require user interaction) *
1448 * *
1449 **************************************************************************/
1450
1451// Examines the MBR & GPT data, and perhaps asks the user questions, to
1452// determine which set of data to use: the MBR (use_mbr), the GPT (use_gpt),
1453// or create a new set of partitions (use_new)
1454WhichToUse GPTData::UseWhichPartitions(void) {
1455 WhichToUse which = use_new;
1456 MBRValidity mbrState;
1457 int answer;
1458
1459 mbrState = protectiveMBR.GetValidity();
1460
1461 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001462 cout << "\n***************************************************************\n"
1463 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001464 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001465 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1466 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001467 } // if
srs5694fed16d02010-01-27 23:03:40 -05001468 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001469 which = use_mbr;
1470 } // if
1471
1472 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001473 cout << "\n**********************************************************************\n"
1474 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1475 << "to GPT format.";
srs56945d58fe02010-01-03 20:57:08 -05001476 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001477 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1478 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1479 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001480 } // if
srs5694fed16d02010-01-27 23:03:40 -05001481 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001482 which = use_bsd;
1483 } // if
1484
1485 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001486 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001487 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001488 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001489 } // if
1490 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001491 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001492 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001493 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001494 } // if
1495 if ((state == gpt_valid) && (mbrState == invalid)) {
srs5694fed16d02010-01-27 23:03:40 -05001496 cout << "\aFound valid GPT with corrupt MBR; using GPT and will create new\n"
1497 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001498 which = use_gpt;
1499 protectiveMBR.MakeProtectiveMBR();
1500 } // if
1501 if ((state == gpt_valid) && (mbrState == mbr)) {
srs56943c0af382010-01-15 19:19:18 -05001502 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -05001503 cout << "Found valid MBR and GPT. Which do you want to use?\n";
1504 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001505 if (answer == 1) {
1506 which = use_mbr;
1507 } else if (answer == 2) {
1508 which = use_gpt;
1509 protectiveMBR.MakeProtectiveMBR();
srs5694fed16d02010-01-27 23:03:40 -05001510 cout << "Using GPT and creating fresh protective MBR.\n";
srs56943c0af382010-01-15 19:19:18 -05001511 } else which = use_new;
1512 } else which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001513 } // if
1514
1515 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
1516 // problems)
1517 if (state == gpt_corrupt) {
srs56943c0af382010-01-15 19:19:18 -05001518 if (beQuiet) {
1519 which = use_abort;
1520 } else {
1521 if ((mbrState == mbr) || (mbrState == hybrid)) {
srs5694fed16d02010-01-27 23:03:40 -05001522 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
1523 << "GPT MAY permit recovery of GPT data.)\n";
1524 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001525 if (answer == 1) {
1526 which = use_mbr;
srs56943c0af382010-01-15 19:19:18 -05001527 } else if (answer == 2) {
1528 which = use_gpt;
1529 } else which = use_new;
1530 } else if (mbrState == invalid) {
srs5694fed16d02010-01-27 23:03:40 -05001531 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
1532 << "GPT MAY permit recovery of GPT data.)\n";
1533 answer = GetNumber(1, 2, 1, " 1 - GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001534 if (answer == 1) {
1535 which = use_gpt;
1536 } else which = use_new;
1537 } else { // corrupt GPT, MBR indicates it's a GPT disk....
srs5694fed16d02010-01-27 23:03:40 -05001538 cout << "\a\a****************************************************************************\n"
1539 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1540 << "verification and recovery are STRONGLY recommended.\n"
1541 << "****************************************************************************\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001542 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001543 } // if/else/else
1544 } // else (beQuiet)
srs5694e4ac11e2009-08-31 10:13:04 -04001545 } // if (corrupt GPT)
1546
1547 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001548 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001549
1550 return which;
1551} // UseWhichPartitions()
1552
1553// Convert MBR partition table into GPT form
1554int GPTData::XFormPartitions(void) {
1555 int i, numToConvert;
1556 uint8_t origType;
1557 struct newGUID;
srs5694e4ac11e2009-08-31 10:13:04 -04001558
1559 // Clear out old data & prepare basics....
1560 ClearGPTData();
1561
1562 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001563 if (mainHeader.numParts > (MAX_MBR_PARTS))
1564 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001565 else
1566 numToConvert = mainHeader.numParts;
1567
1568 for (i = 0; i < numToConvert; i++) {
1569 origType = protectiveMBR.GetType(i);
1570 // don't waste CPU time trying to convert extended, hybrid protective, or
1571 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001572 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs5694e4ac11e2009-08-31 10:13:04 -04001573 (origType != 0x00) && (origType != 0xEE))
1574 partitions[i] = protectiveMBR.AsGPT(i);
1575 } // for
1576
1577 // Convert MBR into protective MBR
1578 protectiveMBR.MakeProtectiveMBR();
1579
1580 // Record that all original CRCs were OK so as not to raise flags
1581 // when doing a disk verification
1582 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1583
1584 return (1);
1585} // GPTData::XFormPartitions()
1586
1587// Transforms BSD disklabel on the specified partition (numbered from 0).
1588// If an invalid partition number is given, the program prompts for one.
1589// Returns the number of new partitions created.
1590int GPTData::XFormDisklabel(int i) {
1591 uint32_t low, high, partNum, startPart;
1592 uint16_t hexCode;
1593 int goOn = 1, numDone = 0;
1594 BSDData disklabel;
1595
1596 if (GetPartRange(&low, &high) != 0) {
1597 if ((i < low) || (i > high))
1598 partNum = GetPartNum();
1599 else
1600 partNum = (uint32_t) i;
1601
1602 // Find the partition after the last used one
1603 startPart = high + 1;
1604
1605 // Now see if the specified partition has a BSD type code....
1606 hexCode = partitions[partNum].GetHexType();
1607 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
srs5694fed16d02010-01-27 23:03:40 -05001608 cout << "Specified partition doesn't have a disklabel partition type "
1609 << "code.\nContinue anyway? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001610 goOn = (GetYN() == 'Y');
1611 } // if
1612
1613 // If all is OK, read the disklabel and convert it.
1614 if (goOn) {
srs5694fed16d02010-01-27 23:03:40 -05001615 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
srs5694e4ac11e2009-08-31 10:13:04 -04001616 partitions[partNum].GetLastLBA());
1617 if ((goOn) && (disklabel.IsDisklabel())) {
1618 numDone = XFormDisklabel(&disklabel, startPart);
1619 if (numDone == 1)
srs5694fed16d02010-01-27 23:03:40 -05001620 cout << "Converted " << numDone << " BSD partition.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001621 else
srs5694fed16d02010-01-27 23:03:40 -05001622 cout << "Converted " << numDone << " BSD partitions.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001623 } else {
srs5694fed16d02010-01-27 23:03:40 -05001624 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001625 } // if/else
1626 } // if
1627 if (numDone > 0) { // converted partitions; delete carrier
1628 partitions[partNum].BlankPartition();
1629 } // if
1630 } else {
srs5694fed16d02010-01-27 23:03:40 -05001631 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001632 } // if/else
1633 return numDone;
1634} // GPTData::XFormDisklable(int i)
1635
1636// Transform the partitions on an already-loaded BSD disklabel...
1637int GPTData::XFormDisklabel(BSDData* disklabel, int startPart) {
1638 int i, numDone = 0;
1639
1640 if ((disklabel->IsDisklabel()) && (startPart >= 0) &&
1641 (startPart < mainHeader.numParts)) {
1642 for (i = 0; i < disklabel->GetNumParts(); i++) {
1643 partitions[i + startPart] = disklabel->AsGPT(i);
1644 if (partitions[i + startPart].GetFirstLBA() != UINT64_C(0))
1645 numDone++;
1646 } // for
1647 } // if
1648
1649 // Record that all original CRCs were OK so as not to raise flags
1650 // when doing a disk verification
1651 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1652
1653 return numDone;
1654} // GPTData::XFormDisklabel(BSDData* disklabel)
1655
srs5694978041c2009-09-21 20:51:47 -04001656// Add one GPT partition to MBR. Used by XFormToMBR() and MakeHybrid()
1657// functions. Returns 1 if operation was successful.
1658int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1659 int allOK = 1, typeCode, bootable;
1660 uint64_t length;
1661 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001662 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001663
srs5694fed16d02010-01-27 23:03:40 -05001664 cout.setf(ios::uppercase);
1665 cout.fill('0');
1666
srs5694978041c2009-09-21 20:51:47 -04001667 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001668 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001669 allOK = 0;
1670 } // if
1671 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001672 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001673 allOK = 0;
1674 } // if
1675 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001676 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001677 allOK = 0;
1678 } // if
1679 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1680 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1681 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001682 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1683 << " some OSes may\nreact strangely.\n";
srs5694978041c2009-09-21 20:51:47 -04001684 } // if partition ends past 32-bit (usually 2TiB) boundary
1685 do {
srs5694fed16d02010-01-27 23:03:40 -05001686 cout << "Enter an MBR hex code (default " << hex;
1687 cout.width(2);
1688 cout << typeHelper.GUIDToID(partitions[gptPart].GetType()) / 256 << "): ";
srs56945d58fe02010-01-03 20:57:08 -05001689 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001690 if (line[0] == '\n')
1691 typeCode = partitions[gptPart].GetHexType() / 256;
srs5694fed16d02010-01-27 23:03:40 -05001692 else
1693 sscanf(line, "%x", &typeCode);
srs5694978041c2009-09-21 20:51:47 -04001694 } while ((typeCode <= 0) || (typeCode > 255));
srs5694fed16d02010-01-27 23:03:40 -05001695 cout << "Set the bootable flag? ";
srs5694978041c2009-09-21 20:51:47 -04001696 bootable = (GetYN() == 'Y');
1697 length = partitions[gptPart].GetLengthLBA();
1698 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1699 (uint32_t) length, typeCode, bootable);
1700 } else { // partition out of range
srs5694fed16d02010-01-27 23:03:40 -05001701 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1702 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001703 allOK = 0;
1704 } // if/else
srs5694fed16d02010-01-27 23:03:40 -05001705 cout.fill(' ');
srs5694978041c2009-09-21 20:51:47 -04001706 return allOK;
1707} // GPTData::OnePartToMBR()
1708
1709// Convert the GPT to MBR form. This function is necessarily limited; it
1710// handles at most four partitions and creates layouts that ignore CHS
1711// geometries. Returns the number of converted partitions; if this value
1712// is over 0, the calling function should call DestroyGPT() to destroy
1713// the GPT data, and then exit.
1714int GPTData::XFormToMBR(void) {
1715 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001716 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001717 int i, j, numParts, numConverted = 0;
1718 uint32_t partNums[4];
1719
1720 // Get the numbers of up to four partitions to add to the
1721 // hybrid MBR....
1722 numParts = CountParts();
srs5694fed16d02010-01-27 23:03:40 -05001723 cout << "Counted " << numParts << " partitions.\n";
srs5694978041c2009-09-21 20:51:47 -04001724
1725 // Prepare the MBR for conversion (empty it of existing partitions).
1726 protectiveMBR.EmptyMBR(0);
1727 protectiveMBR.SetDiskSize(diskSize);
1728
1729 if (numParts > 4) { // Over four partitions; engage in triage
srs5694fed16d02010-01-27 23:03:40 -05001730 cout << "Type from one to four GPT partition numbers, separated by spaces, to be\n"
1731 << "used in the MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001732 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001733 numParts = sscanf(line, "%d %d %d %d", &partNums[0], &partNums[1],
1734 &partNums[2], &partNums[3]);
1735 } else { // Four or fewer partitions; convert them all
1736 i = j = 0;
1737 while ((j < numParts) && (i < mainHeader.numParts)) {
1738 if (partitions[i].GetFirstLBA() > 0) { // if GPT part. is defined
1739 partNums[j++] = ++i; // flag it for conversion
1740 } else i++;
1741 } // while
1742 } // if/else
1743
1744 for (i = 0; i < numParts; i++) {
1745 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001746 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001747 numConverted += OnePartToMBR(j, i);
1748 } // for
srs5694fed16d02010-01-27 23:03:40 -05001749 cout << "MBR writing returned " << protectiveMBR.WriteMBRData(&myDisk) << "\n";
srs5694978041c2009-09-21 20:51:47 -04001750 return numConverted;
1751} // GPTData::XFormToMBR()
1752
srs5694e4ac11e2009-08-31 10:13:04 -04001753// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
1754// OSes that don't understand GPT.
1755void GPTData::MakeHybrid(void) {
1756 uint32_t partNums[3];
1757 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001758 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001759 int numParts, numConverted = 0, i, j, typeCode, mbrNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001760 char fillItUp = 'M'; // fill extra partition entries? (Yes/No/Maybe)
srs5694978041c2009-09-21 20:51:47 -04001761 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
srs5694e4ac11e2009-08-31 10:13:04 -04001762
srs5694fed16d02010-01-27 23:03:40 -05001763 cout << "\nWARNING! Hybrid MBRs are flaky and potentially dangerous! If you decide not\n"
1764 << "to use one, just hit the Enter key at the below prompt and your MBR\n"
1765 << "partition table will be untouched.\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -04001766
1767 // Now get the numbers of up to three partitions to add to the
1768 // hybrid MBR....
srs5694fed16d02010-01-27 23:03:40 -05001769 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
1770 << "added to the hybrid MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001771 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001772 numParts = sscanf(line, "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
1773
1774 if (numParts > 0) {
1775 // Blank out the protective MBR, but leave the boot loader code
1776 // alone....
1777 protectiveMBR.EmptyMBR(0);
1778 protectiveMBR.SetDiskSize(diskSize);
srs5694fed16d02010-01-27 23:03:40 -05001779 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001780 eeFirst = GetYN();
1781 } // if
1782
1783 for (i = 0; i < numParts; i++) {
1784 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001785 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001786 if (eeFirst == 'Y')
1787 mbrNum = i + 1;
1788 else
1789 mbrNum = i;
1790 numConverted += OnePartToMBR(j, mbrNum);
srs5694e4ac11e2009-08-31 10:13:04 -04001791 } // for
1792
srs5694978041c2009-09-21 20:51:47 -04001793 if ((numParts > 0) && (numConverted > 0)) { // User opted to create a hybrid MBR....
srs5694e4ac11e2009-08-31 10:13:04 -04001794 // Create EFI protective partition that covers the start of the disk.
1795 // If this location (covering the main GPT data structures) is omitted,
1796 // Linux won't find any partitions on the disk. Note that this is
1797 // NUMBERED AFTER the hybrid partitions, contrary to what the
1798 // gptsync utility does. This is because Windows seems to choke on
1799 // disks with a 0xEE partition in the first slot and subsequent
1800 // additional partitions, unless it boots from the disk.
1801 if (eeFirst == 'Y')
1802 mbrNum = 0;
1803 else
1804 mbrNum = numParts;
1805 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), 0xEE);
srs5694978041c2009-09-21 20:51:47 -04001806 protectiveMBR.SetHybrid();
srs5694e4ac11e2009-08-31 10:13:04 -04001807
1808 // ... and for good measure, if there are any partition spaces left,
1809 // optionally create another protective EFI partition to cover as much
1810 // space as possible....
1811 for (i = 0; i < 4; i++) {
1812 if (protectiveMBR.GetType(i) == 0x00) { // unused entry....
1813 if (fillItUp == 'M') {
srs5694fed16d02010-01-27 23:03:40 -05001814 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001815 fillItUp = GetYN();
1816 typeCode = 0x00; // use this to flag a need to get type code
1817 } // if
1818 if (fillItUp == 'Y') {
1819 while ((typeCode <= 0) || (typeCode > 255)) {
srs5694fed16d02010-01-27 23:03:40 -05001820 cout << "Enter an MBR hex code (EE is EFI GPT, but may confuse MacOS): ";
srs5694e4ac11e2009-08-31 10:13:04 -04001821 // Comment on above: Mac OS treats disks with more than one
1822 // 0xEE MBR partition as MBR disks, not as GPT disks.
srs56945d58fe02010-01-03 20:57:08 -05001823 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001824 sscanf(line, "%x", &typeCode);
1825 if (line[0] == '\n')
1826 typeCode = 0;
1827 } // while
1828 protectiveMBR.MakeBiggestPart(i, typeCode); // make a partition
1829 } // if (fillItUp == 'Y')
1830 } // if unused entry
1831 } // for (i = 0; i < 4; i++)
1832 } // if (numParts > 0)
1833} // GPTData::MakeHybrid()
1834
1835/**********************************************************************
1836 * *
1837 * Functions that adjust GPT data structures WITHOUT user interaction *
1838 * (they may display information for the user's benefit, though) *
1839 * *
1840 **********************************************************************/
1841
1842// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001843// necessary, copies data if it already exists. Returns 1 if all goes
1844// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001845int GPTData::SetGPTSize(uint32_t numEntries) {
1846 struct GPTPart* newParts;
1847 struct GPTPart* trash;
1848 uint32_t i, high, copyNum;
1849 int allOK = 1;
1850
1851 // First, adjust numEntries upward, if necessary, to get a number
1852 // that fills the allocated sectors
1853 i = blockSize / GPT_SIZE;
1854 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001855 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001856 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001857 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001858 } // if
1859
srs5694247657a2009-11-26 18:36:12 -05001860 // Do the work only if the # of partitions is changing. Along with being
1861 // efficient, this prevents mucking the with location of the secondary
1862 // partition table, which causes problems when loading data from a RAID
1863 // array that's been expanded because this function is called when loading
1864 // data.
srs5694546a9c72010-01-26 16:00:26 -05001865 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1866 || (partitions == NULL)) {
srs5694247657a2009-11-26 18:36:12 -05001867 newParts = (GPTPart*) calloc(numEntries, sizeof (GPTPart));
1868 if (newParts != NULL) {
1869 if (partitions != NULL) { // existing partitions; copy them over
1870 GetPartRange(&i, &high);
1871 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001872 cout << "The highest-numbered partition is " << high + 1
1873 << ", which is greater than the requested\n"
1874 << "partition table size of " << numEntries
1875 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001876 allOK = 0;
1877 } else { // go ahead with copy
1878 if (numEntries < mainHeader.numParts)
1879 copyNum = numEntries;
1880 else
1881 copyNum = mainHeader.numParts;
1882 for (i = 0; i < copyNum; i++) {
1883 newParts[i] = partitions[i];
1884 } // for
1885 trash = partitions;
1886 partitions = newParts;
1887 free(trash);
1888 } // if
1889 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001890 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001891 } // if/else existing partitions
1892 mainHeader.numParts = numEntries;
1893 secondHeader.numParts = numEntries;
1894 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1895 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1896 MoveSecondHeaderToEnd();
1897 if (diskSize > 0)
1898 CheckGPTSize();
1899 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001900 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001901 allOK = 0;
1902 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001903 } // if/else
1904 return (allOK);
1905} // GPTData::SetGPTSize()
1906
1907// Blank the partition array
1908void GPTData::BlankPartitions(void) {
1909 uint32_t i;
1910
1911 for (i = 0; i < mainHeader.numParts; i++) {
1912 partitions[i].BlankPartition();
1913 } // for
1914} // GPTData::BlankPartitions()
1915
srs5694ba00fed2010-01-12 18:18:36 -05001916// Delete a partition by number. Returns 1 if successful,
1917// 0 if there was a problem. Returns 1 if partition was in
1918// range, 0 if it was out of range.
1919int GPTData::DeletePartition(uint32_t partNum) {
1920 uint64_t startSector, length;
1921 uint32_t low, high, numParts, retval = 1;;
1922
1923 numParts = GetPartRange(&low, &high);
1924 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1925 // In case there's a protective MBR, look for & delete matching
1926 // MBR partition....
1927 startSector = partitions[partNum].GetFirstLBA();
1928 length = partitions[partNum].GetLengthLBA();
1929 protectiveMBR.DeleteByLocation(startSector, length);
1930
1931 // Now delete the GPT partition
1932 partitions[partNum].BlankPartition();
1933 } else {
srs5694fed16d02010-01-27 23:03:40 -05001934 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001935 retval = 0;
1936 } // if/else
1937 return retval;
1938} // GPTData::DeletePartition(uint32_t partNum)
1939
1940// Non-interactively create a partition. Note that this function is overloaded
1941// with another of the same name but different parameters; that one prompts
1942// the user for data. This one returns 1 if the operation was successful, 0
1943// if a problem was discovered.
1944int GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
1945 int retval = 1; // assume there'll be no problems
1946
1947 if (IsFreePartNum(partNum)) {
1948 Align(&startSector); // Align sector to correct multiple
1949 if (IsFree(startSector) && (startSector <= endSector)) {
1950 if (FindLastInFree(startSector) >= endSector) {
1951 partitions[partNum].SetFirstLBA(startSector);
1952 partitions[partNum].SetLastLBA(endSector);
1953 partitions[partNum].SetType(0x0700);
1954 partitions[partNum].SetUniqueGUID(1);
1955 } else retval = 0; // if free space until endSector
1956 } else retval = 0; // if startSector is free
1957 } else retval = 0; // if legal partition number
1958 return retval;
1959} // GPTData::CreatePartition(partNum, startSector, endSector)
1960
srs5694e4ac11e2009-08-31 10:13:04 -04001961// Sort the GPT entries, eliminating gaps and making for a logical
1962// ordering. Relies on QuickSortGPT() for the bulk of the work
1963void GPTData::SortGPT(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001964 GPTPart temp;
srs5694546a9c72010-01-26 16:00:26 -05001965 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001966
1967 // First, find the last partition with data, so as not to
1968 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001969 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001970
1971 // Now swap empties with the last partitions, to simplify the logic
1972 // in the Quicksort function....
1973 i = 0;
1974 while (i < lastPart) {
1975 if (partitions[i].GetFirstLBA() == 0) {
1976 temp = partitions[i];
1977 partitions[i] = partitions[lastPart];
1978 partitions[lastPart] = temp;
srs5694546a9c72010-01-26 16:00:26 -05001979 do {
1980 lastPart--;
1981 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001982 } // if
1983 i++;
1984 } // while
1985
srs5694546a9c72010-01-26 16:00:26 -05001986 // If there are more empties than partitions in the range from 0 to lastPart,
1987 // the above leaves lastPart set too high, so we've got to adjust it to
1988 // prevent empties from migrating to the top of the list....
1989 GetPartRange(&firstPart, &lastPart);
1990
srs5694e4ac11e2009-08-31 10:13:04 -04001991 // Now call the recursive quick sort routine to do the real work....
1992 QuickSortGPT(partitions, 0, lastPart);
1993} // GPTData::SortGPT()
1994
1995// Set up data structures for entirely new set of partitions on the
1996// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001997// Note that this function does NOT clear the protectiveMBR data
1998// structure, since it may hold the original MBR partitions if the
1999// program was launched on an MBR disk, and those may need to be
2000// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04002001int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002002 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04002003
2004 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05002005 if (partitions != NULL)
2006 free(partitions);
srs5694e4ac11e2009-08-31 10:13:04 -04002007 partitions = NULL;
2008 SetGPTSize(NUM_GPT_ENTRIES);
2009
2010 // Now initialize a bunch of stuff that's static....
2011 mainHeader.signature = GPT_SIGNATURE;
2012 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04002013 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04002014 mainHeader.reserved = 0;
2015 mainHeader.currentLBA = UINT64_C(1);
2016 mainHeader.partitionEntriesLBA = (uint64_t) 2;
2017 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
2018 for (i = 0; i < GPT_RESERVED; i++) {
2019 mainHeader.reserved2[i] = '\0';
2020 } // for
2021
2022 // Now some semi-static items (computed based on end of disk)
2023 mainHeader.backupLBA = diskSize - UINT64_C(1);
2024 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2025
2026 // Set a unique GUID for the disk, based on random numbers
2027 // rand() is only 32 bits, so multiply together to fill a 64-bit value
2028 mainHeader.diskGUID.data1 = (uint64_t) rand() * (uint64_t) rand();
2029 mainHeader.diskGUID.data2 = (uint64_t) rand() * (uint64_t) rand();
2030
2031 // Copy main header to backup header
2032 RebuildSecondHeader();
2033
2034 // Blank out the partitions array....
2035 BlankPartitions();
2036
2037 // Flag all CRCs as being OK....
2038 mainCrcOk = 1;
2039 secondCrcOk = 1;
2040 mainPartsCrcOk = 1;
2041 secondPartsCrcOk = 1;
2042
2043 return (goOn);
2044} // GPTData::ClearGPTData()
2045
srs5694247657a2009-11-26 18:36:12 -05002046// Set the location of the second GPT header data to the end of the disk.
2047// Used internally and called by the 'e' option on the recovery &
2048// transformation menu, to help users of RAID arrays who add disk space
2049// to their arrays.
2050void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05002051 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2052 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2053 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2054} // GPTData::FixSecondHeaderLocation()
2055
srs5694fed16d02010-01-27 23:03:40 -05002056int GPTData::SetName(uint32_t partNum, string theName) {
srs5694ba00fed2010-01-12 18:18:36 -05002057 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05002058
2059 if (!IsFreePartNum(partNum)) {
2060 partitions[partNum].SetName(theName);
2061 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05002062
2063 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04002064} // GPTData::SetName
2065
2066// Set the disk GUID to the specified value. Note that the header CRCs must
2067// be recomputed after calling this function.
2068void GPTData::SetDiskGUID(GUIDData newGUID) {
2069 mainHeader.diskGUID = newGUID;
2070 secondHeader.diskGUID = newGUID;
2071} // SetDiskGUID()
2072
2073// Set the unique GUID of the specified partition. Returns 1 on
2074// successful completion, 0 if there were problems (invalid
2075// partition number).
2076int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2077 int retval = 0;
2078
2079 if (pn < mainHeader.numParts) {
2080 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
2081 partitions[pn].SetUniqueGUID(theGUID);
2082 retval = 1;
2083 } // if
2084 } // if
2085 return retval;
2086} // GPTData::SetPartitionGUID()
2087
srs5694ba00fed2010-01-12 18:18:36 -05002088// Change partition type code non-interactively. Returns 1 if
2089// successful, 0 if not....
2090int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
2091 int retval = 1;
2092
2093 if (!IsFreePartNum(partNum)) {
2094 partitions[partNum].SetType(hexCode);
2095 } else retval = 0;
2096 return retval;
2097} // GPTData::ChangePartType()
2098
srs56941d1448a2009-12-31 21:20:19 -05002099// Adjust sector number so that it falls on a sector boundary that's a
2100// multiple of sectorAlignment. This is done to improve the performance
2101// of Western Digital Advanced Format disks and disks with similar
2102// technology from other companies, which use 4096-byte sectors
2103// internally although they translate to 512-byte sectors for the
2104// benefit of the OS. If partitions aren't properly aligned on these
2105// disks, some filesystem data structures can span multiple physical
2106// sectors, degrading performance. This function should be called
2107// only on the FIRST sector of the partition, not the last!
2108// This function returns 1 if the alignment was altered, 0 if it
2109// was unchanged.
2110int GPTData::Align(uint64_t* sector) {
2111 int retval = 0, sectorOK = 0;
2112 uint64_t earlier, later, testSector, original;
2113
2114 if ((*sector % sectorAlignment) != 0) {
2115 original = *sector;
2116 retval = 1;
2117 earlier = (*sector / sectorAlignment) * sectorAlignment;
2118 later = earlier + (uint64_t) sectorAlignment;
2119
2120 // Check to see that every sector between the earlier one and the
2121 // requested one is clear, and that it's not too early....
2122 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05002123 sectorOK = 1;
2124 testSector = earlier;
2125 do {
2126 sectorOK = IsFree(testSector++);
2127 } while ((sectorOK == 1) && (testSector < *sector));
2128 if (sectorOK == 1) {
2129 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05002130 } // if
2131 } // if firstUsableLBA check
2132
2133 // If couldn't move the sector earlier, try to move it later instead....
2134 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2135 sectorOK = 1;
2136 testSector = later;
2137 do {
2138 sectorOK = IsFree(testSector--);
2139 } while ((sectorOK == 1) && (testSector > *sector));
2140 if (sectorOK == 1) {
2141 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05002142 } // if
2143 } // if
2144
2145 // If sector was changed successfully, inform the user of this fact.
2146 // Otherwise, notify the user that it couldn't be done....
2147 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05002148 cout << "Information: Moved requested sector from " << original << " to "
2149 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05002150 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05002151 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05002152 } else {
srs5694fed16d02010-01-27 23:03:40 -05002153 cout << "Information: Sector not aligned on " << sectorAlignment
2154 << "-sector boundary and could not be moved.\n"
2155 << "If you're using a Western Digital Advanced Format or similar disk with\n"
2156 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05002157 retval = 0;
2158 } // if/else
2159 } // if
2160 return retval;
2161} // GPTData::Align()
2162
srs5694e4ac11e2009-08-31 10:13:04 -04002163/********************************************************
2164 * *
2165 * Functions that return data about GPT data structures *
2166 * (most of these are inline in gpt.h) *
2167 * *
2168 ********************************************************/
2169
2170// Find the low and high used partition numbers (numbered from 0).
2171// Return value is the number of partitions found. Note that the
2172// *low and *high values are both set to 0 when no partitions
2173// are found, as well as when a single partition in the first
2174// position exists. Thus, the return value is the only way to
2175// tell when no partitions exist.
2176int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2177 uint32_t i;
2178 int numFound = 0;
2179
2180 *low = mainHeader.numParts + 1; // code for "not found"
2181 *high = 0;
2182 if (mainHeader.numParts > 0) { // only try if partition table exists...
2183 for (i = 0; i < mainHeader.numParts; i++) {
2184 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
2185 *high = i; // since we're counting up, set the high value
2186 // Set the low value only if it's not yet found...
2187 if (*low == (mainHeader.numParts + 1)) *low = i;
2188 numFound++;
2189 } // if
2190 } // for
2191 } // if
2192
2193 // Above will leave *low pointing to its "not found" value if no partitions
2194 // are defined, so reset to 0 if this is the case....
2195 if (*low == (mainHeader.numParts + 1))
2196 *low = 0;
2197 return numFound;
2198} // GPTData::GetPartRange()
2199
srs5694978041c2009-09-21 20:51:47 -04002200// Returns the number of defined partitions.
2201uint32_t GPTData::CountParts(void) {
2202 int i, counted = 0;
2203
2204 for (i = 0; i < mainHeader.numParts; i++) {
2205 if (partitions[i].GetFirstLBA() > 0)
2206 counted++;
2207 } // for
2208 return counted;
2209} // GPTData::CountParts()
2210
srs5694e4ac11e2009-08-31 10:13:04 -04002211/****************************************************
2212 * *
2213 * Functions that return data about disk free space *
2214 * *
2215 ****************************************************/
2216
2217// Find the first available block after the starting point; returns 0 if
2218// there are no available blocks left
2219uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2220 uint64_t first;
2221 uint32_t i;
2222 int firstMoved = 0;
2223
2224 // Begin from the specified starting point or from the first usable
2225 // LBA, whichever is greater...
2226 if (start < mainHeader.firstUsableLBA)
2227 first = mainHeader.firstUsableLBA;
2228 else
2229 first = start;
2230
2231 // ...now search through all partitions; if first is within an
2232 // existing partition, move it to the next sector after that
2233 // partition and repeat. If first was moved, set firstMoved
2234 // flag; repeat until firstMoved is not set, so as to catch
2235 // cases where partitions are out of sequential order....
2236 do {
2237 firstMoved = 0;
2238 for (i = 0; i < mainHeader.numParts; i++) {
2239 if ((first >= partitions[i].GetFirstLBA()) &&
2240 (first <= partitions[i].GetLastLBA())) { // in existing part.
2241 first = partitions[i].GetLastLBA() + 1;
2242 firstMoved = 1;
2243 } // if
2244 } // for
2245 } while (firstMoved == 1);
2246 if (first > mainHeader.lastUsableLBA)
2247 first = 0;
2248 return (first);
2249} // GPTData::FindFirstAvailable()
2250
2251// Finds the first available sector in the largest block of unallocated
2252// space on the disk. Returns 0 if there are no available blocks left
2253uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002254 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002255
2256 start = 0;
2257 do {
2258 firstBlock = FindFirstAvailable(start);
2259 if (firstBlock != UINT32_C(0)) { // something's free...
2260 lastBlock = FindLastInFree(firstBlock);
2261 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2262 if (segmentSize > selectedSize) {
2263 selectedSize = segmentSize;
2264 selectedSegment = firstBlock;
2265 } // if
2266 start = lastBlock + 1;
2267 } // if
2268 } while (firstBlock != 0);
2269 return selectedSegment;
2270} // GPTData::FindFirstInLargest()
2271
2272// Find the last available block on the disk at or after the start
2273// block. Returns 0 if there are no available partitions after
2274// (or including) start.
2275uint64_t GPTData::FindLastAvailable(uint64_t start) {
2276 uint64_t last;
2277 uint32_t i;
2278 int lastMoved = 0;
2279
2280 // Start by assuming the last usable LBA is available....
2281 last = mainHeader.lastUsableLBA;
2282
2283 // ...now, similar to algorithm in FindFirstAvailable(), search
2284 // through all partitions, moving last when it's in an existing
2285 // partition. Set the lastMoved flag so we repeat to catch cases
2286 // where partitions are out of logical order.
2287 do {
2288 lastMoved = 0;
2289 for (i = 0; i < mainHeader.numParts; i++) {
2290 if ((last >= partitions[i].GetFirstLBA()) &&
2291 (last <= partitions[i].GetLastLBA())) { // in existing part.
2292 last = partitions[i].GetFirstLBA() - 1;
2293 lastMoved = 1;
2294 } // if
2295 } // for
2296 } while (lastMoved == 1);
2297 if (last < mainHeader.firstUsableLBA)
2298 last = 0;
2299 return (last);
2300} // GPTData::FindLastAvailable()
2301
2302// Find the last available block in the free space pointed to by start.
2303uint64_t GPTData::FindLastInFree(uint64_t start) {
2304 uint64_t nearestStart;
2305 uint32_t i;
2306
2307 nearestStart = mainHeader.lastUsableLBA;
2308 for (i = 0; i < mainHeader.numParts; i++) {
2309 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2310 (partitions[i].GetFirstLBA() > start)) {
2311 nearestStart = partitions[i].GetFirstLBA() - 1;
2312 } // if
2313 } // for
2314 return (nearestStart);
2315} // GPTData::FindLastInFree()
2316
2317// Finds the total number of free blocks, the number of segments in which
2318// they reside, and the size of the largest of those segments
2319uint64_t GPTData::FindFreeBlocks(int *numSegments, uint64_t *largestSegment) {
2320 uint64_t start = UINT64_C(0); // starting point for each search
2321 uint64_t totalFound = UINT64_C(0); // running total
2322 uint64_t firstBlock; // first block in a segment
2323 uint64_t lastBlock; // last block in a segment
2324 uint64_t segmentSize; // size of segment in blocks
2325 int num = 0;
2326
2327 *largestSegment = UINT64_C(0);
2328 do {
2329 firstBlock = FindFirstAvailable(start);
2330 if (firstBlock != UINT64_C(0)) { // something's free...
2331 lastBlock = FindLastInFree(firstBlock);
2332 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2333 if (segmentSize > *largestSegment) {
2334 *largestSegment = segmentSize;
2335 } // if
2336 totalFound += segmentSize;
2337 num++;
2338 start = lastBlock + 1;
2339 } // if
2340 } while (firstBlock != 0);
2341 *numSegments = num;
2342 return totalFound;
2343} // GPTData::FindFreeBlocks()
2344
2345// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2346int GPTData::IsFree(uint64_t sector) {
2347 int isFree = 1;
2348 uint32_t i;
2349
2350 for (i = 0; i < mainHeader.numParts; i++) {
2351 if ((sector >= partitions[i].GetFirstLBA()) &&
2352 (sector <= partitions[i].GetLastLBA())) {
2353 isFree = 0;
2354 } // if
2355 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002356 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002357 (sector > mainHeader.lastUsableLBA)) {
2358 isFree = 0;
2359 } // if
2360 return (isFree);
2361} // GPTData::IsFree()
2362
srs5694ba00fed2010-01-12 18:18:36 -05002363// Returns 1 if partNum is unused.
2364int GPTData::IsFreePartNum(uint32_t partNum) {
2365 int retval = 1;
2366
2367 if ((partNum >= 0) && (partNum < mainHeader.numParts)) {
2368 if ((partitions[partNum].GetFirstLBA() != UINT64_C(0)) ||
2369 (partitions[partNum].GetLastLBA() != UINT64_C(0))) {
2370 retval = 0;
2371 } // if partition is in use
2372 } else retval = 0;
2373
2374 return retval;
2375} // GPTData::IsFreePartNum()
2376
srs5694e4ac11e2009-08-31 10:13:04 -04002377/********************************
2378 * *
2379 * Endianness support functions *
2380 * *
2381 ********************************/
2382
srs56942a9f5da2009-08-26 00:48:01 -04002383void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002384 ReverseBytes(&header->signature, 8);
2385 ReverseBytes(&header->revision, 4);
2386 ReverseBytes(&header->headerSize, 4);
2387 ReverseBytes(&header->headerCRC, 4);
2388 ReverseBytes(&header->reserved, 4);
2389 ReverseBytes(&header->currentLBA, 8);
2390 ReverseBytes(&header->backupLBA, 8);
2391 ReverseBytes(&header->firstUsableLBA, 8);
2392 ReverseBytes(&header->lastUsableLBA, 8);
2393 ReverseBytes(&header->partitionEntriesLBA, 8);
2394 ReverseBytes(&header->numParts, 4);
2395 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2396 ReverseBytes(&header->partitionEntriesCRC, 4);
2397 ReverseBytes(&header->reserved2, GPT_RESERVED);
2398 ReverseBytes(&header->diskGUID.data1, 8);
2399 ReverseBytes(&header->diskGUID.data2, 8);
srs56942a9f5da2009-08-26 00:48:01 -04002400} // GPTData::ReverseHeaderBytes()
2401
2402// IMPORTANT NOTE: This function requires non-reversed mainHeader
2403// structure!
2404void GPTData::ReversePartitionBytes() {
2405 uint32_t i;
2406
2407 // Check GPT signature on big-endian systems; this will mismatch
2408 // if the function is called out of order. Unfortunately, it'll also
2409 // mismatch if there's data corruption.
2410 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002411 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2412 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002413 } // if signature mismatch....
2414 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002415 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002416 } // for
2417} // GPTData::ReversePartitionBytes()
2418
2419/******************************************
2420 * *
2421 * Additional non-class support functions *
2422 * *
2423 ******************************************/
2424
srs5694e7b4ff92009-08-18 13:16:10 -04002425// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2426// never fail these tests, but the struct types may fail depending on compile options.
2427// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2428// sizes.
2429int SizesOK(void) {
2430 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002431
2432 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002433 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002434 allOK = 0;
2435 } // if
2436 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002437 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002438 allOK = 0;
2439 } // if
2440 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002441 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002442 allOK = 0;
2443 } // if
2444 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002445 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002446 allOK = 0;
2447 } // if
2448 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002449 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002450 allOK = 0;
2451 } // if
srs5694978041c2009-09-21 20:51:47 -04002452 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002453 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002454 allOK = 0;
2455 } // if
2456 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002457 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002458 allOK = 0;
2459 } // if
srs5694221e0872009-08-29 15:00:31 -04002460 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002461 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002462 allOK = 0;
2463 } // if
srs5694fed16d02010-01-27 23:03:40 -05002464 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002465 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002466 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2467 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002468 } // if
2469 return (allOK);
2470} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002471