blob: 7dcbc86ca54ddf618be3e3a6f56f71e3c436e150 [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>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
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"
srs569455d92612010-03-07 22:16:07 -050029#include "partnotes.h"
srs5694e7b4ff92009-08-18 13:16:10 -040030
31using namespace std;
32
srs56948f1b2d62010-05-23 13:07:19 -040033#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040034#define log2(x) (log(x) / M_LN2)
35#endif // __FreeBSD__
36
srs56948f1b2d62010-05-23 13:07:19 -040037#ifdef _MSC_VER
38#define log2(x) (log((double) x) / log(2.0))
39#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040040
srs5694e7b4ff92009-08-18 13:16:10 -040041/****************************************
42 * *
43 * GPTData class and related structures *
44 * *
45 ****************************************/
46
srs5694e4ac11e2009-08-31 10:13:04 -040047// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040048GPTData::GPTData(void) {
49 blockSize = SECTOR_SIZE; // set a default
50 diskSize = 0;
51 partitions = NULL;
52 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050053 device = "";
srs56945d58fe02010-01-03 20:57:08 -050054 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040055 mainCrcOk = 0;
56 secondCrcOk = 0;
57 mainPartsCrcOk = 0;
58 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040059 apmFound = 0;
60 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050061 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050062 beQuiet = 0;
63 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040064 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050065 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040066 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040067 SetGPTSize(NUM_GPT_ENTRIES);
68} // GPTData default constructor
69
70// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050071GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040072 blockSize = SECTOR_SIZE; // set a default
73 diskSize = 0;
74 partitions = NULL;
75 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050076 device = "";
srs56945d58fe02010-01-03 20:57:08 -050077 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040078 mainCrcOk = 0;
79 secondCrcOk = 0;
80 mainPartsCrcOk = 0;
81 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040082 apmFound = 0;
83 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050084 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050085 beQuiet = 0;
86 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040087 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050088 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040089 numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050090 if (!LoadPartitions(filename))
91 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050092} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040093
srs5694e4ac11e2009-08-31 10:13:04 -040094// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040095GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050096 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040097} // GPTData destructor
98
srs5694e4ac11e2009-08-31 10:13:04 -040099/*********************************************************************
100 * *
101 * Begin functions that verify data, or that adjust the verification *
102 * information (compute CRCs, rebuild headers) *
103 * *
104 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400105
srs5694e4ac11e2009-08-31 10:13:04 -0400106// Perform detailed verification, reporting on any problems found, but
107// do *NOT* recover from these problems. Returns the total number of
108// problems identified.
109int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -0500110 int problems = 0;
111 uint32_t i, numSegments;
112 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400113
114 // First, check for CRC errors in the GPT data....
115 if (!mainCrcOk) {
116 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500117 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
118 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
119 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
120 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400121 } // if
122 if (!mainPartsCrcOk) {
123 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500124 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
125 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
126 << "transformation menu). This report may be a false alarm if you've already\n"
127 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400128 } // if
129 if (!secondCrcOk) {
130 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500131 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
132 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
133 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
134 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400135 } // if
136 if (!secondPartsCrcOk) {
137 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500138 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
139 << "be corrupt. This program will automatically create a new backup partition\n"
140 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400141 } // if
142
srs5694978041c2009-09-21 20:51:47 -0400143 // Now check that the main and backup headers both point to themselves....
144 if (mainHeader.currentLBA != 1) {
145 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500146 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
147 << "is being automatically corrected, but it may be a symptom of more serious\n"
148 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400149 mainHeader.currentLBA = 1;
150 } // if
151 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
152 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500153 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
154 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
155 << "option on the experts' menu to adjust the secondary header's and partition\n"
156 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400157 } // if
158
159 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400160 if (mainHeader.currentLBA != secondHeader.backupLBA) {
161 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500162 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
163 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
164 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400165 } // if
166 if (mainHeader.backupLBA != secondHeader.currentLBA) {
167 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500168 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
169 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
170 << secondHeader.currentLBA << ").\n"
171 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400172 } // if
173 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
174 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500175 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
176 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
177 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400178 } // if
179 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
180 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500181 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
182 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
183 << secondHeader.lastUsableLBA << ")\n"
184 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400185 } // if
srs56946699b012010-02-04 00:55:30 -0500186 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400187 problems++;
srs56946699b012010-02-04 00:55:30 -0500188 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500189 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500190 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500191 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
192 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400193 } // if
194 if (mainHeader.numParts != secondHeader.numParts) {
195 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500196 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
197 << ") doesn't\nmatch the backup GPT header's number of partitions ("
198 << secondHeader.numParts << ")\n"
199 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400200 } // if
201 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
202 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500203 cout << "\nProblem: main GPT header's size of partition entries ("
204 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
205 << "match the backup GPT header's size of partition entries ("
206 << secondHeader.sizeOfPartitionEntries << ")\n"
207 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
208 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400209 } // if
210
211 // Now check for a few other miscellaneous problems...
212 // Check that the disk size will hold the data...
213 if (mainHeader.backupLBA > diskSize) {
214 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500215 cout << "\nProblem: Disk is too small to hold all the data!\n"
216 << "(Disk size is " << diskSize << " sectors, needs to be "
217 << mainHeader.backupLBA << " sectors.)\n"
218 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400219 } // if
220
221 // Check for overlapping partitions....
222 problems += FindOverlaps();
223
srs569455d92612010-03-07 22:16:07 -0500224 // Check for insane partitions (start after end, hugely big, etc.)
225 problems += FindInsanePartitions();
226
srs5694e4ac11e2009-08-31 10:13:04 -0400227 // Check for mismatched MBR and GPT partitions...
228 problems += FindHybridMismatches();
229
230 // Verify that partitions don't run into GPT data areas....
231 problems += CheckGPTSize();
232
srs56941d1448a2009-12-31 21:20:19 -0500233 // Check that partitions are aligned on proper boundaries (for WD Advanced
234 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400235 for (i = 0; i < numParts; i++) {
srs56941d1448a2009-12-31 21:20:19 -0500236 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500237 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
238 << sectorAlignment << "-sector boundary. This may\nresult "
239 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500240 } // if
241 } // for
242
srs5694e4ac11e2009-08-31 10:13:04 -0400243 // Now compute available space, but only if no problems found, since
244 // problems could affect the results
245 if (problems == 0) {
246 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500247 cout << "No problems found. " << totalFree << " free sectors ("
248 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
249 << numSegments << "\nsegments, the largest of which is "
250 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
srs56940283dae2010-04-28 16:44:34 -0400251 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400252 } else {
srs56940a697312010-01-28 21:10:52 -0500253 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400254 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400255
256 return (problems);
257} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400258
259// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400260// do, issues a warning but takes no action. Returns number of problems
261// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400262int GPTData::CheckGPTSize(void) {
263 uint64_t overlap, firstUsedBlock, lastUsedBlock;
264 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400265 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400266
267 // first, locate the first & last used blocks
268 firstUsedBlock = UINT64_MAX;
269 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400270 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400271 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400272 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400273 firstUsedBlock = partitions[i].GetFirstLBA();
274 if (partitions[i].GetLastLBA() > lastUsedBlock)
275 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400276 } // for
277
278 // If the disk size is 0 (the default), then it means that various
279 // variables aren't yet set, so the below tests will be useless;
280 // therefore we should skip everything
281 if (diskSize != 0) {
282 if (mainHeader.firstUsableLBA > firstUsedBlock) {
283 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500284 cout << "Warning! Main partition table overlaps the first partition by "
285 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400286 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500287 cout << "Try reducing the partition table size by " << overlap * 4
288 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400289 } else {
srs5694fed16d02010-01-27 23:03:40 -0500290 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400291 } // if/else
292 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400293 } // Problem at start of disk
294 if (mainHeader.lastUsableLBA < lastUsedBlock) {
295 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500296 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500297 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400298 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500299 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400300 } else {
srs5694fed16d02010-01-27 23:03:40 -0500301 cout << "Try reducing the partition table size by " << overlap * 4
302 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400303 } // if/else
304 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400305 } // Problem at end of disk
306 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400307 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400308} // GPTData::CheckGPTSize()
309
srs5694e7b4ff92009-08-18 13:16:10 -0400310// Check the validity of the GPT header. Returns 1 if the main header
311// is valid, 2 if the backup header is valid, 3 if both are valid, and
312// 0 if neither is valid. Note that this function just checks the GPT
313// signature and revision numbers, not CRCs or other data.
314int GPTData::CheckHeaderValidity(void) {
315 int valid = 3;
316
srs5694fed16d02010-01-27 23:03:40 -0500317 cout.setf(ios::uppercase);
318 cout.fill('0');
319
320 // Note: failed GPT signature checks produce no error message because
321 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400322 if (mainHeader.signature != GPT_SIGNATURE) {
323 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } else if ((mainHeader.revision != 0x00010000) && valid) {
325 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500326 cout << "Unsupported GPT version in main header; read 0x";
327 cout.width(8);
328 cout << hex << mainHeader.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
333 if (secondHeader.signature != GPT_SIGNATURE) {
334 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400335 } else if ((secondHeader.revision != 0x00010000) && valid) {
336 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500337 cout << "Unsupported GPT version in backup header; read 0x";
338 cout.width(8);
339 cout << hex << secondHeader.revision << ", should be\n0x";
340 cout.width(8);
341 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400342 } // if/else/if
343
srs56942a9f5da2009-08-26 00:48:01 -0400344 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400345 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400346 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400347 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400348 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500349 } // if
srs5694fed16d02010-01-27 23:03:40 -0500350 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400351
srs5694fed16d02010-01-27 23:03:40 -0500352 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400353} // GPTData::CheckHeaderValidity()
354
355// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500356// Note: Must be called with header in LITTLE-ENDIAN
357// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400358int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400359 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400360
srs56942a9f5da2009-08-26 00:48:01 -0400361 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400362 // computation to be valid
363 oldCRC = header->headerCRC;
364 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400365 hSize = header->headerSize;
366
367 // If big-endian system, reverse byte order
368 if (IsLittleEndian() == 0) {
369 ReverseBytes(&oldCRC, 4);
370 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400371
372 // Initialize CRC functions...
373 chksum_crc32gentab();
374
375 // Compute CRC, restore original, and return result of comparison
376 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400377 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400378 return (oldCRC == newCRC);
379} // GPTData::CheckHeaderCRC()
380
srs56946699b012010-02-04 00:55:30 -0500381// Recompute all the CRCs. Must be called before saving if any changes have
382// been made. Must be called on platform-ordered data (this function reverses
383// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400384void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400385 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400386 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400387
388 // Initialize CRC functions...
389 chksum_crc32gentab();
390
srs56946699b012010-02-04 00:55:30 -0500391 // Save some key data from header before reversing byte order....
srs5694978041c2009-09-21 20:51:47 -0400392 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500393
394 if ((littleEndian = IsLittleEndian()) == 0) {
395 ReversePartitionBytes();
396 ReverseHeaderBytes(&mainHeader);
397 ReverseHeaderBytes(&secondHeader);
398 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400399
srs5694e7b4ff92009-08-18 13:16:10 -0400400 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400401 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400402 mainHeader.partitionEntriesCRC = crc;
403 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400404 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400405 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
406 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400407 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400408
409 // Zero out GPT tables' own CRCs (required for correct computation)
410 mainHeader.headerCRC = 0;
411 secondHeader.headerCRC = 0;
412
413 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400414 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400415 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400416 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400417 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400418 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400419 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400420 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400421 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500422
423 if ((littleEndian = IsLittleEndian()) == 0) {
424 ReverseHeaderBytes(&mainHeader);
425 ReverseHeaderBytes(&secondHeader);
426 ReversePartitionBytes();
427 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400428} // GPTData::RecomputeCRCs()
429
srs5694e7b4ff92009-08-18 13:16:10 -0400430// Rebuild the main GPT header, using the secondary header as a model.
431// Typically called when the main header has been found to be corrupt.
432void GPTData::RebuildMainHeader(void) {
433 int i;
434
435 mainHeader.signature = GPT_SIGNATURE;
436 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400437 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400438 mainHeader.headerCRC = UINT32_C(0);
439 mainHeader.reserved = secondHeader.reserved;
440 mainHeader.currentLBA = secondHeader.backupLBA;
441 mainHeader.backupLBA = secondHeader.currentLBA;
442 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
443 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500444 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400445 mainHeader.partitionEntriesLBA = UINT64_C(2);
446 mainHeader.numParts = secondHeader.numParts;
447 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
448 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
449 for (i = 0 ; i < GPT_RESERVED; i++)
450 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500451 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400452 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400453} // GPTData::RebuildMainHeader()
454
455// Rebuild the secondary GPT header, using the main header as a model.
456void GPTData::RebuildSecondHeader(void) {
457 int i;
458
459 secondHeader.signature = GPT_SIGNATURE;
460 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400461 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400462 secondHeader.headerCRC = UINT32_C(0);
463 secondHeader.reserved = mainHeader.reserved;
464 secondHeader.currentLBA = mainHeader.backupLBA;
465 secondHeader.backupLBA = mainHeader.currentLBA;
466 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
467 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500468 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400469 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
470 secondHeader.numParts = mainHeader.numParts;
471 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
472 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
473 for (i = 0 ; i < GPT_RESERVED; i++)
474 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500475 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400476 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400477} // GPTData::RebuildSecondHeader()
478
479// Search for hybrid MBR entries that have no corresponding GPT partition.
480// Returns number of such mismatches found
481int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500482 int i, found, numFound = 0;
483 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400484 uint64_t mbrFirst, mbrLast;
485
486 for (i = 0; i < 4; i++) {
487 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
488 j = 0;
489 found = 0;
490 do {
491 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
492 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
493 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
494 (partitions[j].GetLastLBA() == mbrLast))
495 found = 1;
496 j++;
srs56940283dae2010-04-28 16:44:34 -0400497 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400498 if (!found) {
499 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500500 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
501 << i + 1 << ", of type 0x";
502 cout.fill('0');
503 cout.setf(ios::uppercase);
504 cout.width(2);
505 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
506 << "has no corresponding GPT partition! You may continue, but this condition\n"
507 << "might cause data loss in the future!\a\n" << dec;
508 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400509 } // if
510 } // if
511 } // for
512 return numFound;
513} // GPTData::FindHybridMismatches
514
515// Find overlapping partitions and warn user about them. Returns number of
516// overlapping partitions.
517int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500518 int problems = 0;
519 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400520
srs56940283dae2010-04-28 16:44:34 -0400521 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400522 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500523 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400524 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500525 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
526 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
527 << " to " << partitions[i].GetLastLBA() << "\n";
528 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
529 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400530 } // if
531 } // for j...
532 } // for i...
533 return problems;
534} // GPTData::FindOverlaps()
535
srs569455d92612010-03-07 22:16:07 -0500536// Find partitions that are insane -- they start after they end or are too
537// big for the disk. (The latter should duplicate detection of overlaps
538// with GPT backup data structures, but better to err on the side of
539// redundant tests than to miss something....)
540int GPTData::FindInsanePartitions(void) {
541 uint32_t i;
542 int problems = 0;
543
srs56940283dae2010-04-28 16:44:34 -0400544 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500545 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
546 problems++;
srs56940283dae2010-04-28 16:44:34 -0400547 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500548 } // if
549 if (partitions[i].GetLastLBA() >= diskSize) {
550 problems++;
srs56940283dae2010-04-28 16:44:34 -0400551 cout << "\nProblem: partition " << i + 1<< " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500552 } // if
553 } // for
554 return problems;
555} // GPTData::FindInsanePartitions(void)
556
557
srs5694e4ac11e2009-08-31 10:13:04 -0400558/******************************************************************
559 * *
560 * Begin functions that load data from disk or save data to disk. *
561 * *
562 ******************************************************************/
563
564// Scan for partition data. This function loads the MBR data (regular MBR or
565// protective MBR) and loads BSD disklabel data (which is probably invalid).
566// It also looks for APM data, forces a load of GPT data, and summarizes
567// the results.
srs5694546a9c72010-01-26 16:00:26 -0500568void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400569 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400570
571 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500572 protectiveMBR.ReadMBRData(&myDisk);
573 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400574
575 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500576 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500577
578 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500579 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500580 protectiveMBR.ShowState();
581 bsdDisklabel.ShowState();
582 ShowAPMState(); // Show whether there's an Apple Partition Map present
583 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500584 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500585 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400586
587 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500588 cout << "\n*******************************************************************\n"
589 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500590 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500591 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500592 } // if
srs5694fed16d02010-01-27 23:03:40 -0500593 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400594 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400595} // GPTData::PartitionScan()
596
597// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500598int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500599 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500600 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500601 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400602
srs5694546a9c72010-01-26 16:00:26 -0500603 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500604 err = myDisk.OpenForWrite(deviceFilename);
605 if ((err == 0) && (!justLooking)) {
606 cout << "\aNOTE: Write test failed with error number " << errno
607 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
608#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
609 cout << "You may be able to enable writes by exiting this program, typing\n"
610 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
611 << "program.\n";
612#endif
613 cout << "\n";
614 } // if
615 myDisk.Close(); // Close and re-open read-only in case of bugs
616 } else allOK = 0; // if
617
618 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400619 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500620 diskSize = myDisk.DiskSize(&err);
621 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500622 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500623 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400624
srs5694ba00fed2010-01-12 18:18:36 -0500625 whichWasUsed = UseWhichPartitions();
626 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400627 case use_mbr:
628 XFormPartitions();
629 break;
630 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500631 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400632// bsdDisklabel.DisplayBSDData();
633 ClearGPTData();
634 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500635 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400636 break;
637 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500638 mbrState = protectiveMBR.GetValidity();
639 if ((mbrState == invalid) || (mbrState == mbr))
640 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400641 break;
642 case use_new:
643 ClearGPTData();
644 protectiveMBR.MakeProtectiveMBR();
645 break;
srs56943c0af382010-01-15 19:19:18 -0500646 case use_abort:
647 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400648 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500649 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400650 } // switch
651
srs569455d92612010-03-07 22:16:07 -0500652 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500653 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500654 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400655 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400656 } else {
657 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400658 } // if/else
659 return (allOK);
660} // GPTData::LoadPartitions()
661
662// Loads the GPT, as much as possible. Returns 1 if this seems to have
663// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500664int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500665 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400666
srs5694cb76c672010-02-11 22:22:22 -0500667 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400668
srs5694cb76c672010-02-11 22:22:22 -0500669 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
670 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
671 } else {
srs569408bb0da2010-02-19 17:19:55 -0500672 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
673 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500674 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
675 << "secondary header from the last sector of the disk! You should use 'v' to\n"
676 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
677 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500678 } // if/else
679 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400680 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400681
682 // Return valid headers code: 0 = both headers bad; 1 = main header
683 // good, backup bad; 2 = backup header good, main header bad;
684 // 3 = both headers good. Note these codes refer to valid GPT
685 // signatures and version numbers; more subtle problems will elude
686 // this check!
687 validHeaders = CheckHeaderValidity();
688
689 // Read partitions (from primary array)
690 if (validHeaders > 0) { // if at least one header is OK....
691 // GPT appears to be valid....
692 state = gpt_valid;
693
694 // We're calling the GPT valid, but there's a possibility that one
695 // of the two headers is corrupt. If so, use the one that seems to
696 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500697 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500698 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
699 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400700 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500701 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400702 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500703 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500704 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
705 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500706 RebuildMainHeader();
707 state = gpt_corrupt;
708 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400709 } // if/else/if
710
srs5694546a9c72010-01-26 16:00:26 -0500711 // Figure out which partition table to load....
712 // Load the main partition table, since either its header's CRC is OK or the
713 // backup header's CRC is not OK....
714 if (mainCrcOk || !secondCrcOk) {
715 if (LoadMainTable() == 0)
716 allOK = 0;
717 } else { // bad main header CRC and backup header CRC is OK
718 state = gpt_corrupt;
719 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500720 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500721 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500722 } else { // backup table bad, bad main header CRC, but try main table in desperation....
723 if (LoadMainTable() == 0) {
724 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500725 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500726 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500727 } // if
728 } // if/else (LoadSecondTableAsMain())
729 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400730
srs5694cb76c672010-02-11 22:22:22 -0500731 if (loadedTable == 1)
732 secondPartsCrcOk = CheckTable(&secondHeader);
733 else if (loadedTable == 2)
734 mainPartsCrcOk = CheckTable(&mainHeader);
735 else
736 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400737
srs5694546a9c72010-01-26 16:00:26 -0500738 // Problem with main partition table; if backup is OK, use it instead....
739 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
740 state = gpt_corrupt;
741 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500742 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500743 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
744 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500745 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500746
srs5694e4ac11e2009-08-31 10:13:04 -0400747 // Check for valid CRCs and warn if there are problems
748 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
749 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500750 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400751 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500752 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400753 } else {
754 state = gpt_invalid;
755 } // if/else
756 return allOK;
757} // GPTData::ForceLoadGPTData()
758
srs5694247657a2009-11-26 18:36:12 -0500759// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400760// main GPT header in memory MUST be valid for this call to do anything
761// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500762// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400763int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500764 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400765} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400766
767// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500768// table. Used in repair functions, and when starting up if the main
769// partition table is damaged.
770// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
771int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500772 return LoadPartitionTable(secondHeader, myDisk);
773} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400774
srs5694cb76c672010-02-11 22:22:22 -0500775// Load a single GPT header (main or backup) from the specified disk device and
776// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
777// value appropriately.
778// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
779// failure.
780int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
781 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500782 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500783
784 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500785 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500786 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
787 allOK = 0;
788 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500789 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500790
srs56941c6f8b02010-02-21 11:09:20 -0500791 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500792 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500793 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500794 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500795
srs56940283dae2010-04-28 16:44:34 -0400796 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500797 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500798 }
srs56941c6f8b02010-02-21 11:09:20 -0500799
800 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500801 return allOK;
802} // GPTData::LoadHeader
803
804// Load a partition table (either main or secondary) from the specified disk,
805// using header as a reference for what to load. If sector != 0 (the default
806// is 0), loads from the specified sector; otherwise loads from the sector
807// indicated in header.
808// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
809int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
810 uint32_t sizeOfParts, newCRC;
811 int retval;
812
813 if (disk.OpenForRead()) {
814 if (sector == 0) {
815 retval = disk.Seek(header.partitionEntriesLBA);
816 } else {
817 retval = disk.Seek(sector);
818 } // if/else
srs569455d92612010-03-07 22:16:07 -0500819 if (retval == 1)
820 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500821 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500822 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
823 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500824 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500825 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500826 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400827 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500828 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400829 if (IsLittleEndian() == 0)
830 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500831 if (!mainPartsCrcOk) {
832 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400833 } // if
834 } else {
srs5694cb76c672010-02-11 22:22:22 -0500835 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400836 } // if/else
837 } else {
srs5694fed16d02010-01-27 23:03:40 -0500838 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500839 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500840 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400841 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500842 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500843} // GPTData::LoadPartitionsTable()
844
845// Check the partition table pointed to by header, but don't keep it
846// around.
847// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
848int GPTData::CheckTable(struct GPTHeader *header) {
849 uint32_t sizeOfParts, newCRC;
850 uint8_t *storage;
851 int newCrcOk = 0;
852
srs56940283dae2010-04-28 16:44:34 -0400853 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500854 // its CRC and store the results, then discard this temporary
855 // storage, since we don't use it in any but recovery operations
856 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400857 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500858 storage = new uint8_t[sizeOfParts];
859 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400860 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500861 } else {
862 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
863 newCrcOk = (newCRC == header->partitionEntriesCRC);
864 } // if/else
865 delete[] storage;
866 } // if
867 return newCrcOk;
868} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400869
srs5694e7b4ff92009-08-18 13:16:10 -0400870// Writes GPT (and protective MBR) to disk. Returns 1 on successful
871// write, 0 if there was a problem.
srs5694f9312b02010-07-06 15:39:51 -0400872int GPTData::SaveGPTData(int quiet, string filename) {
srs56946699b012010-02-04 00:55:30 -0500873 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500874 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400875
srs5694f9312b02010-07-06 15:39:51 -0400876 if (filename == "")
877 filename = device;
878
srs56946699b012010-02-04 00:55:30 -0500879 littleEndian = IsLittleEndian();
880
srs5694f9312b02010-07-06 15:39:51 -0400881 if (filename == "") {
srs5694fed16d02010-01-27 23:03:40 -0500882 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400883 } // if
884
885 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500886
887 // This test should only fail on read-only disks....
888 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500889 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500890 allOK = 0;
891 } // if
892
srs5694e7b4ff92009-08-18 13:16:10 -0400893 // Is there enough space to hold the GPT headers and partition tables,
894 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400895 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400896 allOK = 0;
897 } // if
898
899 // Check that disk is really big enough to handle this...
900 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500901 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
902 << "problem (or it might not). Aborting!\n(Disk size is "
903 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400904 allOK = 0;
905 } // if
srs5694247657a2009-11-26 18:36:12 -0500906 // Check that second header is properly placed. Warn and ask if this should
907 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500908 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500909 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
910 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500911 if (GetYN() == 'Y') {
912 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500913 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500914 } else {
srs5694fed16d02010-01-27 23:03:40 -0500915 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500916 } // if correction requested
917 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400918
srs569455d92612010-03-07 22:16:07 -0500919 // Check for overlapping or insane partitions....
920 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400921 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500922 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400923 } // if
924
925 // Check for mismatched MBR and GPT data, but let it pass if found
926 // (function displays warning message)
927 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400928
929 RecomputeCRCs();
930
srs5694ba00fed2010-01-12 18:18:36 -0500931 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500932 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
933 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500934 answer = GetYN();
935 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500936 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400937 } else {
938 allOK = 0;
939 } // if/else
940 } // if
941
942 // Do it!
943 if (allOK) {
srs5694f9312b02010-07-06 15:39:51 -0400944 if (myDisk.OpenForWrite(filename)) {
srs56948a4ddfc2010-03-21 19:05:49 -0400945 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -0500946 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
947 if (!allOK)
948 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
949 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400950
951 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -0400952 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
953
954 // Now write the main partition tables...
955 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
956
957 // Now write the main GPT header...
958 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
959
960 // To top it off, write the protective MBR...
961 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400962
963 // re-read the partition table
964 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500965 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400966 } // if
967
968 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500969 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400970 } else {
srs5694fed16d02010-01-27 23:03:40 -0500971 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -0400972 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400973 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -0400974
srs5694546a9c72010-01-26 16:00:26 -0500975 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400976 } else {
srs5694f9312b02010-07-06 15:39:51 -0400977 cerr << "Unable to open device " << filename << " for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -0500978 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400979 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400980 } // if/else
981 } else {
srs5694fed16d02010-01-27 23:03:40 -0500982 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400983 } // if
984
985 return (allOK);
986} // GPTData::SaveGPTData()
987
988// Save GPT data to a backup file. This function does much less error
989// checking than SaveGPTData(). It can therefore preserve many types of
990// corruption for later analysis; however, it preserves only the MBR,
991// the main GPT header, the backup GPT header, and the main partition
992// table; it discards the backup partition table, since it should be
993// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500994int GPTData::SaveGPTBackup(const string & filename) {
995 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500996 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400997
srs5694546a9c72010-01-26 16:00:26 -0500998 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500999 // Recomputing the CRCs is likely to alter them, which could be bad
1000 // if the intent is to save a potentially bad GPT for later analysis;
1001 // but if we don't do this, we get bogus errors when we load the
1002 // backup. I'm favoring misses over false alarms....
1003 RecomputeCRCs();
1004
srs5694546a9c72010-01-26 16:00:26 -05001005 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001006
srs5694cb76c672010-02-11 22:22:22 -05001007 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001008 // MBR write closed disk, so re-open and seek to end....
1009 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001010 allOK = SaveHeader(&mainHeader, backupFile, 1);
1011 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001012
srs5694e7b4ff92009-08-18 13:16:10 -04001013 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001014 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001015
srs5694cb76c672010-02-11 22:22:22 -05001016 if (allOK)
1017 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001018
1019 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001020 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001021 } else {
srs5694fed16d02010-01-27 23:03:40 -05001022 cerr << "Warning! An error was reported when writing the backup file.\n"
1023 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001024 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001025 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001026 } else {
srs5694fed16d02010-01-27 23:03:40 -05001027 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001028 allOK = 0;
1029 } // if/else
1030 return allOK;
1031} // GPTData::SaveGPTBackup()
1032
srs5694cb76c672010-02-11 22:22:22 -05001033// Write a GPT header (main or backup) to the specified sector. Used by both
1034// the SaveGPTData() and SaveGPTBackup() functions.
1035// Should be passed an architecture-appropriate header (DO NOT call
1036// ReverseHeaderBytes() on the header before calling this function)
1037// Returns 1 on success, 0 on failure
1038int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1039 int littleEndian, allOK = 1;
1040
1041 littleEndian = IsLittleEndian();
1042 if (!littleEndian)
1043 ReverseHeaderBytes(header);
1044 if (disk.Seek(sector)) {
1045 if (disk.Write(header, 512) == -1)
1046 allOK = 0;
1047 } else allOK = 0; // if (disk.Seek()...)
1048 if (!littleEndian)
1049 ReverseHeaderBytes(header);
1050 return allOK;
1051} // GPTData::SaveHeader()
1052
1053// Save the partitions to the specified sector. Used by both the SaveGPTData()
1054// and SaveGPTBackup() functions.
1055// Should be passed an architecture-appropriate header (DO NOT call
1056// ReverseHeaderBytes() on the header before calling this function)
1057// Returns 1 on success, 0 on failure
1058int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1059 int littleEndian, allOK = 1;
1060
1061 littleEndian = IsLittleEndian();
1062 if (disk.Seek(sector)) {
1063 if (!littleEndian)
1064 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001065 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001066 allOK = 0;
1067 if (!littleEndian)
1068 ReversePartitionBytes();
1069 } else allOK = 0; // if (myDisk.Seek()...)
1070 return allOK;
1071} // GPTData::SavePartitionTable()
1072
srs5694e7b4ff92009-08-18 13:16:10 -04001073// Load GPT data from a backup file created by SaveGPTBackup(). This function
1074// does minimal error checking. It returns 1 if it completed successfully,
1075// 0 if there was a problem. In the latter case, it creates a new empty
1076// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001077int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001078 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001079 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001080 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001081 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001082
srs5694546a9c72010-01-26 16:00:26 -05001083 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001084 if (IsLittleEndian() == 0)
1085 littleEndian = 0;
1086
srs5694e7b4ff92009-08-18 13:16:10 -04001087 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001088 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001089
srs5694cb76c672010-02-11 22:22:22 -05001090 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001091
srs5694cb76c672010-02-11 22:22:22 -05001092 // Check backup file size and rebuild second header if file is right
1093 // size to be direct dd copy of MBR, main header, and main partition
1094 // table; if other size, treat it like a GPT fdisk-generated backup
1095 // file
1096 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1097 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1098 if (shortBackup) {
1099 RebuildSecondHeader();
1100 secondCrcOk = mainCrcOk;
1101 } else {
1102 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1103 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001104
srs5694e7b4ff92009-08-18 13:16:10 -04001105 // Return valid headers code: 0 = both headers bad; 1 = main header
1106 // good, backup bad; 2 = backup header good, main header bad;
1107 // 3 = both headers good. Note these codes refer to valid GPT
1108 // signatures and version numbers; more subtle problems will elude
1109 // this check!
1110 if ((val = CheckHeaderValidity()) > 0) {
1111 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001112 SetGPTSize(secondHeader.numParts);
1113// numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001114 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001115 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001116 SetGPTSize(mainHeader.numParts);
1117// numParts = mainHeader.numParts;
srs5694e7b4ff92009-08-18 13:16:10 -04001118 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1119 } // if/else
1120
srs56940283dae2010-04-28 16:44:34 -04001121// SetGPTSize(numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001122
srs5694e7b4ff92009-08-18 13:16:10 -04001123 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001124 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1125 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001126 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001127 } // if
1128
srs5694cb76c672010-02-11 22:22:22 -05001129 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1130 cerr << "Warning! Read error " << errno
1131 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001132 } else {
1133 allOK = 0;
1134 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001135 // Something went badly wrong, so blank out partitions
1136 if (allOK == 0) {
1137 cerr << "Improper backup file! Clearing all partition data!\n";
1138 ClearGPTData();
1139 protectiveMBR.MakeProtectiveMBR();
1140 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001141 } else {
1142 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001143 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001144 } // if/else
1145
srs5694e7b4ff92009-08-18 13:16:10 -04001146 return allOK;
1147} // GPTData::LoadGPTBackup()
1148
srs569408bb0da2010-02-19 17:19:55 -05001149int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001150 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001151} // GPTData::SaveMBR()
1152
1153// This function destroys the on-disk GPT structures, but NOT the on-disk
1154// MBR.
1155// Returns 1 if the operation succeeds, 0 if not.
1156int GPTData::DestroyGPT(void) {
1157 int i, sum, tableSize, allOK = 1;
1158 uint8_t blankSector[512];
1159 uint8_t* emptyTable;
1160
1161 for (i = 0; i < 512; i++) {
1162 blankSector[i] = 0;
1163 } // for
1164
1165 if (myDisk.OpenForWrite()) {
1166 if (!myDisk.Seek(mainHeader.currentLBA))
1167 allOK = 0;
1168 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1169 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1170 allOK = 0;
1171 } // if
1172 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1173 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001174 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001175 emptyTable = new uint8_t[tableSize];
1176 for (i = 0; i < tableSize; i++)
1177 emptyTable[i] = 0;
1178 if (allOK) {
1179 sum = myDisk.Write(emptyTable, tableSize);
1180 if (sum != tableSize) {
1181 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1182 allOK = 0;
1183 } // if write failed
1184 } // if
1185 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1186 allOK = 0;
1187 if (allOK) {
1188 sum = myDisk.Write(emptyTable, tableSize);
1189 if (sum != tableSize) {
1190 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1191 << errno << "\n";
1192 allOK = 0;
1193 } // if wrong size written
1194 } // if
1195 if (!myDisk.Seek(secondHeader.currentLBA))
1196 allOK = 0;
1197 if (allOK) {
1198 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1199 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1200 allOK = 0;
1201 } // if
1202 } // if
1203 myDisk.DiskSync();
1204 myDisk.Close();
1205 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1206 << "other utilities.\n";
1207 delete[] emptyTable;
1208 } else {
1209 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1210 } // if/else (fd != -1)
1211 return (allOK);
1212} // GPTDataTextUI::DestroyGPT()
1213
1214// Wipe MBR data from the disk (zero it out completely)
1215// Returns 1 on success, 0 on failure.
1216int GPTData::DestroyMBR(void) {
1217 int allOK = 1, i;
1218 uint8_t blankSector[512];
1219
1220 for (i = 0; i < 512; i++)
1221 blankSector[i] = 0;
1222
1223 if (myDisk.OpenForWrite()) {
1224 if (myDisk.Seek(0)) {
1225 if (myDisk.Write(blankSector, 512) != 512)
1226 allOK = 0;
1227 } else allOK = 0;
1228 } else allOK = 0;
1229 if (!allOK)
1230 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1231 return allOK;
1232} // GPTData::DestroyMBR(void)
1233
srs5694e4ac11e2009-08-31 10:13:04 -04001234// Tell user whether Apple Partition Map (APM) was discovered....
1235void GPTData::ShowAPMState(void) {
1236 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001237 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001238 else
srs5694fed16d02010-01-27 23:03:40 -05001239 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001240} // GPTData::ShowAPMState()
1241
1242// Tell user about the state of the GPT data....
1243void GPTData::ShowGPTState(void) {
1244 switch (state) {
1245 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001246 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001247 break;
1248 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001250 break;
1251 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001252 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001253 break;
1254 default:
srs5694fed16d02010-01-27 23:03:40 -05001255 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001256 break;
1257 } // switch
1258} // GPTData::ShowGPTState()
1259
1260// Display the basic GPT data
1261void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001262 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001263 uint64_t temp, totalFree;
1264
srs5694fed16d02010-01-27 23:03:40 -05001265 cout << "Disk " << device << ": " << diskSize << " sectors, "
1266 << BytesToSI(diskSize * blockSize) << "\n";
1267 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001268 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs56940283dae2010-04-28 16:44:34 -04001269 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001270 cout << "First usable sector is " << mainHeader.firstUsableLBA
1271 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001272 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001273 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001274 cout << "Total free space is " << totalFree << " sectors ("
1275 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1276 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001277 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001278 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001279 } // for
1280} // GPTData::DisplayGPTData()
1281
srs5694e4ac11e2009-08-31 10:13:04 -04001282// Show detailed information on the specified partition
1283void GPTData::ShowPartDetails(uint32_t partNum) {
1284 if (partitions[partNum].GetFirstLBA() != 0) {
1285 partitions[partNum].ShowDetails(blockSize);
1286 } else {
srs5694fed16d02010-01-27 23:03:40 -05001287 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001288 } // if
1289} // GPTData::ShowPartDetails()
1290
srs5694e4ac11e2009-08-31 10:13:04 -04001291/**************************************************************************
1292 * *
1293 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1294 * (some of these functions may require user interaction) *
1295 * *
1296 **************************************************************************/
1297
srs569408bb0da2010-02-19 17:19:55 -05001298// Examines the MBR & GPT data to determine which set of data to use: the
1299// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1300// a new set of partitions (use_new). A return value of use_abort indicates
1301// that this function couldn't determine what to do. Overriding functions
1302// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001303WhichToUse GPTData::UseWhichPartitions(void) {
1304 WhichToUse which = use_new;
1305 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001306
1307 mbrState = protectiveMBR.GetValidity();
1308
1309 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001310 cout << "\n***************************************************************\n"
1311 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001312 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001313 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001314 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001315 } // if
srs5694fed16d02010-01-27 23:03:40 -05001316 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001317 which = use_mbr;
1318 } // if
1319
1320 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001321 cout << "\n**********************************************************************\n"
1322 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1323 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001324 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001325 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001326 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1327 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001328 } // if
srs5694fed16d02010-01-27 23:03:40 -05001329 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001330 which = use_bsd;
1331 } // if
1332
1333 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001334 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001335 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001336 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001337 } // if
1338 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001339 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001340 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001341 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001342 } // if
1343 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001344 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001345 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001346 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001347 } // if
1348 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001349 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001350 } // if
1351
srs5694e4ac11e2009-08-31 10:13:04 -04001352 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001353 if (mbrState == gpt) {
1354 cout << "\a\a****************************************************************************\n"
1355 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1356 << "verification and recovery are STRONGLY recommended.\n"
1357 << "****************************************************************************\n";
1358 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001359 } else {
srs569408bb0da2010-02-19 17:19:55 -05001360 which = use_abort;
1361 } // if/else MBR says disk is GPT
1362 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001363
1364 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001365 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001366
1367 return which;
1368} // UseWhichPartitions()
1369
srs569408bb0da2010-02-19 17:19:55 -05001370// Convert MBR partition table into GPT form.
1371void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001372 int i, numToConvert;
1373 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001374
1375 // Clear out old data & prepare basics....
1376 ClearGPTData();
1377
1378 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001379 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001380 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001381 else
srs56940283dae2010-04-28 16:44:34 -04001382 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001383
1384 for (i = 0; i < numToConvert; i++) {
1385 origType = protectiveMBR.GetType(i);
1386 // don't waste CPU time trying to convert extended, hybrid protective, or
1387 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001388 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001389 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001390 partitions[i] = protectiveMBR.AsGPT(i);
1391 } // for
1392
1393 // Convert MBR into protective MBR
1394 protectiveMBR.MakeProtectiveMBR();
1395
1396 // Record that all original CRCs were OK so as not to raise flags
1397 // when doing a disk verification
1398 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001399} // GPTData::XFormPartitions()
1400
1401// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001402// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001403// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001404int GPTData::XFormDisklabel(uint32_t partNum) {
1405 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001406 int goOn = 1, numDone = 0;
1407 BSDData disklabel;
1408
srs569408bb0da2010-02-19 17:19:55 -05001409 if (GetPartRange(&low, &high) == 0) {
1410 goOn = 0;
1411 cout << "No partitions!\n";
1412 } // if
1413 if (partNum > high) {
1414 goOn = 0;
1415 cout << "Specified partition is invalid!\n";
1416 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001417
srs569408bb0da2010-02-19 17:19:55 -05001418 // If all is OK, read the disklabel and convert it.
1419 if (goOn) {
1420 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1421 partitions[partNum].GetLastLBA());
1422 if ((goOn) && (disklabel.IsDisklabel())) {
1423 numDone = XFormDisklabel(&disklabel);
1424 if (numDone == 1)
1425 cout << "Converted 1 BSD partition.\n";
1426 else
1427 cout << "Converted " << numDone << " BSD partitions.\n";
1428 } else {
1429 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1430 } // if/else
1431 } // if
1432 if (numDone > 0) { // converted partitions; delete carrier
1433 partitions[partNum].BlankPartition();
1434 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001435 return numDone;
srs569455d92612010-03-07 22:16:07 -05001436} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001437
1438// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001439int GPTData::XFormDisklabel(BSDData* disklabel) {
1440 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001441
srs569408bb0da2010-02-19 17:19:55 -05001442 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001443 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001444 partNum = FindFirstFreePart();
1445 if (partNum >= 0) {
1446 partitions[partNum] = disklabel->AsGPT(i);
1447 if (partitions[partNum].IsUsed())
1448 numDone++;
1449 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001450 } // for
srs569408bb0da2010-02-19 17:19:55 -05001451 if (partNum == -1)
1452 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001453 } // if
1454
1455 // Record that all original CRCs were OK so as not to raise flags
1456 // when doing a disk verification
1457 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1458
1459 return numDone;
1460} // GPTData::XFormDisklabel(BSDData* disklabel)
1461
srs569408bb0da2010-02-19 17:19:55 -05001462// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1463// partition has the active/bootable flag UNset and uses the GPT fdisk
1464// type code divided by 0x0100 as the MBR type code.
1465// Returns 1 if operation was 100% successful, 0 if there were ANY
1466// problems.
srs5694978041c2009-09-21 20:51:47 -04001467int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001468 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001469
srs5694978041c2009-09-21 20:51:47 -04001470 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001471 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001472 allOK = 0;
1473 } // if
srs56940283dae2010-04-28 16:44:34 -04001474 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001475 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001476 allOK = 0;
1477 } // if
1478 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001479 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001480 allOK = 0;
1481 } // if
1482 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1483 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1484 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001485 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1486 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001487 } // if
srs5694978041c2009-09-21 20:51:47 -04001488 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001489 (uint32_t) partitions[gptPart].GetLengthLBA(),
1490 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001491 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001492 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1493 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1494 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001495 allOK = 0;
1496 } // if/else
1497 return allOK;
1498} // GPTData::OnePartToMBR()
1499
srs569455d92612010-03-07 22:16:07 -05001500// Convert partitions to MBR form (primary and logical) and return
1501// the number done. Partitions are specified in a PartNotes variable,
1502// which includes pointers to GPT partition numbers. A partition number
1503// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1504// location in the table, and MBR_EMPTY means not to create a partition
1505// in that table position. If the partition type entry for a partition
1506// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001507// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001508// protective partitions or extended partitions.
1509int GPTData::PartsToMBR(PartNotes & notes) {
1510 int mbrNum = 0, numConverted = 0;
1511 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001512
srs56949ddc14b2010-08-22 22:44:42 -04001513 protectiveMBR.EmptyMBR(0);
srs569455d92612010-03-07 22:16:07 -05001514 protectiveMBR.SetDiskSize(diskSize);
1515 notes.Rewind();
1516 while (notes.GetNextInfo(&convInfo) >= 0) {
1517 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1518 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1519 if (convInfo.hexCode != 0)
1520 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1521 if (convInfo.active)
1522 protectiveMBR.SetPartBootable(mbrNum);
1523 mbrNum++;
1524 } // if
srs569461768bc2010-07-04 01:54:00 -04001525 if (convInfo.gptPartNum == MBR_EFI_GPT)
1526 mbrNum++;
1527 } // for
1528 // Now go through and set sizes for MBR_EFI_GPT partitions....
1529 notes.Rewind();
1530 mbrNum = 0;
1531 while (notes.GetNextInfo(&convInfo) >= 0) {
1532 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY))
1533 mbrNum++;
srs569455d92612010-03-07 22:16:07 -05001534 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1535 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1536 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1537 protectiveMBR.SetHybrid();
1538 } else {
1539 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1540 } // if/else
1541 mbrNum++;
srs569461768bc2010-07-04 01:54:00 -04001542 } // if
1543 } // while
srs569455d92612010-03-07 22:16:07 -05001544 // Now do logical partition(s)...
1545 protectiveMBR.SetDisk(&myDisk);
1546 numConverted += protectiveMBR.CreateLogicals(notes);
srs569408bb0da2010-02-19 17:19:55 -05001547 return numConverted;
1548} // GPTData::PartsToMBR()
1549
srs5694e4ac11e2009-08-31 10:13:04 -04001550
1551/**********************************************************************
1552 * *
1553 * Functions that adjust GPT data structures WITHOUT user interaction *
1554 * (they may display information for the user's benefit, though) *
1555 * *
1556 **********************************************************************/
1557
1558// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001559// necessary, copies data if it already exists. Returns 1 if all goes
1560// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001561int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001562 GPTPart* newParts;
1563 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001564 uint32_t i, high, copyNum;
1565 int allOK = 1;
1566
1567 // First, adjust numEntries upward, if necessary, to get a number
1568 // that fills the allocated sectors
1569 i = blockSize / GPT_SIZE;
1570 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001571 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001572 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001573 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001574 } // if
1575
srs5694247657a2009-11-26 18:36:12 -05001576 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001577 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001578 // partition table, which causes problems when loading data from a RAID
1579 // array that's been expanded because this function is called when loading
1580 // data.
srs56940283dae2010-04-28 16:44:34 -04001581 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001582 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001583 if (newParts != NULL) {
1584 if (partitions != NULL) { // existing partitions; copy them over
1585 GetPartRange(&i, &high);
1586 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001587 cout << "The highest-numbered partition is " << high + 1
1588 << ", which is greater than the requested\n"
1589 << "partition table size of " << numEntries
1590 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001591 allOK = 0;
1592 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001593 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001594 copyNum = numEntries;
1595 else
srs56940283dae2010-04-28 16:44:34 -04001596 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001597 for (i = 0; i < copyNum; i++) {
1598 newParts[i] = partitions[i];
1599 } // for
1600 trash = partitions;
1601 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001602 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001603 } // if
1604 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001605 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001606 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001607 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001608 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1609 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1610 MoveSecondHeaderToEnd();
1611 if (diskSize > 0)
1612 CheckGPTSize();
1613 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001614 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001615 allOK = 0;
1616 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001617 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001618 mainHeader.numParts = numParts;
1619 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001620 return (allOK);
1621} // GPTData::SetGPTSize()
1622
1623// Blank the partition array
1624void GPTData::BlankPartitions(void) {
1625 uint32_t i;
1626
srs56940283dae2010-04-28 16:44:34 -04001627 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001628 partitions[i].BlankPartition();
1629 } // for
1630} // GPTData::BlankPartitions()
1631
srs5694ba00fed2010-01-12 18:18:36 -05001632// Delete a partition by number. Returns 1 if successful,
1633// 0 if there was a problem. Returns 1 if partition was in
1634// range, 0 if it was out of range.
1635int GPTData::DeletePartition(uint32_t partNum) {
1636 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001637 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001638
srs56940283dae2010-04-28 16:44:34 -04001639 numUsedParts = GetPartRange(&low, &high);
1640 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001641 // In case there's a protective MBR, look for & delete matching
1642 // MBR partition....
1643 startSector = partitions[partNum].GetFirstLBA();
1644 length = partitions[partNum].GetLengthLBA();
1645 protectiveMBR.DeleteByLocation(startSector, length);
1646
1647 // Now delete the GPT partition
1648 partitions[partNum].BlankPartition();
1649 } else {
srs5694fed16d02010-01-27 23:03:40 -05001650 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001651 retval = 0;
1652 } // if/else
1653 return retval;
1654} // GPTData::DeletePartition(uint32_t partNum)
1655
srs569408bb0da2010-02-19 17:19:55 -05001656// Non-interactively create a partition.
1657// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001658uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001659 int retval = 1; // assume there'll be no problems
1660
1661 if (IsFreePartNum(partNum)) {
1662 Align(&startSector); // Align sector to correct multiple
1663 if (IsFree(startSector) && (startSector <= endSector)) {
1664 if (FindLastInFree(startSector) >= endSector) {
1665 partitions[partNum].SetFirstLBA(startSector);
1666 partitions[partNum].SetLastLBA(endSector);
1667 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001668 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001669 } else retval = 0; // if free space until endSector
1670 } else retval = 0; // if startSector is free
1671 } else retval = 0; // if legal partition number
1672 return retval;
1673} // GPTData::CreatePartition(partNum, startSector, endSector)
1674
srs5694e4ac11e2009-08-31 10:13:04 -04001675// Sort the GPT entries, eliminating gaps and making for a logical
1676// ordering. Relies on QuickSortGPT() for the bulk of the work
1677void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001678 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001679
1680 // First, find the last partition with data, so as not to
1681 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001682 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001683
1684 // Now swap empties with the last partitions, to simplify the logic
1685 // in the Quicksort function....
1686 i = 0;
1687 while (i < lastPart) {
1688 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001689 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001690 do {
1691 lastPart--;
1692 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001693 } // if
1694 i++;
1695 } // while
1696
srs5694546a9c72010-01-26 16:00:26 -05001697 // If there are more empties than partitions in the range from 0 to lastPart,
1698 // the above leaves lastPart set too high, so we've got to adjust it to
1699 // prevent empties from migrating to the top of the list....
1700 GetPartRange(&firstPart, &lastPart);
1701
srs5694e4ac11e2009-08-31 10:13:04 -04001702 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001703 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001704} // GPTData::SortGPT()
1705
srs569408bb0da2010-02-19 17:19:55 -05001706// Recursive quick sort algorithm for GPT partitions. Note that if there
1707// are any empties in the specified range, they'll be sorted to the
1708// start, resulting in a sorted set of partitions that begins with
1709// partition 2, 3, or higher.
1710void GPTData::QuickSortGPT(int start, int finish) {
1711 uint64_t starterValue; // starting location of median partition
1712 int left, right;
1713
1714 left = start;
1715 right = finish;
1716 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1717 do {
1718 while (partitions[left].GetFirstLBA() < starterValue)
1719 left++;
1720 while (partitions[right].GetFirstLBA() > starterValue)
1721 right--;
1722 if (left <= right)
1723 SwapPartitions(left++, right--);
1724 } while (left <= right);
1725 if (start < right) QuickSortGPT(start, right);
1726 if (finish > left) QuickSortGPT(left, finish);
1727} // GPTData::QuickSortGPT()
1728
1729// Swap the contents of two partitions.
1730// Returns 1 if successful, 0 if either partition is out of range
1731// (that is, not a legal number; either or both can be empty).
1732// Note that if partNum1 = partNum2 and this number is in range,
1733// it will be considered successful.
1734int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1735 GPTPart temp;
1736 int allOK = 1;
1737
srs56940283dae2010-04-28 16:44:34 -04001738 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001739 if (partNum1 != partNum2) {
1740 temp = partitions[partNum1];
1741 partitions[partNum1] = partitions[partNum2];
1742 partitions[partNum2] = temp;
1743 } // if
1744 } else allOK = 0; // partition numbers are valid
1745 return allOK;
1746} // GPTData::SwapPartitions()
1747
srs5694e4ac11e2009-08-31 10:13:04 -04001748// Set up data structures for entirely new set of partitions on the
1749// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001750// Note that this function does NOT clear the protectiveMBR data
1751// structure, since it may hold the original MBR partitions if the
1752// program was launched on an MBR disk, and those may need to be
1753// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001754int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001755 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001756
1757 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001758 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001759 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001760 partitions = NULL;
1761 SetGPTSize(NUM_GPT_ENTRIES);
1762
1763 // Now initialize a bunch of stuff that's static....
1764 mainHeader.signature = GPT_SIGNATURE;
1765 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001766 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001767 mainHeader.reserved = 0;
1768 mainHeader.currentLBA = UINT64_C(1);
1769 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1770 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1771 for (i = 0; i < GPT_RESERVED; i++) {
1772 mainHeader.reserved2[i] = '\0';
1773 } // for
srs56948a4ddfc2010-03-21 19:05:49 -04001774 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001775
1776 // Now some semi-static items (computed based on end of disk)
1777 mainHeader.backupLBA = diskSize - UINT64_C(1);
1778 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1779
1780 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001781 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001782
1783 // Copy main header to backup header
1784 RebuildSecondHeader();
1785
1786 // Blank out the partitions array....
1787 BlankPartitions();
1788
1789 // Flag all CRCs as being OK....
1790 mainCrcOk = 1;
1791 secondCrcOk = 1;
1792 mainPartsCrcOk = 1;
1793 secondPartsCrcOk = 1;
1794
1795 return (goOn);
1796} // GPTData::ClearGPTData()
1797
srs5694247657a2009-11-26 18:36:12 -05001798// Set the location of the second GPT header data to the end of the disk.
1799// Used internally and called by the 'e' option on the recovery &
1800// transformation menu, to help users of RAID arrays who add disk space
1801// to their arrays.
1802void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001803 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1804 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1805 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1806} // GPTData::FixSecondHeaderLocation()
1807
srs56940a697312010-01-28 21:10:52 -05001808int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001809 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001810
1811 if (!IsFreePartNum(partNum)) {
1812 partitions[partNum].SetName(theName);
1813 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001814
1815 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001816} // GPTData::SetName
1817
1818// Set the disk GUID to the specified value. Note that the header CRCs must
1819// be recomputed after calling this function.
1820void GPTData::SetDiskGUID(GUIDData newGUID) {
1821 mainHeader.diskGUID = newGUID;
1822 secondHeader.diskGUID = newGUID;
1823} // SetDiskGUID()
1824
1825// Set the unique GUID of the specified partition. Returns 1 on
1826// successful completion, 0 if there were problems (invalid
1827// partition number).
1828int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1829 int retval = 0;
1830
srs56940283dae2010-04-28 16:44:34 -04001831 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001832 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1833 partitions[pn].SetUniqueGUID(theGUID);
1834 retval = 1;
1835 } // if
1836 } // if
1837 return retval;
1838} // GPTData::SetPartitionGUID()
1839
srs56949ba54212010-05-18 23:24:02 -04001840// Set new random GUIDs for the disk and all partitions. Intended to be used
1841// after disk cloning or similar operations that don't randomize the GUIDs.
1842void GPTData::RandomizeGUIDs(void) {
1843 uint32_t i;
1844
1845 mainHeader.diskGUID.Randomize();
1846 secondHeader.diskGUID = mainHeader.diskGUID;
1847 for (i = 0; i < numParts; i++)
1848 if (partitions[i].IsUsed())
1849 partitions[i].RandomizeUniqueGUID();
1850} // GPTData::RandomizeGUIDs()
1851
srs5694ba00fed2010-01-12 18:18:36 -05001852// Change partition type code non-interactively. Returns 1 if
1853// successful, 0 if not....
1854int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1855 int retval = 1;
1856
1857 if (!IsFreePartNum(partNum)) {
1858 partitions[partNum].SetType(hexCode);
1859 } else retval = 0;
1860 return retval;
1861} // GPTData::ChangePartType()
1862
srs56949ba54212010-05-18 23:24:02 -04001863// Recompute the CHS values of all the MBR partitions. Used to reset
1864// CHS values that some BIOSes require, despite the fact that the
1865// resulting CHS values violate the GPT standard.
1866void GPTData::RecomputeCHS(void) {
1867 int i;
1868
1869 for (i = 0; i < 4; i++)
1870 protectiveMBR.RecomputeCHS(i);
1871} // GPTData::RecomputeCHS()
1872
srs56941d1448a2009-12-31 21:20:19 -05001873// Adjust sector number so that it falls on a sector boundary that's a
1874// multiple of sectorAlignment. This is done to improve the performance
1875// of Western Digital Advanced Format disks and disks with similar
1876// technology from other companies, which use 4096-byte sectors
1877// internally although they translate to 512-byte sectors for the
1878// benefit of the OS. If partitions aren't properly aligned on these
1879// disks, some filesystem data structures can span multiple physical
1880// sectors, degrading performance. This function should be called
1881// only on the FIRST sector of the partition, not the last!
1882// This function returns 1 if the alignment was altered, 0 if it
1883// was unchanged.
1884int GPTData::Align(uint64_t* sector) {
1885 int retval = 0, sectorOK = 0;
1886 uint64_t earlier, later, testSector, original;
1887
1888 if ((*sector % sectorAlignment) != 0) {
1889 original = *sector;
1890 retval = 1;
1891 earlier = (*sector / sectorAlignment) * sectorAlignment;
1892 later = earlier + (uint64_t) sectorAlignment;
1893
1894 // Check to see that every sector between the earlier one and the
1895 // requested one is clear, and that it's not too early....
1896 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001897 sectorOK = 1;
1898 testSector = earlier;
1899 do {
1900 sectorOK = IsFree(testSector++);
1901 } while ((sectorOK == 1) && (testSector < *sector));
1902 if (sectorOK == 1) {
1903 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001904 } // if
1905 } // if firstUsableLBA check
1906
1907 // If couldn't move the sector earlier, try to move it later instead....
1908 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1909 sectorOK = 1;
1910 testSector = later;
1911 do {
1912 sectorOK = IsFree(testSector--);
1913 } while ((sectorOK == 1) && (testSector > *sector));
1914 if (sectorOK == 1) {
1915 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001916 } // if
1917 } // if
1918
1919 // If sector was changed successfully, inform the user of this fact.
1920 // Otherwise, notify the user that it couldn't be done....
1921 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001922 cout << "Information: Moved requested sector from " << original << " to "
srs56948a4ddfc2010-03-21 19:05:49 -04001923 << *sector << " in\norder to align on " << sectorAlignment
1924 << "-sector boundaries.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001925 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001926 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001927 } else {
srs5694fed16d02010-01-27 23:03:40 -05001928 cout << "Information: Sector not aligned on " << sectorAlignment
1929 << "-sector boundary and could not be moved.\n"
1930 << "If you're using a Western Digital Advanced Format or similar disk with\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001931 << "underlying 4096-byte sectors or certain types of RAID array, performance\n"
1932 << "may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001933 retval = 0;
1934 } // if/else
1935 } // if
1936 return retval;
1937} // GPTData::Align()
1938
srs5694e4ac11e2009-08-31 10:13:04 -04001939/********************************************************
1940 * *
1941 * Functions that return data about GPT data structures *
1942 * (most of these are inline in gpt.h) *
1943 * *
1944 ********************************************************/
1945
1946// Find the low and high used partition numbers (numbered from 0).
1947// Return value is the number of partitions found. Note that the
1948// *low and *high values are both set to 0 when no partitions
1949// are found, as well as when a single partition in the first
1950// position exists. Thus, the return value is the only way to
1951// tell when no partitions exist.
1952int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1953 uint32_t i;
1954 int numFound = 0;
1955
srs56940283dae2010-04-28 16:44:34 -04001956 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001957 *high = 0;
srs56940283dae2010-04-28 16:44:34 -04001958 if (numParts > 0) { // only try if partition table exists...
1959 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001960 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1961 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001962 // Set the low value only if it's not yet found...
srs56940283dae2010-04-28 16:44:34 -04001963 if (*low == (numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001964 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001965 } // if
1966 } // for
1967 } // if
1968
1969 // Above will leave *low pointing to its "not found" value if no partitions
1970 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001971 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001972 *low = 0;
1973 return numFound;
1974} // GPTData::GetPartRange()
1975
srs569408bb0da2010-02-19 17:19:55 -05001976// Returns the value of the first free partition, or -1 if none is
1977// unused.
1978int GPTData::FindFirstFreePart(void) {
1979 int i = 0;
1980
1981 if (partitions != NULL) {
srs56940283dae2010-04-28 16:44:34 -04001982 while ((partitions[i].IsUsed()) && (i < (int) numParts))
srs569408bb0da2010-02-19 17:19:55 -05001983 i++;
srs56940283dae2010-04-28 16:44:34 -04001984 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001985 i = -1;
1986 } else i = -1;
1987 return i;
1988} // GPTData::FindFirstFreePart()
1989
srs5694978041c2009-09-21 20:51:47 -04001990// Returns the number of defined partitions.
1991uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001992 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001993
srs56940283dae2010-04-28 16:44:34 -04001994 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001995 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001996 counted++;
1997 } // for
1998 return counted;
1999} // GPTData::CountParts()
2000
srs5694e4ac11e2009-08-31 10:13:04 -04002001/****************************************************
2002 * *
2003 * Functions that return data about disk free space *
2004 * *
2005 ****************************************************/
2006
2007// Find the first available block after the starting point; returns 0 if
2008// there are no available blocks left
2009uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2010 uint64_t first;
2011 uint32_t i;
2012 int firstMoved = 0;
2013
2014 // Begin from the specified starting point or from the first usable
2015 // LBA, whichever is greater...
2016 if (start < mainHeader.firstUsableLBA)
2017 first = mainHeader.firstUsableLBA;
2018 else
2019 first = start;
2020
2021 // ...now search through all partitions; if first is within an
2022 // existing partition, move it to the next sector after that
2023 // partition and repeat. If first was moved, set firstMoved
2024 // flag; repeat until firstMoved is not set, so as to catch
2025 // cases where partitions are out of sequential order....
2026 do {
2027 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002028 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002029 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002030 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002031 first = partitions[i].GetLastLBA() + 1;
2032 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002033 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002034 } // for
2035 } while (firstMoved == 1);
2036 if (first > mainHeader.lastUsableLBA)
2037 first = 0;
2038 return (first);
2039} // GPTData::FindFirstAvailable()
2040
2041// Finds the first available sector in the largest block of unallocated
2042// space on the disk. Returns 0 if there are no available blocks left
2043uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002044 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002045
2046 start = 0;
2047 do {
2048 firstBlock = FindFirstAvailable(start);
2049 if (firstBlock != UINT32_C(0)) { // something's free...
2050 lastBlock = FindLastInFree(firstBlock);
2051 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2052 if (segmentSize > selectedSize) {
2053 selectedSize = segmentSize;
2054 selectedSegment = firstBlock;
2055 } // if
2056 start = lastBlock + 1;
2057 } // if
2058 } while (firstBlock != 0);
2059 return selectedSegment;
2060} // GPTData::FindFirstInLargest()
2061
srs5694cb76c672010-02-11 22:22:22 -05002062// Find the last available block on the disk.
2063// Returns 0 if there are no available partitions
2064uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002065 uint64_t last;
2066 uint32_t i;
2067 int lastMoved = 0;
2068
2069 // Start by assuming the last usable LBA is available....
2070 last = mainHeader.lastUsableLBA;
2071
2072 // ...now, similar to algorithm in FindFirstAvailable(), search
2073 // through all partitions, moving last when it's in an existing
2074 // partition. Set the lastMoved flag so we repeat to catch cases
2075 // where partitions are out of logical order.
2076 do {
2077 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002078 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002079 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002080 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002081 last = partitions[i].GetFirstLBA() - 1;
2082 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002083 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002084 } // for
2085 } while (lastMoved == 1);
2086 if (last < mainHeader.firstUsableLBA)
2087 last = 0;
2088 return (last);
2089} // GPTData::FindLastAvailable()
2090
2091// Find the last available block in the free space pointed to by start.
2092uint64_t GPTData::FindLastInFree(uint64_t start) {
2093 uint64_t nearestStart;
2094 uint32_t i;
2095
2096 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002097 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002098 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002099 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002100 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002101 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002102 } // for
2103 return (nearestStart);
2104} // GPTData::FindLastInFree()
2105
2106// Finds the total number of free blocks, the number of segments in which
2107// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002108uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002109 uint64_t start = UINT64_C(0); // starting point for each search
2110 uint64_t totalFound = UINT64_C(0); // running total
2111 uint64_t firstBlock; // first block in a segment
2112 uint64_t lastBlock; // last block in a segment
2113 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002114 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002115
2116 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002117 if (diskSize > 0) {
2118 do {
2119 firstBlock = FindFirstAvailable(start);
2120 if (firstBlock != UINT64_C(0)) { // something's free...
2121 lastBlock = FindLastInFree(firstBlock);
2122 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2123 if (segmentSize > *largestSegment) {
2124 *largestSegment = segmentSize;
2125 } // if
2126 totalFound += segmentSize;
2127 num++;
2128 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002129 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002130 } while (firstBlock != 0);
2131 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002132 *numSegments = num;
2133 return totalFound;
2134} // GPTData::FindFreeBlocks()
2135
srs569455d92612010-03-07 22:16:07 -05002136// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2137// If it's allocated, return the partition number to which it's allocated
2138// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2139// returned in partNum if the sector is in use by basic GPT data structures.)
2140int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002141 int isFree = 1;
2142 uint32_t i;
2143
srs56940283dae2010-04-28 16:44:34 -04002144 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002145 if ((sector >= partitions[i].GetFirstLBA()) &&
2146 (sector <= partitions[i].GetLastLBA())) {
2147 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002148 if (partNum != NULL)
2149 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002150 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002151 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002152 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002153 (sector > mainHeader.lastUsableLBA)) {
2154 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002155 if (partNum != NULL)
2156 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002157 } // if
2158 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002159} // GPTData::IsFree()
2160
srs5694ba00fed2010-01-12 18:18:36 -05002161// Returns 1 if partNum is unused.
2162int GPTData::IsFreePartNum(uint32_t partNum) {
2163 int retval = 1;
2164
srs56940283dae2010-04-28 16:44:34 -04002165 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002166 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002167 retval = 0;
2168 } // if partition is in use
2169 } else retval = 0;
2170
2171 return retval;
2172} // GPTData::IsFreePartNum()
2173
srs5694a8582cf2010-03-19 14:21:59 -04002174
2175/***********************************************************
2176 * *
2177 * Change how functions work or return information on them *
2178 * *
2179 ***********************************************************/
2180
2181// Set partition alignment value; partitions will begin on multiples of
2182// the specified value
2183void GPTData::SetAlignment(uint32_t n) {
srs5694a8582cf2010-03-19 14:21:59 -04002184 sectorAlignment = n;
srs5694a8582cf2010-03-19 14:21:59 -04002185} // GPTData::SetAlignment()
2186
2187// Compute sector alignment based on the current partitions (if any). Each
2188// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56948a4ddfc2010-03-21 19:05:49 -04002189// value less than or equal to the DEFAULT_ALIGNMENT value, but not by the
2190// previously-located alignment value, then the alignment value is adjusted
2191// down. If the computed alignment is less than 8 and the disk is bigger than
2192// SMALLEST_ADVANCED_FORMAT, resets it to 8. This is a safety measure for WD
2193// Advanced Format and similar drives. If no partitions are defined, the
2194// alignment value is set to DEFAULT_ALIGNMENT (2048). The result is that new
2195// drives are aligned to 2048-sector multiples but the program won't complain
2196// about other alignments on existing disks unless a smaller-than-8 alignment
2197// is used on small disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002198// Returns the computed alignment value.
2199uint32_t GPTData::ComputeAlignment(void) {
2200 uint32_t i = 0, found, exponent = 31;
2201 uint64_t align = DEFAULT_ALIGNMENT;
2202
srs56948a4ddfc2010-03-21 19:05:49 -04002203 exponent = (uint32_t) log2(DEFAULT_ALIGNMENT);
srs56940283dae2010-04-28 16:44:34 -04002204 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002205 if (partitions[i].IsUsed()) {
2206 found = 0;
2207 while (!found) {
srs56949ddc14b2010-08-22 22:44:42 -04002208 align = UINT64_C(1)<<exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002209 if ((partitions[i].GetFirstLBA() % align) == 0) {
2210 found = 1;
2211 } else {
2212 exponent--;
2213 } // if/else
2214 } // while
2215 } // if
2216 } // for
2217 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2218 align = 8;
srs5694a8582cf2010-03-19 14:21:59 -04002219 SetAlignment(align);
2220 return align;
2221} // GPTData::ComputeAlignment()
2222
srs5694e4ac11e2009-08-31 10:13:04 -04002223/********************************
2224 * *
2225 * Endianness support functions *
2226 * *
2227 ********************************/
2228
srs56942a9f5da2009-08-26 00:48:01 -04002229void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002230 ReverseBytes(&header->signature, 8);
2231 ReverseBytes(&header->revision, 4);
2232 ReverseBytes(&header->headerSize, 4);
2233 ReverseBytes(&header->headerCRC, 4);
2234 ReverseBytes(&header->reserved, 4);
2235 ReverseBytes(&header->currentLBA, 8);
2236 ReverseBytes(&header->backupLBA, 8);
2237 ReverseBytes(&header->firstUsableLBA, 8);
2238 ReverseBytes(&header->lastUsableLBA, 8);
2239 ReverseBytes(&header->partitionEntriesLBA, 8);
2240 ReverseBytes(&header->numParts, 4);
2241 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2242 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002243 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002244} // GPTData::ReverseHeaderBytes()
2245
srs56940283dae2010-04-28 16:44:34 -04002246// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002247void GPTData::ReversePartitionBytes() {
2248 uint32_t i;
2249
srs56940283dae2010-04-28 16:44:34 -04002250 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002251 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002252 } // for
2253} // GPTData::ReversePartitionBytes()
2254
srs56949ddc14b2010-08-22 22:44:42 -04002255// Validate partition number
2256bool GPTData::ValidPartNum (const uint32_t partNum) {
2257 if (partNum >= numParts) {
2258 cerr << "Partition number out of range: " << (signed) partNum << endl;
2259 return false;
2260 } // if
2261 return true;
2262} // GPTData::ValidPartNum
2263
2264// Manage attributes for a partition, based on commands passed to this function.
2265// (Function is non-interactive.)
2266// Returns 1 if a modification command succeeded, 0 if the command should not have
2267// modified data, and -1 if a modification command failed.
2268int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2269 int retval = 0;
2270 Attributes theAttr;
2271
2272 if (command == "show") {
2273 ShowAttributes(partNum);
2274 } else if (command == "get") {
2275 GetAttribute(partNum, bits);
2276 } else {
2277 theAttr = partitions[partNum].GetAttributes();
2278 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2279 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2280 retval = 1;
2281 } else {
2282 retval = -1;
2283 } // if/else
2284 } // if/elseif/else
2285
2286 return retval;
2287} // GPTData::ManageAttributes()
2288
2289// Show all attributes for a specified partition....
2290void GPTData::ShowAttributes(const uint32_t partNum) {
2291 Attributes theAttr (partitions[partNum].GetAttributes());
2292 theAttr.ShowAttributes(partNum);
2293} // GPTData::ShowAttributes
2294
2295// Show whether a single attribute bit is set (terse output)...
2296void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
2297 Attributes theAttr (partitions[partNum].GetAttributes());
2298 theAttr.OperateOnAttributes(partNum, "get", attributeBits);
2299} // GPTData::GetAttribute
2300
2301
srs56942a9f5da2009-08-26 00:48:01 -04002302/******************************************
2303 * *
2304 * Additional non-class support functions *
2305 * *
2306 ******************************************/
2307
srs5694e7b4ff92009-08-18 13:16:10 -04002308// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2309// never fail these tests, but the struct types may fail depending on compile options.
2310// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2311// sizes.
2312int SizesOK(void) {
2313 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002314
2315 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002316 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002317 allOK = 0;
2318 } // if
2319 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002320 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002321 allOK = 0;
2322 } // if
2323 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002324 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002325 allOK = 0;
2326 } // if
2327 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002328 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002329 allOK = 0;
2330 } // if
2331 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002332 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002333 allOK = 0;
2334 } // if
srs5694978041c2009-09-21 20:51:47 -04002335 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002336 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002337 allOK = 0;
2338 } // if
2339 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002340 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002341 allOK = 0;
2342 } // if
srs5694221e0872009-08-29 15:00:31 -04002343 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002344 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002345 allOK = 0;
2346 } // if
srs56946699b012010-02-04 00:55:30 -05002347 if (sizeof(GUIDData) != 16) {
2348 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2349 allOK = 0;
2350 } // if
2351 if (sizeof(PartType) != 16) {
2352 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2353 allOK = 0;
2354 } // if
srs5694fed16d02010-01-27 23:03:40 -05002355 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002356 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002357 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2358 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002359 } // if
2360 return (allOK);
2361} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002362