blob: 562a085b5397175dd0655f4a124635ce10943683 [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) {
srs5694e321d442010-01-29 17:44:04 -050099 int problems = 0;
100 uint32_t i, numSegments;
101 uint64_t totalFree, largestSegment;
102 char siTotal[255], siLargest[255];
srs5694e4ac11e2009-08-31 10:13:04 -0400103
104 // First, check for CRC errors in the GPT data....
105 if (!mainCrcOk) {
106 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500107 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
108 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
109 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
110 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400111 } // if
112 if (!mainPartsCrcOk) {
113 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500114 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
115 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
116 << "transformation menu). This report may be a false alarm if you've already\n"
117 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400118 } // if
119 if (!secondCrcOk) {
120 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500121 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
122 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
123 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
124 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400125 } // if
126 if (!secondPartsCrcOk) {
127 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500128 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
129 << "be corrupt. This program will automatically create a new backup partition\n"
130 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400131 } // if
132
srs5694978041c2009-09-21 20:51:47 -0400133 // Now check that the main and backup headers both point to themselves....
134 if (mainHeader.currentLBA != 1) {
135 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500136 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
137 << "is being automatically corrected, but it may be a symptom of more serious\n"
138 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400139 mainHeader.currentLBA = 1;
140 } // if
141 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
142 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500143 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
144 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
145 << "option on the experts' menu to adjust the secondary header's and partition\n"
146 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400147 } // if
148
149 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400150 if (mainHeader.currentLBA != secondHeader.backupLBA) {
151 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500152 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
153 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
154 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400155 } // if
156 if (mainHeader.backupLBA != secondHeader.currentLBA) {
157 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500158 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
159 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
160 << secondHeader.currentLBA << ").\n"
161 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
166 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
167 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400168 } // if
169 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
170 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500171 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
172 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
173 << secondHeader.lastUsableLBA << ")\n"
174 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400175 } // if
srs56946699b012010-02-04 00:55:30 -0500176 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400177 problems++;
srs56946699b012010-02-04 00:55:30 -0500178 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500179 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500180 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500181 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
182 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400183 } // if
184 if (mainHeader.numParts != secondHeader.numParts) {
185 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500186 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
187 << ") doesn't\nmatch the backup GPT header's number of partitions ("
188 << secondHeader.numParts << ")\n"
189 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400190 } // if
191 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
192 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500193 cout << "\nProblem: main GPT header's size of partition entries ("
194 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
195 << "match the backup GPT header's size of partition entries ("
196 << secondHeader.sizeOfPartitionEntries << ")\n"
197 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
198 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400199 } // if
200
201 // Now check for a few other miscellaneous problems...
202 // Check that the disk size will hold the data...
203 if (mainHeader.backupLBA > diskSize) {
204 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500205 cout << "\nProblem: Disk is too small to hold all the data!\n"
206 << "(Disk size is " << diskSize << " sectors, needs to be "
207 << mainHeader.backupLBA << " sectors.)\n"
208 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400209 } // if
210
211 // Check for overlapping partitions....
212 problems += FindOverlaps();
213
214 // Check for mismatched MBR and GPT partitions...
215 problems += FindHybridMismatches();
216
217 // Verify that partitions don't run into GPT data areas....
218 problems += CheckGPTSize();
219
srs56941d1448a2009-12-31 21:20:19 -0500220 // Check that partitions are aligned on proper boundaries (for WD Advanced
221 // Format and similar disks)....
222 for (i = 0; i < mainHeader.numParts; i++) {
223 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500224 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
225 << sectorAlignment << "-sector boundary. This may\nresult "
226 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500227 } // if
228 } // for
229
srs5694e4ac11e2009-08-31 10:13:04 -0400230 // Now compute available space, but only if no problems found, since
231 // problems could affect the results
232 if (problems == 0) {
233 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500234 strcpy(siTotal, BytesToSI(totalFree * (uint64_t) blockSize).c_str());
235 strcpy(siLargest, BytesToSI(largestSegment * (uint64_t) blockSize).c_str());
236 cout << "No problems found. " << totalFree << " free sectors ("
237 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
238 << numSegments << "\nsegments, the largest of which is "
239 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
240 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } else {
srs56940a697312010-01-28 21:10:52 -0500242 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400243 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400244
245 return (problems);
246} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400247
248// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400249// do, issues a warning but takes no action. Returns number of problems
250// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400251int GPTData::CheckGPTSize(void) {
252 uint64_t overlap, firstUsedBlock, lastUsedBlock;
253 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400254 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400255
256 // first, locate the first & last used blocks
257 firstUsedBlock = UINT64_MAX;
258 lastUsedBlock = 0;
259 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400260 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400261 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400262 firstUsedBlock = partitions[i].GetFirstLBA();
263 if (partitions[i].GetLastLBA() > lastUsedBlock)
264 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400265 } // for
266
267 // If the disk size is 0 (the default), then it means that various
268 // variables aren't yet set, so the below tests will be useless;
269 // therefore we should skip everything
270 if (diskSize != 0) {
271 if (mainHeader.firstUsableLBA > firstUsedBlock) {
272 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500273 cout << "Warning! Main partition table overlaps the first partition by "
274 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400275 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "Try reducing the partition table size by " << overlap * 4
277 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400278 } else {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400280 } // if/else
281 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400282 } // Problem at start of disk
283 if (mainHeader.lastUsableLBA < lastUsedBlock) {
284 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs5694fed16d02010-01-27 23:03:40 -0500285 cout << "Warning! Secondary partition table overlaps the last partition by "
286 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400287 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500288 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400289 } else {
srs5694fed16d02010-01-27 23:03:40 -0500290 cout << "Try reducing the partition table size by " << overlap * 4
291 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400292 } // if/else
293 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400294 } // Problem at end of disk
295 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400296 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400297} // GPTData::CheckGPTSize()
298
srs5694e7b4ff92009-08-18 13:16:10 -0400299// Check the validity of the GPT header. Returns 1 if the main header
300// is valid, 2 if the backup header is valid, 3 if both are valid, and
301// 0 if neither is valid. Note that this function just checks the GPT
302// signature and revision numbers, not CRCs or other data.
303int GPTData::CheckHeaderValidity(void) {
304 int valid = 3;
305
srs5694fed16d02010-01-27 23:03:40 -0500306 cout.setf(ios::uppercase);
307 cout.fill('0');
308
309 // Note: failed GPT signature checks produce no error message because
310 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400311 if (mainHeader.signature != GPT_SIGNATURE) {
312 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400313 } else if ((mainHeader.revision != 0x00010000) && valid) {
314 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500315 cout << "Unsupported GPT version in main header; read 0x";
316 cout.width(8);
317 cout << hex << mainHeader.revision << ", should be\n0x";
318 cout.width(8);
319 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400320 } // if/else/if
321
322 if (secondHeader.signature != GPT_SIGNATURE) {
323 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } else if ((secondHeader.revision != 0x00010000) && valid) {
325 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500326 cout << "Unsupported GPT version in backup header; read 0x";
327 cout.width(8);
328 cout << hex << secondHeader.revision << ", should be\n0x";
329 cout.width(8);
330 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400331 } // if/else/if
332
srs56942a9f5da2009-08-26 00:48:01 -0400333 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400334 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400335 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400336 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400337 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500338 } // if
srs5694fed16d02010-01-27 23:03:40 -0500339 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400340
srs5694fed16d02010-01-27 23:03:40 -0500341 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400342} // GPTData::CheckHeaderValidity()
343
344// Check the header CRC to see if it's OK...
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
srs56946699b012010-02-04 00:55:30 -0500370// Recompute all the CRCs. Must be called before saving if any changes have
371// been made. Must be called on platform-ordered data (this function reverses
372// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400373void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400374 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400375 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400376
377 // Initialize CRC functions...
378 chksum_crc32gentab();
379
srs56946699b012010-02-04 00:55:30 -0500380 // Save some key data from header before reversing byte order....
381 trueNumParts = mainHeader.numParts;
srs5694978041c2009-09-21 20:51:47 -0400382 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500383
384 if ((littleEndian = IsLittleEndian()) == 0) {
385 ReversePartitionBytes();
386 ReverseHeaderBytes(&mainHeader);
387 ReverseHeaderBytes(&secondHeader);
388 } // if
389/* if ((littleEndian = IsLittleEndian()) == 0) {
390 ReverseBytes(&trueNumParts, 4);
391 ReverseBytes(&hSize, 4);
392 } // if */
srs56942a9f5da2009-08-26 00:48:01 -0400393
srs5694e7b4ff92009-08-18 13:16:10 -0400394 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400395 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400396 mainHeader.partitionEntriesCRC = crc;
397 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400398 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400399 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
400 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400401 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400402
403 // Zero out GPT tables' own CRCs (required for correct computation)
404 mainHeader.headerCRC = 0;
405 secondHeader.headerCRC = 0;
406
407 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400408 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400409 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400410 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400411 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400412 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400413 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400414 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400415 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500416
417 if ((littleEndian = IsLittleEndian()) == 0) {
418 ReverseHeaderBytes(&mainHeader);
419 ReverseHeaderBytes(&secondHeader);
420 ReversePartitionBytes();
421 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400422} // GPTData::RecomputeCRCs()
423
srs5694e7b4ff92009-08-18 13:16:10 -0400424// Rebuild the main GPT header, using the secondary header as a model.
425// Typically called when the main header has been found to be corrupt.
426void GPTData::RebuildMainHeader(void) {
427 int i;
428
429 mainHeader.signature = GPT_SIGNATURE;
430 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400431 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400432 mainHeader.headerCRC = UINT32_C(0);
433 mainHeader.reserved = secondHeader.reserved;
434 mainHeader.currentLBA = secondHeader.backupLBA;
435 mainHeader.backupLBA = secondHeader.currentLBA;
436 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
437 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500438 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400439 mainHeader.partitionEntriesLBA = UINT64_C(2);
440 mainHeader.numParts = secondHeader.numParts;
441 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
442 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
443 for (i = 0 ; i < GPT_RESERVED; i++)
444 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500445 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400446} // GPTData::RebuildMainHeader()
447
448// Rebuild the secondary GPT header, using the main header as a model.
449void GPTData::RebuildSecondHeader(void) {
450 int i;
451
452 secondHeader.signature = GPT_SIGNATURE;
453 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400454 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400455 secondHeader.headerCRC = UINT32_C(0);
456 secondHeader.reserved = mainHeader.reserved;
457 secondHeader.currentLBA = mainHeader.backupLBA;
458 secondHeader.backupLBA = mainHeader.currentLBA;
459 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
460 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500461 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400462 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
463 secondHeader.numParts = mainHeader.numParts;
464 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
465 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
466 for (i = 0 ; i < GPT_RESERVED; i++)
467 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500468 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400469} // GPTData::RebuildSecondHeader()
470
471// Search for hybrid MBR entries that have no corresponding GPT partition.
472// Returns number of such mismatches found
473int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500474 int i, found, numFound = 0;
475 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400476 uint64_t mbrFirst, mbrLast;
477
478 for (i = 0; i < 4; i++) {
479 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
480 j = 0;
481 found = 0;
482 do {
483 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
484 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
485 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
486 (partitions[j].GetLastLBA() == mbrLast))
487 found = 1;
488 j++;
489 } while ((!found) && (j < mainHeader.numParts));
490 if (!found) {
491 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500492 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
493 << i + 1 << ", of type 0x";
494 cout.fill('0');
495 cout.setf(ios::uppercase);
496 cout.width(2);
497 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
498 << "has no corresponding GPT partition! You may continue, but this condition\n"
499 << "might cause data loss in the future!\a\n" << dec;
500 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400501 } // if
502 } // if
503 } // for
504 return numFound;
505} // GPTData::FindHybridMismatches
506
507// Find overlapping partitions and warn user about them. Returns number of
508// overlapping partitions.
509int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500510 int problems = 0;
511 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400512
513 for (i = 1; i < mainHeader.numParts; i++) {
514 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500515 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400516 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500517 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
518 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
519 << " to " << partitions[i].GetLastLBA() << "\n";
520 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
521 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400522 } // if
523 } // for j...
524 } // for i...
525 return problems;
526} // GPTData::FindOverlaps()
527
528/******************************************************************
529 * *
530 * Begin functions that load data from disk or save data to disk. *
531 * *
532 ******************************************************************/
533
534// Scan for partition data. This function loads the MBR data (regular MBR or
535// protective MBR) and loads BSD disklabel data (which is probably invalid).
536// It also looks for APM data, forces a load of GPT data, and summarizes
537// the results.
srs5694546a9c72010-01-26 16:00:26 -0500538void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400539 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400540
541 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500542 protectiveMBR.ReadMBRData(&myDisk);
543 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400544
545 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500546 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500547
548 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500549 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500550 protectiveMBR.ShowState();
551 bsdDisklabel.ShowState();
552 ShowAPMState(); // Show whether there's an Apple Partition Map present
553 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500554 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500555 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400556
557 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500558 cout << "\n*******************************************************************\n"
559 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500560 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500561 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500562 } // if
srs5694fed16d02010-01-27 23:03:40 -0500563 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400564 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400565} // GPTData::PartitionScan()
566
567// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500568int GPTData::LoadPartitions(const string & deviceFilename) {
srs5694e321d442010-01-29 17:44:04 -0500569 int err, allOK = 1;
570 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -0400571 uint64_t firstBlock, lastBlock;
572 BSDData bsdDisklabel;
srs5694fed16d02010-01-27 23:03:40 -0500573 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400574
575 // First, do a test to see if writing will be possible later....
srs5694fed16d02010-01-27 23:03:40 -0500576 err = myDisk.OpenForWrite(deviceFilename);
577 if ((err == 0) && (!justLooking)) {
578 cout << "\aNOTE: Write test failed with error number " << errno
579 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
srs56947dbb9322010-01-20 16:56:30 -0500580#ifdef __FreeBSD__
srs5694fed16d02010-01-27 23:03:40 -0500581 cout << "You may be able to enable writes by exiting this program, typing\n"
582 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
583 << "program.\n";
srs56947dbb9322010-01-20 16:56:30 -0500584#endif
srs5694fed16d02010-01-27 23:03:40 -0500585 cout << "\n";
srs56945d58fe02010-01-03 20:57:08 -0500586 } // if
srs5694546a9c72010-01-26 16:00:26 -0500587 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400588
srs5694546a9c72010-01-26 16:00:26 -0500589 if (myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400590 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500591 diskSize = myDisk.DiskSize(&err);
592 blockSize = (uint32_t) myDisk.GetBlockSize();
593 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500594 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500595 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400596
srs5694ba00fed2010-01-12 18:18:36 -0500597 whichWasUsed = UseWhichPartitions();
598 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400599 case use_mbr:
600 XFormPartitions();
601 break;
602 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500603 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400604// bsdDisklabel.DisplayBSDData();
605 ClearGPTData();
606 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
607 XFormDisklabel(&bsdDisklabel, 0);
608 break;
609 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500610 mbrState = protectiveMBR.GetValidity();
611 if ((mbrState == invalid) || (mbrState == mbr))
612 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400613 break;
614 case use_new:
615 ClearGPTData();
616 protectiveMBR.MakeProtectiveMBR();
617 break;
srs56943c0af382010-01-15 19:19:18 -0500618 case use_abort:
619 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500620 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500621 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400622 } // switch
623
624 // Now find the first and last sectors used by partitions...
625 if (allOK) {
626 firstBlock = mainHeader.backupLBA; // start high
627 lastBlock = 0; // start low
628 for (i = 0; i < mainHeader.numParts; i++) {
629 if ((partitions[i].GetFirstLBA() < firstBlock) &&
630 (partitions[i].GetFirstLBA() > 0))
631 firstBlock = partitions[i].GetFirstLBA();
632 if (partitions[i].GetLastLBA() > lastBlock)
633 lastBlock = partitions[i].GetLastLBA();
634 } // for
srs56943c0af382010-01-15 19:19:18 -0500635 CheckGPTSize();
srs5694e4ac11e2009-08-31 10:13:04 -0400636 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400637 } else {
638 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500639 cerr << "Problem opening " << deviceFilename << " for reading! Error is "
640 << errno << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400641 if (errno == EACCES) { // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -0500642 cerr << "You must run this program as root or use sudo!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400643 } // if
644 } // if/else
645 return (allOK);
646} // GPTData::LoadPartitions()
647
648// Loads the GPT, as much as possible. Returns 1 if this seems to have
649// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500650int GPTData::ForceLoadGPTData(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400651 int allOK = 1, validHeaders;
srs56940a697312010-01-28 21:10:52 -0500652 uint64_t seekTo;
srs5694fed16d02010-01-27 23:03:40 -0500653 uint8_t* storage;
srs5694e4ac11e2009-08-31 10:13:04 -0400654 uint32_t newCRC, sizeOfParts;
655
656 // Seek to and read the main GPT header
srs5694546a9c72010-01-26 16:00:26 -0500657 if (myDisk.Seek(1)) {
658 if (myDisk.Read(&mainHeader, 512) != 512) { // read main GPT header
srs5694fed16d02010-01-27 23:03:40 -0500659 cerr << "Warning! Error " << errno << " reading main GPT header!\n";
srs5694546a9c72010-01-26 16:00:26 -0500660 } // if read not OK
661 } else allOK = 0; // if/else seek OK
srs5694e4ac11e2009-08-31 10:13:04 -0400662 mainCrcOk = CheckHeaderCRC(&mainHeader);
663 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
664 ReverseHeaderBytes(&mainHeader);
665
srs56943f2fe992009-11-24 18:28:18 -0500666 // Load backup header, check its CRC, and store the results of the
667 // check for future reference. Load backup header using pointer in main
668 // header if possible; but if main header has a CRC error, or if it
669 // points to beyond the end of the disk, load the last sector of the
670 // disk instead.
671 if (mainCrcOk) {
672 if (mainHeader.backupLBA < diskSize) {
srs5694546a9c72010-01-26 16:00:26 -0500673 seekTo = mainHeader.backupLBA;
srs56943f2fe992009-11-24 18:28:18 -0500674 } else {
srs5694546a9c72010-01-26 16:00:26 -0500675 seekTo = diskSize - UINT64_C(1);
srs5694fed16d02010-01-27 23:03:40 -0500676 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
677 << "secondary header from the last sector of the disk! You should use 'v' to\n"
678 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
679 << "the disk.\n";
srs56943f2fe992009-11-24 18:28:18 -0500680 } // else
681 } else {
srs5694546a9c72010-01-26 16:00:26 -0500682 seekTo = diskSize - UINT64_C(1);
srs56943f2fe992009-11-24 18:28:18 -0500683 } // if/else (mainCrcOk)
684
srs5694546a9c72010-01-26 16:00:26 -0500685 if (myDisk.Seek(seekTo)) {
686 if (myDisk.Read(&secondHeader, 512) != 512) { // read secondary GPT header
srs5694fed16d02010-01-27 23:03:40 -0500687 cerr << "Warning! Error " << errno << " reading secondary GPT header!\n";
srs56945d58fe02010-01-03 20:57:08 -0500688 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400689 secondCrcOk = CheckHeaderCRC(&secondHeader);
690 if (IsLittleEndian() == 0) // big-endian system; adjust header byte order....
691 ReverseHeaderBytes(&secondHeader);
692 } else {
693 allOK = 0;
694 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -0500695 cerr << "Unable to seek to secondary GPT header at sector "
696 << (diskSize - (UINT64_C(1))) << "!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400697 } // if/else lseek
698
699 // Return valid headers code: 0 = both headers bad; 1 = main header
700 // good, backup bad; 2 = backup header good, main header bad;
701 // 3 = both headers good. Note these codes refer to valid GPT
702 // signatures and version numbers; more subtle problems will elude
703 // this check!
704 validHeaders = CheckHeaderValidity();
705
706 // Read partitions (from primary array)
707 if (validHeaders > 0) { // if at least one header is OK....
708 // GPT appears to be valid....
709 state = gpt_valid;
710
711 // We're calling the GPT valid, but there's a possibility that one
712 // of the two headers is corrupt. If so, use the one that seems to
713 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500714 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500715 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
716 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400717 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500718 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400719 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500720 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500721 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
722 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500723 RebuildMainHeader();
724 state = gpt_corrupt;
725 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400726 } // if/else/if
727
srs5694546a9c72010-01-26 16:00:26 -0500728 // Figure out which partition table to load....
729 // Load the main partition table, since either its header's CRC is OK or the
730 // backup header's CRC is not OK....
731 if (mainCrcOk || !secondCrcOk) {
732 if (LoadMainTable() == 0)
733 allOK = 0;
734 } else { // bad main header CRC and backup header CRC is OK
735 state = gpt_corrupt;
736 if (LoadSecondTableAsMain()) {
srs5694fed16d02010-01-27 23:03:40 -0500737 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500738 } else { // backup table bad, bad main header CRC, but try main table in desperation....
739 if (LoadMainTable() == 0) {
740 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500741 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500742 } // if
743 } // if/else (LoadSecondTableAsMain())
744 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400745
746 // Load backup partition table into temporary storage to check
747 // its CRC and store the results, then discard this temporary
748 // storage, since we don't use it in any but recovery operations
srs5694546a9c72010-01-26 16:00:26 -0500749 seekTo = secondHeader.partitionEntriesLBA;
750 if ((myDisk.Seek(seekTo)) && (secondCrcOk)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400751 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -0500752 storage = (uint8_t*) malloc(sizeOfParts);
srs5694e321d442010-01-29 17:44:04 -0500753 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500754 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500755 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400756 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
757 free(storage);
758 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
759 } // if
760
srs5694546a9c72010-01-26 16:00:26 -0500761 // Problem with main partition table; if backup is OK, use it instead....
762 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
763 state = gpt_corrupt;
764 allOK = allOK && LoadSecondTableAsMain();
srs5694fed16d02010-01-27 23:03:40 -0500765 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
766 << "partition table\ninstead of main partition table!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500767 } // if
768
srs5694e4ac11e2009-08-31 10:13:04 -0400769 // Check for valid CRCs and warn if there are problems
770 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
771 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500772 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400773 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500774 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400775 } else {
776 state = gpt_invalid;
777 } // if/else
778 return allOK;
779} // GPTData::ForceLoadGPTData()
780
srs5694247657a2009-11-26 18:36:12 -0500781// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400782// main GPT header in memory MUST be valid for this call to do anything
783// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500784// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400785int GPTData::LoadMainTable(void) {
srs5694e321d442010-01-29 17:44:04 -0500786 int retval = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400787 uint32_t newCRC, sizeOfParts;
788
srs5694546a9c72010-01-26 16:00:26 -0500789 if (myDisk.OpenForRead(device)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400790 // Set internal data structures for number of partitions on the disk
791 SetGPTSize(mainHeader.numParts);
792
793 // Load main partition table, and record whether its CRC
794 // matches the stored value
srs5694546a9c72010-01-26 16:00:26 -0500795 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
796 retval = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400797 sizeOfParts = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694e321d442010-01-29 17:44:04 -0500798 if (myDisk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500799 cerr << "Warning! Error " << errno << " when loading the main partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500800 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500801 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400802 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
803 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
804 if (IsLittleEndian() == 0)
805 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500806 } else retval = 0; // if open for read....
srs5694e4ac11e2009-08-31 10:13:04 -0400807 return retval;
808} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400809
810// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500811// table. Used in repair functions, and when starting up if the main
812// partition table is damaged.
813// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
814int GPTData::LoadSecondTableAsMain(void) {
815 uint64_t seekTo;
srs5694e7b4ff92009-08-18 13:16:10 -0400816 uint32_t sizeOfParts, newCRC;
srs5694546a9c72010-01-26 16:00:26 -0500817 int retval = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400818
srs5694546a9c72010-01-26 16:00:26 -0500819 if (myDisk.OpenForRead(device)) {
820 seekTo = secondHeader.partitionEntriesLBA;
821 retval = myDisk.Seek(seekTo);
822 if (retval == 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400823 SetGPTSize(secondHeader.numParts);
824 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
srs5694e321d442010-01-29 17:44:04 -0500825 if (myDisk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500826 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500827 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500828 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400829 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
830 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs5694e4ac11e2009-08-31 10:13:04 -0400831 mainPartsCrcOk = secondPartsCrcOk;
srs56942a9f5da2009-08-26 00:48:01 -0400832 if (IsLittleEndian() == 0)
833 ReversePartitionBytes();
srs5694e7b4ff92009-08-18 13:16:10 -0400834 if (!secondPartsCrcOk) {
srs5694fed16d02010-01-27 23:03:40 -0500835 cout << "Caution! After loading backup partitions, the CRC still doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400836 } // if
837 } else {
srs5694fed16d02010-01-27 23:03:40 -0500838 cerr << "Error! Couldn't seek to backup partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400839 } // if/else
840 } else {
srs5694fed16d02010-01-27 23:03:40 -0500841 cerr << "Error! Couldn't open device " << device
842 << " when recovering backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500843 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400844 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500845 return retval;
srs5694e7b4ff92009-08-18 13:16:10 -0400846} // GPTData::LoadSecondTableAsMain()
847
srs5694e7b4ff92009-08-18 13:16:10 -0400848// Writes GPT (and protective MBR) to disk. Returns 1 on successful
849// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500850int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500851 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500852 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400853 uint64_t secondTable;
srs56942a9f5da2009-08-26 00:48:01 -0400854 uint32_t numParts;
srs56940a697312010-01-28 21:10:52 -0500855 uint64_t offset;
srs5694e7b4ff92009-08-18 13:16:10 -0400856
srs56946699b012010-02-04 00:55:30 -0500857 littleEndian = IsLittleEndian();
858
srs5694fed16d02010-01-27 23:03:40 -0500859 if (device == "") {
860 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400861 } // if
862
863 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500864
865 // This test should only fail on read-only disks....
866 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500867 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500868 allOK = 0;
869 } // if
870
srs5694e7b4ff92009-08-18 13:16:10 -0400871 // Is there enough space to hold the GPT headers and partition tables,
872 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400873 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400874 allOK = 0;
875 } // if
876
877 // Check that disk is really big enough to handle this...
878 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500879 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
880 << "problem (or it might not). Aborting!\n(Disk size is "
881 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400882 allOK = 0;
883 } // if
srs5694247657a2009-11-26 18:36:12 -0500884 // Check that second header is properly placed. Warn and ask if this should
885 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500886 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500887 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
888 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500889 if (GetYN() == 'Y') {
890 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500891 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500892 } else {
srs5694fed16d02010-01-27 23:03:40 -0500893 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500894 } // if correction requested
895 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400896
897 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400898 if (FindOverlaps() > 0) {
899 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500900 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400901 } // if
902
903 // Check for mismatched MBR and GPT data, but let it pass if found
904 // (function displays warning message)
905 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400906
srs56942a9f5da2009-08-26 00:48:01 -0400907 // Pull out some data that's needed before doing byte-order reversal on
908 // big-endian systems....
909 numParts = mainHeader.numParts;
910 secondTable = secondHeader.partitionEntriesLBA;
srs56946699b012010-02-04 00:55:30 -0500911/* if (IsLittleEndian() == 0) {
srs56942a9f5da2009-08-26 00:48:01 -0400912 // Reverse partition bytes first, since that function requires non-reversed
913 // data from the main header....
914 ReversePartitionBytes();
915 ReverseHeaderBytes(&mainHeader);
916 ReverseHeaderBytes(&secondHeader);
srs56946699b012010-02-04 00:55:30 -0500917 } // if */
srs5694e7b4ff92009-08-18 13:16:10 -0400918 RecomputeCRCs();
srs56946699b012010-02-04 00:55:30 -0500919/* ReverseHeaderBytes(&mainHeader);
920 ReverseHeaderBytes(&secondHeader);
921 ReversePartitionBytes(); */
srs5694e7b4ff92009-08-18 13:16:10 -0400922
srs5694ba00fed2010-01-12 18:18:36 -0500923 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500924 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
925 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500926 answer = GetYN();
927 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500928 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400929 } else {
930 allOK = 0;
931 } // if/else
932 } // if
933
934 // Do it!
935 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500936 // First, write the protective MBR...
937 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400938
srs5694546a9c72010-01-26 16:00:26 -0500939 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400940 // Now write the main GPT header...
srs5694546a9c72010-01-26 16:00:26 -0500941 if (myDisk.Seek(1) == 1) {
srs56946699b012010-02-04 00:55:30 -0500942 if (!littleEndian)
943 ReverseHeaderBytes(&mainHeader);
srs5694546a9c72010-01-26 16:00:26 -0500944 if (myDisk.Write(&mainHeader, 512) != 512)
945 allOK = 0;
srs56946699b012010-02-04 00:55:30 -0500946 if (!littleEndian)
947 ReverseHeaderBytes(&mainHeader);
srs5694546a9c72010-01-26 16:00:26 -0500948 } else allOK = 0; // if (myDisk.Seek()...)
srs5694e7b4ff92009-08-18 13:16:10 -0400949
950 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400951 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500952 offset = mainHeader.partitionEntriesLBA;
953 if (myDisk.Seek(offset)) {
srs56946699b012010-02-04 00:55:30 -0500954 if (!littleEndian)
955 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500956 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
957 allOK = 0;
srs56946699b012010-02-04 00:55:30 -0500958 if (!littleEndian)
959 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500960 } else allOK = 0; // if (myDisk.Seek()...)
srs56941e093722010-01-05 00:14:19 -0500961 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400962
963 // Now seek to near the end to write the secondary GPT....
srs5694e4ac11e2009-08-31 10:13:04 -0400964 if (allOK) {
srs56940a697312010-01-28 21:10:52 -0500965 offset = (uint64_t) secondTable;
srs5694546a9c72010-01-26 16:00:26 -0500966 if (myDisk.Seek(offset) != 1) {
srs5694e7b4ff92009-08-18 13:16:10 -0400967 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500968 cerr << "Unable to seek to end of disk! Perhaps the 'e' option on the experts' menu\n"
969 << "will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400970 } // if
971 } // if
972
973 // Now write the secondary partition tables....
srs56941e093722010-01-05 00:14:19 -0500974 if (allOK) {
srs56946699b012010-02-04 00:55:30 -0500975 if (!littleEndian)
976 ReversePartitionBytes();
srs5694546a9c72010-01-26 16:00:26 -0500977 if (myDisk.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -0400978 allOK = 0;
srs56946699b012010-02-04 00:55:30 -0500979 if (!littleEndian)
980 ReversePartitionBytes();
981 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400982
983 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500984 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500985 offset = mainHeader.backupLBA;
srs56946699b012010-02-04 00:55:30 -0500986 if (!littleEndian)
987 ReverseHeaderBytes(&secondHeader);
988 if (myDisk.Seek(offset)) {
srs5694546a9c72010-01-26 16:00:26 -0500989 if (myDisk.Write(&secondHeader, 512) == -1)
srs56941e093722010-01-05 00:14:19 -0500990 allOK = 0;
srs5694546a9c72010-01-26 16:00:26 -0500991 } else allOK = 0; // if (myDisk.Seek()...)
srs56946699b012010-02-04 00:55:30 -0500992 if (!littleEndian)
993 ReverseHeaderBytes(&secondHeader);
994 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400995
996 // re-read the partition table
997 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500998 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400999 } // if
1000
1001 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001002 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001003 } else {
srs5694fed16d02010-01-27 23:03:40 -05001004 cerr << "Warning! An error was reported when writing the partition table! This error\n"
1005 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
1006 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001007 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001008 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001009 } else {
srs5694fed16d02010-01-27 23:03:40 -05001010 cerr << "Unable to open device " << device << " for writing! Errno is "
1011 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001012 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001013 } // if/else
1014 } else {
srs5694fed16d02010-01-27 23:03:40 -05001015 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001016 } // if
1017
srs56946699b012010-02-04 00:55:30 -05001018/* if (IsLittleEndian() == 0) {
srs56942a9f5da2009-08-26 00:48:01 -04001019 // Reverse (normalize) header bytes first, since ReversePartitionBytes()
1020 // requires non-reversed data in mainHeader...
1021 ReverseHeaderBytes(&mainHeader);
1022 ReverseHeaderBytes(&secondHeader);
1023 ReversePartitionBytes();
srs56946699b012010-02-04 00:55:30 -05001024 } // if */
srs56942a9f5da2009-08-26 00:48:01 -04001025
srs5694e7b4ff92009-08-18 13:16:10 -04001026 return (allOK);
1027} // GPTData::SaveGPTData()
1028
1029// Save GPT data to a backup file. This function does much less error
1030// checking than SaveGPTData(). It can therefore preserve many types of
1031// corruption for later analysis; however, it preserves only the MBR,
1032// the main GPT header, the backup GPT header, and the main partition
1033// table; it discards the backup partition table, since it should be
1034// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001035int GPTData::SaveGPTBackup(const string & filename) {
1036 int allOK = 1;
srs56942a9f5da2009-08-26 00:48:01 -04001037 uint32_t numParts;
srs5694546a9c72010-01-26 16:00:26 -05001038 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001039
srs5694546a9c72010-01-26 16:00:26 -05001040 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001041 // Recomputing the CRCs is likely to alter them, which could be bad
1042 // if the intent is to save a potentially bad GPT for later analysis;
1043 // but if we don't do this, we get bogus errors when we load the
1044 // backup. I'm favoring misses over false alarms....
1045 RecomputeCRCs();
1046
srs56942a9f5da2009-08-26 00:48:01 -04001047 // Reverse the byte order, if necessary....
1048 numParts = mainHeader.numParts;
1049 if (IsLittleEndian() == 0) {
1050 ReversePartitionBytes();
1051 ReverseHeaderBytes(&mainHeader);
1052 ReverseHeaderBytes(&secondHeader);
1053 } // if
1054
1055 // Now write the protective MBR...
srs5694546a9c72010-01-26 16:00:26 -05001056 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001057
1058 // Now write the main GPT header...
1059 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001060 // MBR write closed disk, so re-open and seek to end....
1061 backupFile.OpenForWrite();
1062 backupFile.Seek(1);
1063 if (backupFile.Write(&mainHeader, 512) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001064 allOK = 0;
1065
1066 // Now write the secondary GPT header...
1067 if (allOK)
srs5694546a9c72010-01-26 16:00:26 -05001068 if (backupFile.Write(&secondHeader, 512) == -1)
srs5694e4ac11e2009-08-31 10:13:04 -04001069 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001070
1071 // Now write the main partition tables...
1072 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001073 if (backupFile.Write(partitions, GPT_SIZE * numParts) == -1)
srs5694e7b4ff92009-08-18 13:16:10 -04001074 allOK = 0;
1075 } // if
1076
1077 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001078 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001079 } else {
srs5694fed16d02010-01-27 23:03:40 -05001080 cerr << "Warning! An error was reported when writing the backup file.\n"
1081 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001082 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001083 backupFile.Close();
srs56942a9f5da2009-08-26 00:48:01 -04001084
1085 // Now reverse the byte-order reversal, if necessary....
1086 if (IsLittleEndian() == 0) {
1087 ReverseHeaderBytes(&mainHeader);
1088 ReverseHeaderBytes(&secondHeader);
1089 ReversePartitionBytes();
1090 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001091 } else {
srs5694fed16d02010-01-27 23:03:40 -05001092 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001093 allOK = 0;
1094 } // if/else
1095 return allOK;
1096} // GPTData::SaveGPTBackup()
1097
1098// Load GPT data from a backup file created by SaveGPTBackup(). This function
1099// does minimal error checking. It returns 1 if it completed successfully,
1100// 0 if there was a problem. In the latter case, it creates a new empty
1101// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001102int GPTData::LoadGPTBackup(const string & filename) {
1103 int allOK = 1, val;
srs5694e7b4ff92009-08-18 13:16:10 -04001104 uint32_t numParts, sizeOfEntries, sizeOfParts, newCRC;
srs56942a9f5da2009-08-26 00:48:01 -04001105 int littleEndian = 1;
srs5694546a9c72010-01-26 16:00:26 -05001106 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001107
srs5694546a9c72010-01-26 16:00:26 -05001108 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001109 if (IsLittleEndian() == 0)
1110 littleEndian = 0;
1111
srs5694e7b4ff92009-08-18 13:16:10 -04001112 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001113 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001114
1115 // Load the main GPT header, check its vaility, and set the GPT
1116 // size based on the data
srs5694546a9c72010-01-26 16:00:26 -05001117 if (backupFile.Read(&mainHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001118 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001119 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001120 mainCrcOk = CheckHeaderCRC(&mainHeader);
1121
srs56942a9f5da2009-08-26 00:48:01 -04001122 // Reverse byte order, if necessary
1123 if (littleEndian == 0) {
1124 ReverseHeaderBytes(&mainHeader);
1125 } // if
1126
srs5694e7b4ff92009-08-18 13:16:10 -04001127 // Load the backup GPT header in much the same way as the main
1128 // GPT header....
srs5694546a9c72010-01-26 16:00:26 -05001129 if (backupFile.Read(&secondHeader, 512) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05001130 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001131 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001132 secondCrcOk = CheckHeaderCRC(&secondHeader);
1133
srs56942a9f5da2009-08-26 00:48:01 -04001134 // Reverse byte order, if necessary
1135 if (littleEndian == 0) {
1136 ReverseHeaderBytes(&secondHeader);
1137 } // if
1138
srs5694e7b4ff92009-08-18 13:16:10 -04001139 // Return valid headers code: 0 = both headers bad; 1 = main header
1140 // good, backup bad; 2 = backup header good, main header bad;
1141 // 3 = both headers good. Note these codes refer to valid GPT
1142 // signatures and version numbers; more subtle problems will elude
1143 // this check!
1144 if ((val = CheckHeaderValidity()) > 0) {
1145 if (val == 2) { // only backup header seems to be good
1146 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001147 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001148 } else { // main header is OK
1149 numParts = mainHeader.numParts;
1150 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1151 } // if/else
1152
1153 SetGPTSize(numParts);
1154
1155 // If current disk size doesn't match that of backup....
1156 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001157 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1158 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001159 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001160 } // if
1161
1162 // Load main partition table, and record whether its CRC
1163 // matches the stored value
1164 sizeOfParts = numParts * sizeOfEntries;
srs5694e321d442010-01-29 17:44:04 -05001165 if (backupFile.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -05001166 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
srs56945d58fe02010-01-03 20:57:08 -05001167 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001168
1169 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
1170 mainPartsCrcOk = (newCRC == mainHeader.partitionEntriesCRC);
1171 secondPartsCrcOk = (newCRC == secondHeader.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -04001172 // Reverse byte order, if necessary
srs5694e4ac11e2009-08-31 10:13:04 -04001173 if (littleEndian == 0) {
1174 ReversePartitionBytes();
1175 } // if
srs56942a9f5da2009-08-26 00:48:01 -04001176
srs5694e7b4ff92009-08-18 13:16:10 -04001177 } else {
1178 allOK = 0;
1179 } // if/else
1180 } else {
1181 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001182 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001183 } // if/else
1184
1185 // Something went badly wrong, so blank out partitions
1186 if (allOK == 0) {
1187 ClearGPTData();
1188 protectiveMBR.MakeProtectiveMBR();
1189 } // if
1190 return allOK;
1191} // GPTData::LoadGPTBackup()
1192
srs5694e4ac11e2009-08-31 10:13:04 -04001193// Tell user whether Apple Partition Map (APM) was discovered....
1194void GPTData::ShowAPMState(void) {
1195 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001196 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001197 else
srs5694fed16d02010-01-27 23:03:40 -05001198 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001199} // GPTData::ShowAPMState()
1200
1201// Tell user about the state of the GPT data....
1202void GPTData::ShowGPTState(void) {
1203 switch (state) {
1204 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001205 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001206 break;
1207 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001208 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001209 break;
1210 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001211 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001212 break;
1213 default:
srs5694fed16d02010-01-27 23:03:40 -05001214 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001215 break;
1216 } // switch
1217} // GPTData::ShowGPTState()
1218
1219// Display the basic GPT data
1220void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001221 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001222 uint64_t temp, totalFree;
1223
srs5694fed16d02010-01-27 23:03:40 -05001224 cout << "Disk " << device << ": " << diskSize << " sectors, "
1225 << BytesToSI(diskSize * blockSize) << "\n";
1226 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001227 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001228 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1229 cout << "First usable sector is " << mainHeader.firstUsableLBA
1230 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001231 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001232 cout << "Total free space is " << totalFree << " sectors ("
1233 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1234 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001235 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001236 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001237 } // for
1238} // GPTData::DisplayGPTData()
1239
1240// Get partition number from user and then call ShowPartDetails(partNum)
1241// to show its detailed information
1242void GPTData::ShowDetails(void) {
1243 int partNum;
1244 uint32_t low, high;
1245
1246 if (GetPartRange(&low, &high) > 0) {
1247 partNum = GetPartNum();
1248 ShowPartDetails(partNum);
1249 } else {
srs5694fed16d02010-01-27 23:03:40 -05001250 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001251 } // if/else
1252} // GPTData::ShowDetails()
1253
1254// Show detailed information on the specified partition
1255void GPTData::ShowPartDetails(uint32_t partNum) {
1256 if (partitions[partNum].GetFirstLBA() != 0) {
1257 partitions[partNum].ShowDetails(blockSize);
1258 } else {
srs5694fed16d02010-01-27 23:03:40 -05001259 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001260 } // if
1261} // GPTData::ShowPartDetails()
1262
1263/*********************************************************************
1264 * *
1265 * Begin functions that obtain information from the users, and often *
1266 * do something with that information (call other functions) *
1267 * *
1268 *********************************************************************/
1269
1270// Prompts user for partition number and returns the result.
1271uint32_t GPTData::GetPartNum(void) {
1272 uint32_t partNum;
1273 uint32_t low, high;
1274 char prompt[255];
1275
1276 if (GetPartRange(&low, &high) > 0) {
1277 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1278 partNum = GetNumber(low + 1, high + 1, low, prompt);
1279 } else partNum = 1;
1280 return (partNum - 1);
1281} // GPTData::GetPartNum()
1282
1283// What it says: Resize the partition table. (Default is 128 entries.)
1284void GPTData::ResizePartitionTable(void) {
1285 int newSize;
1286 char prompt[255];
1287 uint32_t curLow, curHigh;
1288
srs5694fed16d02010-01-27 23:03:40 -05001289 cout << "Current partition table size is " << mainHeader.numParts << ".\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001290 GetPartRange(&curLow, &curHigh);
1291 curHigh++; // since GetPartRange() returns numbers starting from 0...
1292 // There's no point in having fewer than four partitions....
1293 if (curHigh < 4)
1294 curHigh = 4;
1295 sprintf(prompt, "Enter new size (%d up, default %d): ", (int) curHigh,
1296 (int) NUM_GPT_ENTRIES);
1297 newSize = GetNumber(4, 65535, 128, prompt);
1298 if (newSize < 128) {
srs5694fed16d02010-01-27 23:03:40 -05001299 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
1300 << "which works out to 128 entries. In practice, smaller tables seem to\n"
1301 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
1302 << "the resize, but you may want to reconsider this action and undo it.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001303 } // if
1304 SetGPTSize(newSize);
1305} // GPTData::ResizePartitionTable()
1306
1307// Interactively create a partition
1308void GPTData::CreatePartition(void) {
1309 uint64_t firstBlock, firstInLargest, lastBlock, sector;
srs5694e321d442010-01-29 17:44:04 -05001310 uint32_t firstFreePart = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001311 char prompt[255];
srs5694e321d442010-01-29 17:44:04 -05001312 int partNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001313
1314 // Find first free partition...
1315 while (partitions[firstFreePart].GetFirstLBA() != 0) {
1316 firstFreePart++;
1317 } // while
1318
1319 if (((firstBlock = FindFirstAvailable()) != 0) &&
1320 (firstFreePart < mainHeader.numParts)) {
1321 lastBlock = FindLastAvailable(firstBlock);
1322 firstInLargest = FindFirstInLargest();
1323
1324 // Get partition number....
1325 do {
1326 sprintf(prompt, "Partition number (%d-%d, default %d): ", firstFreePart + 1,
1327 mainHeader.numParts, firstFreePart + 1);
1328 partNum = GetNumber(firstFreePart + 1, mainHeader.numParts,
1329 firstFreePart + 1, prompt) - 1;
1330 if (partitions[partNum].GetFirstLBA() != 0)
srs5694fed16d02010-01-27 23:03:40 -05001331 cout << "partition " << partNum + 1 << " is in use.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001332 } while (partitions[partNum].GetFirstLBA() != 0);
1333
1334 // Get first block for new partition...
srs56945d58fe02010-01-03 20:57:08 -05001335 sprintf(prompt, "First sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1336 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1337 (unsigned long long) firstInLargest);
srs5694e4ac11e2009-08-31 10:13:04 -04001338 do {
1339 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt);
1340 } while (IsFree(sector) == 0);
srs56941d1448a2009-12-31 21:20:19 -05001341 Align(&sector); // Align sector to correct multiple
srs5694e4ac11e2009-08-31 10:13:04 -04001342 firstBlock = sector;
1343
1344 // Get last block for new partitions...
1345 lastBlock = FindLastInFree(firstBlock);
srs56945d58fe02010-01-03 20:57:08 -05001346 sprintf(prompt, "Last sector (%llu-%llu, default = %llu) or {+-}size{KMGT}: ",
1347 (unsigned long long) firstBlock, (unsigned long long) lastBlock,
1348 (unsigned long long) lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001349 do {
1350 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, prompt);
1351 } while (IsFree(sector) == 0);
1352 lastBlock = sector;
1353
srs5694ba00fed2010-01-12 18:18:36 -05001354 firstFreePart = CreatePartition(partNum, firstBlock, lastBlock);
srs5694e4ac11e2009-08-31 10:13:04 -04001355 partitions[partNum].ChangeType();
srs56946699b012010-02-04 00:55:30 -05001356 partitions[partNum].SetDefaultDescription();
srs5694ba00fed2010-01-12 18:18:36 -05001357 } else {
srs5694fed16d02010-01-27 23:03:40 -05001358 cout << "No free sectors available\n";
srs5694ba00fed2010-01-12 18:18:36 -05001359 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001360} // GPTData::CreatePartition()
1361
1362// Interactively delete a partition (duh!)
1363void GPTData::DeletePartition(void) {
1364 int partNum;
1365 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001366 char prompt[255];
1367
1368 if (GetPartRange(&low, &high) > 0) {
1369 sprintf(prompt, "Partition number (%d-%d): ", low + 1, high + 1);
1370 partNum = GetNumber(low + 1, high + 1, low, prompt);
srs5694ba00fed2010-01-12 18:18:36 -05001371 DeletePartition(partNum - 1);
srs5694e4ac11e2009-08-31 10:13:04 -04001372 } else {
srs5694fed16d02010-01-27 23:03:40 -05001373 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001374 } // if/else
1375} // GPTData::DeletePartition()
1376
1377// Prompt user for a partition number, then change its type code
1378// using ChangeGPTType(struct GPTPartition*) function.
1379void GPTData::ChangePartType(void) {
1380 int partNum;
1381 uint32_t low, high;
1382
1383 if (GetPartRange(&low, &high) > 0) {
1384 partNum = GetPartNum();
1385 partitions[partNum].ChangeType();
1386 } else {
srs5694fed16d02010-01-27 23:03:40 -05001387 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001388 } // if/else
1389} // GPTData::ChangePartType()
1390
1391// Partition attributes seem to be rarely used, but I want a way to
1392// adjust them for completeness....
1393void GPTData::SetAttributes(uint32_t partNum) {
1394 Attributes theAttr;
1395
1396 theAttr.SetAttributes(partitions[partNum].GetAttributes());
1397 theAttr.DisplayAttributes();
1398 theAttr.ChangeAttributes();
1399 partitions[partNum].SetAttributes(theAttr.GetAttributes());
1400} // GPTData::SetAttributes()
1401
srs5694c0ca8f82009-08-20 21:35:25 -04001402// This function destroys the on-disk GPT structures. Returns 1 if the
1403// user confirms destruction, 0 if the user aborts.
srs5694978041c2009-09-21 20:51:47 -04001404// If prompt == 0, don't ask user about proceeding and do NOT wipe out
1405// MBR. (Set prompt == 0 when doing a GPT-to-MBR conversion.)
srs5694ba00fed2010-01-12 18:18:36 -05001406// If prompt == -1, don't ask user about proceeding and DO wipe out
1407// MBR.
srs5694978041c2009-09-21 20:51:47 -04001408int GPTData::DestroyGPT(int prompt) {
srs5694e321d442010-01-29 17:44:04 -05001409 int i, sum, tableSize;
srs5694fed16d02010-01-27 23:03:40 -05001410 uint8_t blankSector[512], goOn = 'Y', blank = 'N';
1411 uint8_t* emptyTable;
srs5694c0ca8f82009-08-20 21:35:25 -04001412
1413 for (i = 0; i < 512; i++) {
srs5694fed16d02010-01-27 23:03:40 -05001414 blankSector[i] = 0;
srs5694c0ca8f82009-08-20 21:35:25 -04001415 } // for
1416
srs5694ba00fed2010-01-12 18:18:36 -05001417 if (((apmFound) || (bsdFound)) && (prompt > 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001418 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
1419 << "damage any APM or BSD partitions on this disk!\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001420 } // if APM or BSD
srs5694ba00fed2010-01-12 18:18:36 -05001421 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001422 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
srs5694978041c2009-09-21 20:51:47 -04001423 goOn = GetYN();
1424 } // if
srs5694c0ca8f82009-08-20 21:35:25 -04001425 if (goOn == 'Y') {
srs5694546a9c72010-01-26 16:00:26 -05001426 if (myDisk.OpenForWrite(device)) {
1427 myDisk.Seek(mainHeader.currentLBA); // seek to GPT header
1428 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001429 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001430 } // if
srs5694546a9c72010-01-26 16:00:26 -05001431 myDisk.Seek(mainHeader.partitionEntriesLBA); // seek to partition table
srs56941e093722010-01-05 00:14:19 -05001432 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
srs5694fed16d02010-01-27 23:03:40 -05001433 emptyTable = (uint8_t*) malloc(tableSize);
srs56941e093722010-01-05 00:14:19 -05001434 for (i = 0; i < tableSize; i++)
srs5694fed16d02010-01-27 23:03:40 -05001435 emptyTable[i] = 0;
srs5694546a9c72010-01-26 16:00:26 -05001436 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001437 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001438 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001439 myDisk.Seek(secondHeader.partitionEntriesLBA); // seek to partition table
1440 sum = myDisk.Write(emptyTable, tableSize);
srs56941e093722010-01-05 00:14:19 -05001441 if (sum != tableSize)
srs5694fed16d02010-01-27 23:03:40 -05001442 cerr << "Warning! GPT backup partition table not overwritten! Error is " << errno << "\n";
srs5694546a9c72010-01-26 16:00:26 -05001443 myDisk.Seek(secondHeader.currentLBA); // seek to GPT header
1444 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001445 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs56945d58fe02010-01-03 20:57:08 -05001446 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001447 if (prompt > 0) {
srs5694fed16d02010-01-27 23:03:40 -05001448 cout << "Blank out MBR? ";
srs5694978041c2009-09-21 20:51:47 -04001449 blank = GetYN();
srs5694ba00fed2010-01-12 18:18:36 -05001450 } // if
srs5694978041c2009-09-21 20:51:47 -04001451 // Note on below: Touch the MBR only if the user wants it completely
1452 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
1453 // the MBR, but this could wipe out a valid MBR that the program
1454 // had subsequently discarded (say, if it conflicted with older GPT
1455 // structures).
srs5694ba00fed2010-01-12 18:18:36 -05001456 if ((blank == 'Y') || (prompt < 0)) {
srs5694546a9c72010-01-26 16:00:26 -05001457 myDisk.Seek(0);
1458 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
srs5694fed16d02010-01-27 23:03:40 -05001459 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
srs56945d58fe02010-01-03 20:57:08 -05001460 } // if
srs5694978041c2009-09-21 20:51:47 -04001461 } else {
srs5694fed16d02010-01-27 23:03:40 -05001462 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
1463 << "with fdisk or another tool.\n";
srs5694e35eb1b2009-09-14 00:29:34 -04001464 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001465 myDisk.DiskSync();
1466 myDisk.Close();
srs5694fed16d02010-01-27 23:03:40 -05001467 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1468 << "other utilities. Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001469 } else {
srs5694fed16d02010-01-27 23:03:40 -05001470 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
srs5694c0ca8f82009-08-20 21:35:25 -04001471 } // if/else (fd != -1)
1472 } // if (goOn == 'Y')
1473 return (goOn == 'Y');
1474} // GPTData::DestroyGPT()
1475
srs5694e4ac11e2009-08-31 10:13:04 -04001476/**************************************************************************
1477 * *
1478 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1479 * (some of these functions may require user interaction) *
1480 * *
1481 **************************************************************************/
1482
1483// Examines the MBR & GPT data, and perhaps asks the user questions, to
1484// determine which set of data to use: the MBR (use_mbr), the GPT (use_gpt),
1485// or create a new set of partitions (use_new)
1486WhichToUse GPTData::UseWhichPartitions(void) {
1487 WhichToUse which = use_new;
1488 MBRValidity mbrState;
1489 int answer;
1490
1491 mbrState = protectiveMBR.GetValidity();
1492
1493 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001494 cout << "\n***************************************************************\n"
1495 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001496 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001497 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1498 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001499 } // if
srs5694fed16d02010-01-27 23:03:40 -05001500 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001501 which = use_mbr;
1502 } // if
1503
1504 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001505 cout << "\n**********************************************************************\n"
1506 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1507 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001508 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001509 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1510 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1511 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001512 } // if
srs5694fed16d02010-01-27 23:03:40 -05001513 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001514 which = use_bsd;
1515 } // if
1516
1517 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001518 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001519 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001520 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001521 } // if
1522 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001523 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001524 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001525 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001526 } // if
1527 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001528 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001529 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001530 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001531 } // if
1532 if ((state == gpt_valid) && (mbrState == mbr)) {
srs56943c0af382010-01-15 19:19:18 -05001533 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -05001534 cout << "Found valid MBR and GPT. Which do you want to use?\n";
1535 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001536 if (answer == 1) {
1537 which = use_mbr;
1538 } else if (answer == 2) {
1539 which = use_gpt;
srs5694fed16d02010-01-27 23:03:40 -05001540 cout << "Using GPT and creating fresh protective MBR.\n";
srs56943c0af382010-01-15 19:19:18 -05001541 } else which = use_new;
1542 } else which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001543 } // if
1544
1545 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
1546 // problems)
1547 if (state == gpt_corrupt) {
srs56943c0af382010-01-15 19:19:18 -05001548 if (beQuiet) {
1549 which = use_abort;
1550 } else {
1551 if ((mbrState == mbr) || (mbrState == hybrid)) {
srs5694fed16d02010-01-27 23:03:40 -05001552 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
1553 << "GPT MAY permit recovery of GPT data.)\n";
1554 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001555 if (answer == 1) {
1556 which = use_mbr;
srs56943c0af382010-01-15 19:19:18 -05001557 } else if (answer == 2) {
1558 which = use_gpt;
1559 } else which = use_new;
1560 } else if (mbrState == invalid) {
srs5694fed16d02010-01-27 23:03:40 -05001561 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
1562 << "GPT MAY permit recovery of GPT data.)\n";
1563 answer = GetNumber(1, 2, 1, " 1 - GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs56943c0af382010-01-15 19:19:18 -05001564 if (answer == 1) {
1565 which = use_gpt;
1566 } else which = use_new;
1567 } else { // corrupt GPT, MBR indicates it's a GPT disk....
srs5694fed16d02010-01-27 23:03:40 -05001568 cout << "\a\a****************************************************************************\n"
1569 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1570 << "verification and recovery are STRONGLY recommended.\n"
1571 << "****************************************************************************\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001572 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001573 } // if/else/else
1574 } // else (beQuiet)
srs5694e4ac11e2009-08-31 10:13:04 -04001575 } // if (corrupt GPT)
1576
1577 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001578 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001579
1580 return which;
1581} // UseWhichPartitions()
1582
1583// Convert MBR partition table into GPT form
1584int GPTData::XFormPartitions(void) {
1585 int i, numToConvert;
1586 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001587
1588 // Clear out old data & prepare basics....
1589 ClearGPTData();
1590
1591 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001592 if (mainHeader.numParts > (MAX_MBR_PARTS))
1593 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001594 else
1595 numToConvert = mainHeader.numParts;
1596
1597 for (i = 0; i < numToConvert; i++) {
1598 origType = protectiveMBR.GetType(i);
1599 // don't waste CPU time trying to convert extended, hybrid protective, or
1600 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001601 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001602 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001603 partitions[i] = protectiveMBR.AsGPT(i);
1604 } // for
1605
1606 // Convert MBR into protective MBR
1607 protectiveMBR.MakeProtectiveMBR();
1608
1609 // Record that all original CRCs were OK so as not to raise flags
1610 // when doing a disk verification
1611 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1612
1613 return (1);
1614} // GPTData::XFormPartitions()
1615
1616// Transforms BSD disklabel on the specified partition (numbered from 0).
1617// If an invalid partition number is given, the program prompts for one.
srs56946699b012010-02-04 00:55:30 -05001618// (Default for i is -1; called without an option, it therefore prompts.)
srs5694e4ac11e2009-08-31 10:13:04 -04001619// Returns the number of new partitions created.
1620int GPTData::XFormDisklabel(int i) {
1621 uint32_t low, high, partNum, startPart;
1622 uint16_t hexCode;
1623 int goOn = 1, numDone = 0;
1624 BSDData disklabel;
1625
1626 if (GetPartRange(&low, &high) != 0) {
srs5694e321d442010-01-29 17:44:04 -05001627 if ((i < (int) low) || (i > (int) high))
srs5694e4ac11e2009-08-31 10:13:04 -04001628 partNum = GetPartNum();
1629 else
1630 partNum = (uint32_t) i;
1631
1632 // Find the partition after the last used one
1633 startPart = high + 1;
1634
1635 // Now see if the specified partition has a BSD type code....
1636 hexCode = partitions[partNum].GetHexType();
1637 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
srs5694fed16d02010-01-27 23:03:40 -05001638 cout << "Specified partition doesn't have a disklabel partition type "
1639 << "code.\nContinue anyway? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001640 goOn = (GetYN() == 'Y');
1641 } // if
1642
1643 // If all is OK, read the disklabel and convert it.
1644 if (goOn) {
srs5694e321d442010-01-29 17:44:04 -05001645 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
srs5694e4ac11e2009-08-31 10:13:04 -04001646 partitions[partNum].GetLastLBA());
1647 if ((goOn) && (disklabel.IsDisklabel())) {
1648 numDone = XFormDisklabel(&disklabel, startPart);
1649 if (numDone == 1)
srs5694fed16d02010-01-27 23:03:40 -05001650 cout << "Converted " << numDone << " BSD partition.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001651 else
srs5694fed16d02010-01-27 23:03:40 -05001652 cout << "Converted " << numDone << " BSD partitions.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001653 } else {
srs5694fed16d02010-01-27 23:03:40 -05001654 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001655 } // if/else
1656 } // if
1657 if (numDone > 0) { // converted partitions; delete carrier
1658 partitions[partNum].BlankPartition();
1659 } // if
1660 } else {
srs5694fed16d02010-01-27 23:03:40 -05001661 cout << "No partitions\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001662 } // if/else
1663 return numDone;
1664} // GPTData::XFormDisklable(int i)
1665
1666// Transform the partitions on an already-loaded BSD disklabel...
srs5694e321d442010-01-29 17:44:04 -05001667int GPTData::XFormDisklabel(BSDData* disklabel, uint32_t startPart) {
srs5694e4ac11e2009-08-31 10:13:04 -04001668 int i, numDone = 0;
1669
1670 if ((disklabel->IsDisklabel()) && (startPart >= 0) &&
srs56946699b012010-02-04 00:55:30 -05001671 (startPart < mainHeader.numParts)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001672 for (i = 0; i < disklabel->GetNumParts(); i++) {
1673 partitions[i + startPart] = disklabel->AsGPT(i);
1674 if (partitions[i + startPart].GetFirstLBA() != UINT64_C(0))
1675 numDone++;
1676 } // for
1677 } // if
1678
1679 // Record that all original CRCs were OK so as not to raise flags
1680 // when doing a disk verification
1681 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1682
1683 return numDone;
1684} // GPTData::XFormDisklabel(BSDData* disklabel)
1685
srs5694978041c2009-09-21 20:51:47 -04001686// Add one GPT partition to MBR. Used by XFormToMBR() and MakeHybrid()
1687// functions. Returns 1 if operation was successful.
1688int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1689 int allOK = 1, typeCode, bootable;
1690 uint64_t length;
1691 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001692 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001693
srs5694fed16d02010-01-27 23:03:40 -05001694 cout.setf(ios::uppercase);
1695 cout.fill('0');
1696
srs5694978041c2009-09-21 20:51:47 -04001697 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001698 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001699 allOK = 0;
1700 } // if
1701 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001702 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001703 allOK = 0;
1704 } // if
1705 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001706 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001707 allOK = 0;
1708 } // if
1709 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1710 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1711 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001712 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1713 << " some OSes may\nreact strangely.\n";
srs5694978041c2009-09-21 20:51:47 -04001714 } // if partition ends past 32-bit (usually 2TiB) boundary
1715 do {
srs5694fed16d02010-01-27 23:03:40 -05001716 cout << "Enter an MBR hex code (default " << hex;
1717 cout.width(2);
srs56946699b012010-02-04 00:55:30 -05001718 cout << partitions[gptPart].GetHexType() / 0x0100 << "): ";
srs56945d58fe02010-01-03 20:57:08 -05001719 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001720 if (line[0] == '\n')
1721 typeCode = partitions[gptPart].GetHexType() / 256;
srs5694fed16d02010-01-27 23:03:40 -05001722 else
1723 sscanf(line, "%x", &typeCode);
srs5694978041c2009-09-21 20:51:47 -04001724 } while ((typeCode <= 0) || (typeCode > 255));
srs5694fed16d02010-01-27 23:03:40 -05001725 cout << "Set the bootable flag? ";
srs5694978041c2009-09-21 20:51:47 -04001726 bootable = (GetYN() == 'Y');
1727 length = partitions[gptPart].GetLengthLBA();
1728 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1729 (uint32_t) length, typeCode, bootable);
1730 } else { // partition out of range
srs5694fed16d02010-01-27 23:03:40 -05001731 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1732 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001733 allOK = 0;
1734 } // if/else
srs5694fed16d02010-01-27 23:03:40 -05001735 cout.fill(' ');
srs5694978041c2009-09-21 20:51:47 -04001736 return allOK;
1737} // GPTData::OnePartToMBR()
1738
1739// Convert the GPT to MBR form. This function is necessarily limited; it
1740// handles at most four partitions and creates layouts that ignore CHS
1741// geometries. Returns the number of converted partitions; if this value
1742// is over 0, the calling function should call DestroyGPT() to destroy
1743// the GPT data, and then exit.
1744int GPTData::XFormToMBR(void) {
1745 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001746 char* junk;
srs5694e321d442010-01-29 17:44:04 -05001747 int j, numParts, numConverted = 0;
1748 uint32_t i, partNums[4];
srs5694978041c2009-09-21 20:51:47 -04001749
1750 // Get the numbers of up to four partitions to add to the
1751 // hybrid MBR....
1752 numParts = CountParts();
srs5694fed16d02010-01-27 23:03:40 -05001753 cout << "Counted " << numParts << " partitions.\n";
srs5694978041c2009-09-21 20:51:47 -04001754
1755 // Prepare the MBR for conversion (empty it of existing partitions).
1756 protectiveMBR.EmptyMBR(0);
1757 protectiveMBR.SetDiskSize(diskSize);
1758
1759 if (numParts > 4) { // Over four partitions; engage in triage
srs5694fed16d02010-01-27 23:03:40 -05001760 cout << "Type from one to four GPT partition numbers, separated by spaces, to be\n"
1761 << "used in the MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001762 junk = fgets(line, 255, stdin);
srs5694978041c2009-09-21 20:51:47 -04001763 numParts = sscanf(line, "%d %d %d %d", &partNums[0], &partNums[1],
1764 &partNums[2], &partNums[3]);
1765 } else { // Four or fewer partitions; convert them all
1766 i = j = 0;
1767 while ((j < numParts) && (i < mainHeader.numParts)) {
1768 if (partitions[i].GetFirstLBA() > 0) { // if GPT part. is defined
1769 partNums[j++] = ++i; // flag it for conversion
1770 } else i++;
1771 } // while
1772 } // if/else
1773
srs5694e321d442010-01-29 17:44:04 -05001774 for (i = 0; i < (uint32_t) numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001775 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001776 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001777 numConverted += OnePartToMBR(j, i);
1778 } // for
srs5694fed16d02010-01-27 23:03:40 -05001779 cout << "MBR writing returned " << protectiveMBR.WriteMBRData(&myDisk) << "\n";
srs5694978041c2009-09-21 20:51:47 -04001780 return numConverted;
1781} // GPTData::XFormToMBR()
1782
srs5694e4ac11e2009-08-31 10:13:04 -04001783// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
1784// OSes that don't understand GPT.
1785void GPTData::MakeHybrid(void) {
1786 uint32_t partNums[3];
1787 char line[255];
srs56945d58fe02010-01-03 20:57:08 -05001788 char* junk;
srs5694978041c2009-09-21 20:51:47 -04001789 int numParts, numConverted = 0, i, j, typeCode, mbrNum;
srs5694e4ac11e2009-08-31 10:13:04 -04001790 char fillItUp = 'M'; // fill extra partition entries? (Yes/No/Maybe)
srs5694978041c2009-09-21 20:51:47 -04001791 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
srs5694e4ac11e2009-08-31 10:13:04 -04001792
srs5694fed16d02010-01-27 23:03:40 -05001793 cout << "\nWARNING! Hybrid MBRs are flaky and potentially dangerous! If you decide not\n"
1794 << "to use one, just hit the Enter key at the below prompt and your MBR\n"
1795 << "partition table will be untouched.\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -04001796
1797 // Now get the numbers of up to three partitions to add to the
1798 // hybrid MBR....
srs5694fed16d02010-01-27 23:03:40 -05001799 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
1800 << "added to the hybrid MBR, in sequence: ";
srs56945d58fe02010-01-03 20:57:08 -05001801 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001802 numParts = sscanf(line, "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
1803
1804 if (numParts > 0) {
1805 // Blank out the protective MBR, but leave the boot loader code
1806 // alone....
1807 protectiveMBR.EmptyMBR(0);
1808 protectiveMBR.SetDiskSize(diskSize);
srs5694fed16d02010-01-27 23:03:40 -05001809 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001810 eeFirst = GetYN();
1811 } // if
1812
1813 for (i = 0; i < numParts; i++) {
1814 j = partNums[i] - 1;
srs5694fed16d02010-01-27 23:03:40 -05001815 cout << "\nCreating entry for partition #" << j + 1 << "\n";
srs5694978041c2009-09-21 20:51:47 -04001816 if (eeFirst == 'Y')
1817 mbrNum = i + 1;
1818 else
1819 mbrNum = i;
1820 numConverted += OnePartToMBR(j, mbrNum);
srs5694e4ac11e2009-08-31 10:13:04 -04001821 } // for
1822
srs5694978041c2009-09-21 20:51:47 -04001823 if ((numParts > 0) && (numConverted > 0)) { // User opted to create a hybrid MBR....
srs5694e4ac11e2009-08-31 10:13:04 -04001824 // Create EFI protective partition that covers the start of the disk.
1825 // If this location (covering the main GPT data structures) is omitted,
1826 // Linux won't find any partitions on the disk. Note that this is
1827 // NUMBERED AFTER the hybrid partitions, contrary to what the
1828 // gptsync utility does. This is because Windows seems to choke on
1829 // disks with a 0xEE partition in the first slot and subsequent
1830 // additional partitions, unless it boots from the disk.
1831 if (eeFirst == 'Y')
1832 mbrNum = 0;
1833 else
1834 mbrNum = numParts;
1835 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), 0xEE);
srs5694978041c2009-09-21 20:51:47 -04001836 protectiveMBR.SetHybrid();
srs5694e4ac11e2009-08-31 10:13:04 -04001837
1838 // ... and for good measure, if there are any partition spaces left,
1839 // optionally create another protective EFI partition to cover as much
1840 // space as possible....
1841 for (i = 0; i < 4; i++) {
1842 if (protectiveMBR.GetType(i) == 0x00) { // unused entry....
1843 if (fillItUp == 'M') {
srs5694fed16d02010-01-27 23:03:40 -05001844 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
srs5694e4ac11e2009-08-31 10:13:04 -04001845 fillItUp = GetYN();
1846 typeCode = 0x00; // use this to flag a need to get type code
1847 } // if
1848 if (fillItUp == 'Y') {
1849 while ((typeCode <= 0) || (typeCode > 255)) {
srs5694fed16d02010-01-27 23:03:40 -05001850 cout << "Enter an MBR hex code (EE is EFI GPT, but may confuse MacOS): ";
srs5694e4ac11e2009-08-31 10:13:04 -04001851 // Comment on above: Mac OS treats disks with more than one
1852 // 0xEE MBR partition as MBR disks, not as GPT disks.
srs56945d58fe02010-01-03 20:57:08 -05001853 junk = fgets(line, 255, stdin);
srs5694e4ac11e2009-08-31 10:13:04 -04001854 sscanf(line, "%x", &typeCode);
1855 if (line[0] == '\n')
1856 typeCode = 0;
1857 } // while
1858 protectiveMBR.MakeBiggestPart(i, typeCode); // make a partition
1859 } // if (fillItUp == 'Y')
1860 } // if unused entry
1861 } // for (i = 0; i < 4; i++)
1862 } // if (numParts > 0)
1863} // GPTData::MakeHybrid()
1864
1865/**********************************************************************
1866 * *
1867 * Functions that adjust GPT data structures WITHOUT user interaction *
1868 * (they may display information for the user's benefit, though) *
1869 * *
1870 **********************************************************************/
1871
1872// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001873// necessary, copies data if it already exists. Returns 1 if all goes
1874// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001875int GPTData::SetGPTSize(uint32_t numEntries) {
1876 struct GPTPart* newParts;
1877 struct GPTPart* trash;
1878 uint32_t i, high, copyNum;
1879 int allOK = 1;
1880
1881 // First, adjust numEntries upward, if necessary, to get a number
1882 // that fills the allocated sectors
1883 i = blockSize / GPT_SIZE;
1884 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001885 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001886 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001887 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001888 } // if
1889
srs5694247657a2009-11-26 18:36:12 -05001890 // Do the work only if the # of partitions is changing. Along with being
1891 // efficient, this prevents mucking the with location of the secondary
1892 // partition table, which causes problems when loading data from a RAID
1893 // array that's been expanded because this function is called when loading
1894 // data.
srs5694546a9c72010-01-26 16:00:26 -05001895 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1896 || (partitions == NULL)) {
srs5694247657a2009-11-26 18:36:12 -05001897 newParts = (GPTPart*) calloc(numEntries, sizeof (GPTPart));
1898 if (newParts != NULL) {
1899 if (partitions != NULL) { // existing partitions; copy them over
1900 GetPartRange(&i, &high);
1901 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001902 cout << "The highest-numbered partition is " << high + 1
1903 << ", which is greater than the requested\n"
1904 << "partition table size of " << numEntries
1905 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001906 allOK = 0;
1907 } else { // go ahead with copy
1908 if (numEntries < mainHeader.numParts)
1909 copyNum = numEntries;
1910 else
1911 copyNum = mainHeader.numParts;
1912 for (i = 0; i < copyNum; i++) {
1913 newParts[i] = partitions[i];
1914 } // for
1915 trash = partitions;
1916 partitions = newParts;
1917 free(trash);
1918 } // if
1919 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001920 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001921 } // if/else existing partitions
1922 mainHeader.numParts = numEntries;
1923 secondHeader.numParts = numEntries;
1924 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1925 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1926 MoveSecondHeaderToEnd();
1927 if (diskSize > 0)
1928 CheckGPTSize();
1929 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001930 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001931 allOK = 0;
1932 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001933 } // if/else
1934 return (allOK);
1935} // GPTData::SetGPTSize()
1936
1937// Blank the partition array
1938void GPTData::BlankPartitions(void) {
1939 uint32_t i;
1940
1941 for (i = 0; i < mainHeader.numParts; i++) {
1942 partitions[i].BlankPartition();
1943 } // for
1944} // GPTData::BlankPartitions()
1945
srs5694ba00fed2010-01-12 18:18:36 -05001946// Delete a partition by number. Returns 1 if successful,
1947// 0 if there was a problem. Returns 1 if partition was in
1948// range, 0 if it was out of range.
1949int GPTData::DeletePartition(uint32_t partNum) {
1950 uint64_t startSector, length;
1951 uint32_t low, high, numParts, retval = 1;;
1952
1953 numParts = GetPartRange(&low, &high);
1954 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1955 // In case there's a protective MBR, look for & delete matching
1956 // MBR partition....
1957 startSector = partitions[partNum].GetFirstLBA();
1958 length = partitions[partNum].GetLengthLBA();
1959 protectiveMBR.DeleteByLocation(startSector, length);
1960
1961 // Now delete the GPT partition
1962 partitions[partNum].BlankPartition();
1963 } else {
srs5694fed16d02010-01-27 23:03:40 -05001964 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001965 retval = 0;
1966 } // if/else
1967 return retval;
1968} // GPTData::DeletePartition(uint32_t partNum)
1969
1970// Non-interactively create a partition. Note that this function is overloaded
1971// with another of the same name but different parameters; that one prompts
1972// the user for data. This one returns 1 if the operation was successful, 0
1973// if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001974uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001975 int retval = 1; // assume there'll be no problems
1976
1977 if (IsFreePartNum(partNum)) {
1978 Align(&startSector); // Align sector to correct multiple
1979 if (IsFree(startSector) && (startSector <= endSector)) {
1980 if (FindLastInFree(startSector) >= endSector) {
1981 partitions[partNum].SetFirstLBA(startSector);
1982 partitions[partNum].SetLastLBA(endSector);
1983 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001984 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001985 } else retval = 0; // if free space until endSector
1986 } else retval = 0; // if startSector is free
1987 } else retval = 0; // if legal partition number
1988 return retval;
1989} // GPTData::CreatePartition(partNum, startSector, endSector)
1990
srs5694e4ac11e2009-08-31 10:13:04 -04001991// Sort the GPT entries, eliminating gaps and making for a logical
1992// ordering. Relies on QuickSortGPT() for the bulk of the work
1993void GPTData::SortGPT(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001994 GPTPart temp;
srs5694546a9c72010-01-26 16:00:26 -05001995 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001996
1997 // First, find the last partition with data, so as not to
1998 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001999 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04002000
2001 // Now swap empties with the last partitions, to simplify the logic
2002 // in the Quicksort function....
2003 i = 0;
2004 while (i < lastPart) {
2005 if (partitions[i].GetFirstLBA() == 0) {
2006 temp = partitions[i];
2007 partitions[i] = partitions[lastPart];
2008 partitions[lastPart] = temp;
srs5694546a9c72010-01-26 16:00:26 -05002009 do {
2010 lastPart--;
2011 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04002012 } // if
2013 i++;
2014 } // while
2015
srs5694546a9c72010-01-26 16:00:26 -05002016 // If there are more empties than partitions in the range from 0 to lastPart,
2017 // the above leaves lastPart set too high, so we've got to adjust it to
2018 // prevent empties from migrating to the top of the list....
2019 GetPartRange(&firstPart, &lastPart);
2020
srs5694e4ac11e2009-08-31 10:13:04 -04002021 // Now call the recursive quick sort routine to do the real work....
2022 QuickSortGPT(partitions, 0, lastPart);
2023} // GPTData::SortGPT()
2024
2025// Set up data structures for entirely new set of partitions on the
2026// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04002027// Note that this function does NOT clear the protectiveMBR data
2028// structure, since it may hold the original MBR partitions if the
2029// program was launched on an MBR disk, and those may need to be
2030// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04002031int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002032 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04002033
2034 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05002035 if (partitions != NULL)
2036 free(partitions);
srs5694e4ac11e2009-08-31 10:13:04 -04002037 partitions = NULL;
2038 SetGPTSize(NUM_GPT_ENTRIES);
2039
2040 // Now initialize a bunch of stuff that's static....
2041 mainHeader.signature = GPT_SIGNATURE;
2042 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04002043 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04002044 mainHeader.reserved = 0;
2045 mainHeader.currentLBA = UINT64_C(1);
2046 mainHeader.partitionEntriesLBA = (uint64_t) 2;
2047 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
2048 for (i = 0; i < GPT_RESERVED; i++) {
2049 mainHeader.reserved2[i] = '\0';
2050 } // for
2051
2052 // Now some semi-static items (computed based on end of disk)
2053 mainHeader.backupLBA = diskSize - UINT64_C(1);
2054 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2055
2056 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05002057 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04002058
2059 // Copy main header to backup header
2060 RebuildSecondHeader();
2061
2062 // Blank out the partitions array....
2063 BlankPartitions();
2064
2065 // Flag all CRCs as being OK....
2066 mainCrcOk = 1;
2067 secondCrcOk = 1;
2068 mainPartsCrcOk = 1;
2069 secondPartsCrcOk = 1;
2070
2071 return (goOn);
2072} // GPTData::ClearGPTData()
2073
srs5694247657a2009-11-26 18:36:12 -05002074// Set the location of the second GPT header data to the end of the disk.
2075// Used internally and called by the 'e' option on the recovery &
2076// transformation menu, to help users of RAID arrays who add disk space
2077// to their arrays.
2078void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05002079 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2080 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2081 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2082} // GPTData::FixSecondHeaderLocation()
2083
srs56940a697312010-01-28 21:10:52 -05002084int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05002085 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05002086
2087 if (!IsFreePartNum(partNum)) {
2088 partitions[partNum].SetName(theName);
2089 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05002090
2091 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04002092} // GPTData::SetName
2093
2094// Set the disk GUID to the specified value. Note that the header CRCs must
2095// be recomputed after calling this function.
2096void GPTData::SetDiskGUID(GUIDData newGUID) {
2097 mainHeader.diskGUID = newGUID;
2098 secondHeader.diskGUID = newGUID;
2099} // SetDiskGUID()
2100
2101// Set the unique GUID of the specified partition. Returns 1 on
2102// successful completion, 0 if there were problems (invalid
2103// partition number).
2104int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2105 int retval = 0;
2106
2107 if (pn < mainHeader.numParts) {
2108 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
2109 partitions[pn].SetUniqueGUID(theGUID);
2110 retval = 1;
2111 } // if
2112 } // if
2113 return retval;
2114} // GPTData::SetPartitionGUID()
2115
srs5694ba00fed2010-01-12 18:18:36 -05002116// Change partition type code non-interactively. Returns 1 if
2117// successful, 0 if not....
2118int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
2119 int retval = 1;
2120
2121 if (!IsFreePartNum(partNum)) {
2122 partitions[partNum].SetType(hexCode);
2123 } else retval = 0;
2124 return retval;
2125} // GPTData::ChangePartType()
2126
srs56941d1448a2009-12-31 21:20:19 -05002127// Adjust sector number so that it falls on a sector boundary that's a
2128// multiple of sectorAlignment. This is done to improve the performance
2129// of Western Digital Advanced Format disks and disks with similar
2130// technology from other companies, which use 4096-byte sectors
2131// internally although they translate to 512-byte sectors for the
2132// benefit of the OS. If partitions aren't properly aligned on these
2133// disks, some filesystem data structures can span multiple physical
2134// sectors, degrading performance. This function should be called
2135// only on the FIRST sector of the partition, not the last!
2136// This function returns 1 if the alignment was altered, 0 if it
2137// was unchanged.
2138int GPTData::Align(uint64_t* sector) {
2139 int retval = 0, sectorOK = 0;
2140 uint64_t earlier, later, testSector, original;
2141
2142 if ((*sector % sectorAlignment) != 0) {
2143 original = *sector;
2144 retval = 1;
2145 earlier = (*sector / sectorAlignment) * sectorAlignment;
2146 later = earlier + (uint64_t) sectorAlignment;
2147
2148 // Check to see that every sector between the earlier one and the
2149 // requested one is clear, and that it's not too early....
2150 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05002151 sectorOK = 1;
2152 testSector = earlier;
2153 do {
2154 sectorOK = IsFree(testSector++);
2155 } while ((sectorOK == 1) && (testSector < *sector));
2156 if (sectorOK == 1) {
2157 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05002158 } // if
2159 } // if firstUsableLBA check
2160
2161 // If couldn't move the sector earlier, try to move it later instead....
2162 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2163 sectorOK = 1;
2164 testSector = later;
2165 do {
2166 sectorOK = IsFree(testSector--);
2167 } while ((sectorOK == 1) && (testSector > *sector));
2168 if (sectorOK == 1) {
2169 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05002170 } // if
2171 } // if
2172
2173 // If sector was changed successfully, inform the user of this fact.
2174 // Otherwise, notify the user that it couldn't be done....
2175 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05002176 cout << "Information: Moved requested sector from " << original << " to "
2177 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05002178 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05002179 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05002180 } else {
srs5694fed16d02010-01-27 23:03:40 -05002181 cout << "Information: Sector not aligned on " << sectorAlignment
2182 << "-sector boundary and could not be moved.\n"
2183 << "If you're using a Western Digital Advanced Format or similar disk with\n"
2184 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05002185 retval = 0;
2186 } // if/else
2187 } // if
2188 return retval;
2189} // GPTData::Align()
2190
srs5694e4ac11e2009-08-31 10:13:04 -04002191/********************************************************
2192 * *
2193 * Functions that return data about GPT data structures *
2194 * (most of these are inline in gpt.h) *
2195 * *
2196 ********************************************************/
2197
2198// Find the low and high used partition numbers (numbered from 0).
2199// Return value is the number of partitions found. Note that the
2200// *low and *high values are both set to 0 when no partitions
2201// are found, as well as when a single partition in the first
2202// position exists. Thus, the return value is the only way to
2203// tell when no partitions exist.
2204int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2205 uint32_t i;
2206 int numFound = 0;
2207
2208 *low = mainHeader.numParts + 1; // code for "not found"
2209 *high = 0;
2210 if (mainHeader.numParts > 0) { // only try if partition table exists...
2211 for (i = 0; i < mainHeader.numParts; i++) {
2212 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
2213 *high = i; // since we're counting up, set the high value
2214 // Set the low value only if it's not yet found...
2215 if (*low == (mainHeader.numParts + 1)) *low = i;
2216 numFound++;
2217 } // if
2218 } // for
2219 } // if
2220
2221 // Above will leave *low pointing to its "not found" value if no partitions
2222 // are defined, so reset to 0 if this is the case....
2223 if (*low == (mainHeader.numParts + 1))
2224 *low = 0;
2225 return numFound;
2226} // GPTData::GetPartRange()
2227
srs5694978041c2009-09-21 20:51:47 -04002228// Returns the number of defined partitions.
2229uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002230 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002231
2232 for (i = 0; i < mainHeader.numParts; i++) {
2233 if (partitions[i].GetFirstLBA() > 0)
2234 counted++;
2235 } // for
2236 return counted;
2237} // GPTData::CountParts()
2238
srs5694e4ac11e2009-08-31 10:13:04 -04002239/****************************************************
2240 * *
2241 * Functions that return data about disk free space *
2242 * *
2243 ****************************************************/
2244
2245// Find the first available block after the starting point; returns 0 if
2246// there are no available blocks left
2247uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2248 uint64_t first;
2249 uint32_t i;
2250 int firstMoved = 0;
2251
2252 // Begin from the specified starting point or from the first usable
2253 // LBA, whichever is greater...
2254 if (start < mainHeader.firstUsableLBA)
2255 first = mainHeader.firstUsableLBA;
2256 else
2257 first = start;
2258
2259 // ...now search through all partitions; if first is within an
2260 // existing partition, move it to the next sector after that
2261 // partition and repeat. If first was moved, set firstMoved
2262 // flag; repeat until firstMoved is not set, so as to catch
2263 // cases where partitions are out of sequential order....
2264 do {
2265 firstMoved = 0;
2266 for (i = 0; i < mainHeader.numParts; i++) {
2267 if ((first >= partitions[i].GetFirstLBA()) &&
2268 (first <= partitions[i].GetLastLBA())) { // in existing part.
2269 first = partitions[i].GetLastLBA() + 1;
2270 firstMoved = 1;
2271 } // if
2272 } // for
2273 } while (firstMoved == 1);
2274 if (first > mainHeader.lastUsableLBA)
2275 first = 0;
2276 return (first);
2277} // GPTData::FindFirstAvailable()
2278
2279// Finds the first available sector in the largest block of unallocated
2280// space on the disk. Returns 0 if there are no available blocks left
2281uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002282 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002283
2284 start = 0;
2285 do {
2286 firstBlock = FindFirstAvailable(start);
2287 if (firstBlock != UINT32_C(0)) { // something's free...
2288 lastBlock = FindLastInFree(firstBlock);
2289 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2290 if (segmentSize > selectedSize) {
2291 selectedSize = segmentSize;
2292 selectedSegment = firstBlock;
2293 } // if
2294 start = lastBlock + 1;
2295 } // if
2296 } while (firstBlock != 0);
2297 return selectedSegment;
2298} // GPTData::FindFirstInLargest()
2299
2300// Find the last available block on the disk at or after the start
2301// block. Returns 0 if there are no available partitions after
2302// (or including) start.
2303uint64_t GPTData::FindLastAvailable(uint64_t start) {
2304 uint64_t last;
2305 uint32_t i;
2306 int lastMoved = 0;
2307
2308 // Start by assuming the last usable LBA is available....
2309 last = mainHeader.lastUsableLBA;
2310
2311 // ...now, similar to algorithm in FindFirstAvailable(), search
2312 // through all partitions, moving last when it's in an existing
2313 // partition. Set the lastMoved flag so we repeat to catch cases
2314 // where partitions are out of logical order.
2315 do {
2316 lastMoved = 0;
2317 for (i = 0; i < mainHeader.numParts; i++) {
2318 if ((last >= partitions[i].GetFirstLBA()) &&
2319 (last <= partitions[i].GetLastLBA())) { // in existing part.
2320 last = partitions[i].GetFirstLBA() - 1;
2321 lastMoved = 1;
2322 } // if
2323 } // for
2324 } while (lastMoved == 1);
2325 if (last < mainHeader.firstUsableLBA)
2326 last = 0;
2327 return (last);
2328} // GPTData::FindLastAvailable()
2329
2330// Find the last available block in the free space pointed to by start.
2331uint64_t GPTData::FindLastInFree(uint64_t start) {
2332 uint64_t nearestStart;
2333 uint32_t i;
2334
2335 nearestStart = mainHeader.lastUsableLBA;
2336 for (i = 0; i < mainHeader.numParts; i++) {
2337 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2338 (partitions[i].GetFirstLBA() > start)) {
2339 nearestStart = partitions[i].GetFirstLBA() - 1;
2340 } // if
2341 } // for
2342 return (nearestStart);
2343} // GPTData::FindLastInFree()
2344
2345// Finds the total number of free blocks, the number of segments in which
2346// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002347uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002348 uint64_t start = UINT64_C(0); // starting point for each search
2349 uint64_t totalFound = UINT64_C(0); // running total
2350 uint64_t firstBlock; // first block in a segment
2351 uint64_t lastBlock; // last block in a segment
2352 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002353 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002354
2355 *largestSegment = UINT64_C(0);
2356 do {
2357 firstBlock = FindFirstAvailable(start);
2358 if (firstBlock != UINT64_C(0)) { // something's free...
2359 lastBlock = FindLastInFree(firstBlock);
2360 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2361 if (segmentSize > *largestSegment) {
2362 *largestSegment = segmentSize;
2363 } // if
2364 totalFound += segmentSize;
2365 num++;
2366 start = lastBlock + 1;
2367 } // if
2368 } while (firstBlock != 0);
2369 *numSegments = num;
2370 return totalFound;
2371} // GPTData::FindFreeBlocks()
2372
2373// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2374int GPTData::IsFree(uint64_t sector) {
2375 int isFree = 1;
2376 uint32_t i;
2377
2378 for (i = 0; i < mainHeader.numParts; i++) {
2379 if ((sector >= partitions[i].GetFirstLBA()) &&
2380 (sector <= partitions[i].GetLastLBA())) {
2381 isFree = 0;
2382 } // if
2383 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002384 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002385 (sector > mainHeader.lastUsableLBA)) {
2386 isFree = 0;
2387 } // if
2388 return (isFree);
2389} // GPTData::IsFree()
2390
srs5694ba00fed2010-01-12 18:18:36 -05002391// Returns 1 if partNum is unused.
2392int GPTData::IsFreePartNum(uint32_t partNum) {
2393 int retval = 1;
2394
2395 if ((partNum >= 0) && (partNum < mainHeader.numParts)) {
2396 if ((partitions[partNum].GetFirstLBA() != UINT64_C(0)) ||
2397 (partitions[partNum].GetLastLBA() != UINT64_C(0))) {
2398 retval = 0;
2399 } // if partition is in use
2400 } else retval = 0;
2401
2402 return retval;
2403} // GPTData::IsFreePartNum()
2404
srs5694e4ac11e2009-08-31 10:13:04 -04002405/********************************
2406 * *
2407 * Endianness support functions *
2408 * *
2409 ********************************/
2410
srs56942a9f5da2009-08-26 00:48:01 -04002411void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002412 ReverseBytes(&header->signature, 8);
2413 ReverseBytes(&header->revision, 4);
2414 ReverseBytes(&header->headerSize, 4);
2415 ReverseBytes(&header->headerCRC, 4);
2416 ReverseBytes(&header->reserved, 4);
2417 ReverseBytes(&header->currentLBA, 8);
2418 ReverseBytes(&header->backupLBA, 8);
2419 ReverseBytes(&header->firstUsableLBA, 8);
2420 ReverseBytes(&header->lastUsableLBA, 8);
2421 ReverseBytes(&header->partitionEntriesLBA, 8);
2422 ReverseBytes(&header->numParts, 4);
2423 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2424 ReverseBytes(&header->partitionEntriesCRC, 4);
2425 ReverseBytes(&header->reserved2, GPT_RESERVED);
srs56946699b012010-02-04 00:55:30 -05002426// header->diskGUID.ReverseGUIDBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002427} // GPTData::ReverseHeaderBytes()
2428
2429// IMPORTANT NOTE: This function requires non-reversed mainHeader
2430// structure!
2431void GPTData::ReversePartitionBytes() {
2432 uint32_t i;
2433
2434 // Check GPT signature on big-endian systems; this will mismatch
2435 // if the function is called out of order. Unfortunately, it'll also
2436 // mismatch if there's data corruption.
2437 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002438 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2439 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002440 } // if signature mismatch....
2441 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002442 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002443 } // for
2444} // GPTData::ReversePartitionBytes()
2445
2446/******************************************
2447 * *
2448 * Additional non-class support functions *
2449 * *
2450 ******************************************/
2451
srs5694e7b4ff92009-08-18 13:16:10 -04002452// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2453// never fail these tests, but the struct types may fail depending on compile options.
2454// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2455// sizes.
2456int SizesOK(void) {
2457 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002458
2459 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002460 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002461 allOK = 0;
2462 } // if
2463 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002464 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002465 allOK = 0;
2466 } // if
2467 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002468 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002469 allOK = 0;
2470 } // if
2471 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002472 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002473 allOK = 0;
2474 } // if
2475 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002476 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002477 allOK = 0;
2478 } // if
srs5694978041c2009-09-21 20:51:47 -04002479 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002480 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002481 allOK = 0;
2482 } // if
2483 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002484 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002485 allOK = 0;
2486 } // if
srs5694221e0872009-08-29 15:00:31 -04002487 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002488 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002489 allOK = 0;
2490 } // if
srs56946699b012010-02-04 00:55:30 -05002491 if (sizeof(GUIDData) != 16) {
2492 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2493 allOK = 0;
2494 } // if
2495 if (sizeof(PartType) != 16) {
2496 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2497 allOK = 0;
2498 } // if
srs5694fed16d02010-01-27 23:03:40 -05002499 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002500 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002501 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2502 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002503 } // if
2504 return (allOK);
2505} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002506