blob: 213774ed44a7599a33fbfcf0faff42a076b42a31 [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;
srs5694fed16d02010-01-27 23:03:40 -0500648 cerr << "Aborting because of 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.
srs5694ba00fed2010-01-12 18:18:36 -0500872int GPTData::SaveGPTData(int quiet) {
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
srs56946699b012010-02-04 00:55:30 -0500876 littleEndian = IsLittleEndian();
877
srs5694fed16d02010-01-27 23:03:40 -0500878 if (device == "") {
879 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400880 } // if
881
882 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500883
884 // This test should only fail on read-only disks....
885 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500886 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500887 allOK = 0;
888 } // if
889
srs5694e7b4ff92009-08-18 13:16:10 -0400890 // Is there enough space to hold the GPT headers and partition tables,
891 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400892 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400893 allOK = 0;
894 } // if
895
896 // Check that disk is really big enough to handle this...
897 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500898 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
899 << "problem (or it might not). Aborting!\n(Disk size is "
900 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400901 allOK = 0;
902 } // if
srs5694247657a2009-11-26 18:36:12 -0500903 // Check that second header is properly placed. Warn and ask if this should
904 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500905 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500906 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
907 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500908 if (GetYN() == 'Y') {
909 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500910 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500911 } else {
srs5694fed16d02010-01-27 23:03:40 -0500912 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500913 } // if correction requested
914 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400915
srs569455d92612010-03-07 22:16:07 -0500916 // Check for overlapping or insane partitions....
917 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400918 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500919 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400920 } // if
921
922 // Check for mismatched MBR and GPT data, but let it pass if found
923 // (function displays warning message)
924 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400925
926 RecomputeCRCs();
927
srs5694ba00fed2010-01-12 18:18:36 -0500928 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500929 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
930 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500931 answer = GetYN();
932 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500933 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400934 } else {
935 allOK = 0;
936 } // if/else
937 } // if
938
939 // Do it!
940 if (allOK) {
srs56948a4ddfc2010-03-21 19:05:49 -0400941 if (myDisk.OpenForWrite(device)) {
942 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -0500943 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
944 if (!allOK)
945 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
946 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400947
948 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -0400949 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
950
951 // Now write the main partition tables...
952 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
953
954 // Now write the main GPT header...
955 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
956
957 // To top it off, write the protective MBR...
958 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400959
960 // re-read the partition table
961 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500962 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400963 } // if
964
965 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500966 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400967 } else {
srs5694fed16d02010-01-27 23:03:40 -0500968 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -0400969 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400970 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -0400971
srs5694546a9c72010-01-26 16:00:26 -0500972 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400973 } else {
srs5694fed16d02010-01-27 23:03:40 -0500974 cerr << "Unable to open device " << device << " for writing! Errno is "
975 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400976 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400977 } // if/else
978 } else {
srs5694fed16d02010-01-27 23:03:40 -0500979 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400980 } // if
981
982 return (allOK);
983} // GPTData::SaveGPTData()
984
985// Save GPT data to a backup file. This function does much less error
986// checking than SaveGPTData(). It can therefore preserve many types of
987// corruption for later analysis; however, it preserves only the MBR,
988// the main GPT header, the backup GPT header, and the main partition
989// table; it discards the backup partition table, since it should be
990// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500991int GPTData::SaveGPTBackup(const string & filename) {
992 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500993 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400994
srs5694546a9c72010-01-26 16:00:26 -0500995 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500996 // Recomputing the CRCs is likely to alter them, which could be bad
997 // if the intent is to save a potentially bad GPT for later analysis;
998 // but if we don't do this, we get bogus errors when we load the
999 // backup. I'm favoring misses over false alarms....
1000 RecomputeCRCs();
1001
srs5694546a9c72010-01-26 16:00:26 -05001002 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001003
srs5694cb76c672010-02-11 22:22:22 -05001004 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001005 // MBR write closed disk, so re-open and seek to end....
1006 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001007 allOK = SaveHeader(&mainHeader, backupFile, 1);
1008 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001009
srs5694e7b4ff92009-08-18 13:16:10 -04001010 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001011 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001012
srs5694cb76c672010-02-11 22:22:22 -05001013 if (allOK)
1014 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001015
1016 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001017 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001018 } else {
srs5694fed16d02010-01-27 23:03:40 -05001019 cerr << "Warning! An error was reported when writing the backup file.\n"
1020 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001021 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001022 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001023 } else {
srs5694fed16d02010-01-27 23:03:40 -05001024 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001025 allOK = 0;
1026 } // if/else
1027 return allOK;
1028} // GPTData::SaveGPTBackup()
1029
srs5694cb76c672010-02-11 22:22:22 -05001030// Write a GPT header (main or backup) to the specified sector. Used by both
1031// the SaveGPTData() and SaveGPTBackup() functions.
1032// Should be passed an architecture-appropriate header (DO NOT call
1033// ReverseHeaderBytes() on the header before calling this function)
1034// Returns 1 on success, 0 on failure
1035int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1036 int littleEndian, allOK = 1;
1037
1038 littleEndian = IsLittleEndian();
1039 if (!littleEndian)
1040 ReverseHeaderBytes(header);
1041 if (disk.Seek(sector)) {
1042 if (disk.Write(header, 512) == -1)
1043 allOK = 0;
1044 } else allOK = 0; // if (disk.Seek()...)
1045 if (!littleEndian)
1046 ReverseHeaderBytes(header);
1047 return allOK;
1048} // GPTData::SaveHeader()
1049
1050// Save the partitions to the specified sector. Used by both the SaveGPTData()
1051// and SaveGPTBackup() functions.
1052// Should be passed an architecture-appropriate header (DO NOT call
1053// ReverseHeaderBytes() on the header before calling this function)
1054// Returns 1 on success, 0 on failure
1055int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1056 int littleEndian, allOK = 1;
1057
1058 littleEndian = IsLittleEndian();
1059 if (disk.Seek(sector)) {
1060 if (!littleEndian)
1061 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001062 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001063 allOK = 0;
1064 if (!littleEndian)
1065 ReversePartitionBytes();
1066 } else allOK = 0; // if (myDisk.Seek()...)
1067 return allOK;
1068} // GPTData::SavePartitionTable()
1069
srs5694e7b4ff92009-08-18 13:16:10 -04001070// Load GPT data from a backup file created by SaveGPTBackup(). This function
1071// does minimal error checking. It returns 1 if it completed successfully,
1072// 0 if there was a problem. In the latter case, it creates a new empty
1073// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001074int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001075 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001076 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001077 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001078 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001079
srs5694546a9c72010-01-26 16:00:26 -05001080 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001081 if (IsLittleEndian() == 0)
1082 littleEndian = 0;
1083
srs5694e7b4ff92009-08-18 13:16:10 -04001084 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001085 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001086
srs5694cb76c672010-02-11 22:22:22 -05001087 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001088
srs5694cb76c672010-02-11 22:22:22 -05001089 // Check backup file size and rebuild second header if file is right
1090 // size to be direct dd copy of MBR, main header, and main partition
1091 // table; if other size, treat it like a GPT fdisk-generated backup
1092 // file
1093 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1094 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1095 if (shortBackup) {
1096 RebuildSecondHeader();
1097 secondCrcOk = mainCrcOk;
1098 } else {
1099 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1100 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001101
srs5694e7b4ff92009-08-18 13:16:10 -04001102 // Return valid headers code: 0 = both headers bad; 1 = main header
1103 // good, backup bad; 2 = backup header good, main header bad;
1104 // 3 = both headers good. Note these codes refer to valid GPT
1105 // signatures and version numbers; more subtle problems will elude
1106 // this check!
1107 if ((val = CheckHeaderValidity()) > 0) {
1108 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001109 SetGPTSize(secondHeader.numParts);
1110// numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001111 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001112 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001113 SetGPTSize(mainHeader.numParts);
1114// numParts = mainHeader.numParts;
srs5694e7b4ff92009-08-18 13:16:10 -04001115 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1116 } // if/else
1117
srs56940283dae2010-04-28 16:44:34 -04001118// SetGPTSize(numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001119
srs5694e7b4ff92009-08-18 13:16:10 -04001120 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001121 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1122 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001123 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001124 } // if
1125
srs5694cb76c672010-02-11 22:22:22 -05001126 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1127 cerr << "Warning! Read error " << errno
1128 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001129 } else {
1130 allOK = 0;
1131 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001132 // Something went badly wrong, so blank out partitions
1133 if (allOK == 0) {
1134 cerr << "Improper backup file! Clearing all partition data!\n";
1135 ClearGPTData();
1136 protectiveMBR.MakeProtectiveMBR();
1137 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001138 } else {
1139 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001140 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001141 } // if/else
1142
srs5694e7b4ff92009-08-18 13:16:10 -04001143 return allOK;
1144} // GPTData::LoadGPTBackup()
1145
srs569408bb0da2010-02-19 17:19:55 -05001146int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001147 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001148} // GPTData::SaveMBR()
1149
1150// This function destroys the on-disk GPT structures, but NOT the on-disk
1151// MBR.
1152// Returns 1 if the operation succeeds, 0 if not.
1153int GPTData::DestroyGPT(void) {
1154 int i, sum, tableSize, allOK = 1;
1155 uint8_t blankSector[512];
1156 uint8_t* emptyTable;
1157
1158 for (i = 0; i < 512; i++) {
1159 blankSector[i] = 0;
1160 } // for
1161
1162 if (myDisk.OpenForWrite()) {
1163 if (!myDisk.Seek(mainHeader.currentLBA))
1164 allOK = 0;
1165 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1166 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1167 allOK = 0;
1168 } // if
1169 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1170 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001171 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001172 emptyTable = new uint8_t[tableSize];
1173 for (i = 0; i < tableSize; i++)
1174 emptyTable[i] = 0;
1175 if (allOK) {
1176 sum = myDisk.Write(emptyTable, tableSize);
1177 if (sum != tableSize) {
1178 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1179 allOK = 0;
1180 } // if write failed
1181 } // if
1182 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1183 allOK = 0;
1184 if (allOK) {
1185 sum = myDisk.Write(emptyTable, tableSize);
1186 if (sum != tableSize) {
1187 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1188 << errno << "\n";
1189 allOK = 0;
1190 } // if wrong size written
1191 } // if
1192 if (!myDisk.Seek(secondHeader.currentLBA))
1193 allOK = 0;
1194 if (allOK) {
1195 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1196 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1197 allOK = 0;
1198 } // if
1199 } // if
1200 myDisk.DiskSync();
1201 myDisk.Close();
1202 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1203 << "other utilities.\n";
1204 delete[] emptyTable;
1205 } else {
1206 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1207 } // if/else (fd != -1)
1208 return (allOK);
1209} // GPTDataTextUI::DestroyGPT()
1210
1211// Wipe MBR data from the disk (zero it out completely)
1212// Returns 1 on success, 0 on failure.
1213int GPTData::DestroyMBR(void) {
1214 int allOK = 1, i;
1215 uint8_t blankSector[512];
1216
1217 for (i = 0; i < 512; i++)
1218 blankSector[i] = 0;
1219
1220 if (myDisk.OpenForWrite()) {
1221 if (myDisk.Seek(0)) {
1222 if (myDisk.Write(blankSector, 512) != 512)
1223 allOK = 0;
1224 } else allOK = 0;
1225 } else allOK = 0;
1226 if (!allOK)
1227 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1228 return allOK;
1229} // GPTData::DestroyMBR(void)
1230
srs5694e4ac11e2009-08-31 10:13:04 -04001231// Tell user whether Apple Partition Map (APM) was discovered....
1232void GPTData::ShowAPMState(void) {
1233 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001234 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001235 else
srs5694fed16d02010-01-27 23:03:40 -05001236 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001237} // GPTData::ShowAPMState()
1238
1239// Tell user about the state of the GPT data....
1240void GPTData::ShowGPTState(void) {
1241 switch (state) {
1242 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001243 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001244 break;
1245 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001246 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001247 break;
1248 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001250 break;
1251 default:
srs5694fed16d02010-01-27 23:03:40 -05001252 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001253 break;
1254 } // switch
1255} // GPTData::ShowGPTState()
1256
1257// Display the basic GPT data
1258void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001259 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001260 uint64_t temp, totalFree;
1261
srs5694fed16d02010-01-27 23:03:40 -05001262 cout << "Disk " << device << ": " << diskSize << " sectors, "
1263 << BytesToSI(diskSize * blockSize) << "\n";
1264 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001265 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs56940283dae2010-04-28 16:44:34 -04001266 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001267 cout << "First usable sector is " << mainHeader.firstUsableLBA
1268 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001269 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001270 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001271 cout << "Total free space is " << totalFree << " sectors ("
1272 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1273 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001274 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001275 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001276 } // for
1277} // GPTData::DisplayGPTData()
1278
srs5694e4ac11e2009-08-31 10:13:04 -04001279// Show detailed information on the specified partition
1280void GPTData::ShowPartDetails(uint32_t partNum) {
1281 if (partitions[partNum].GetFirstLBA() != 0) {
1282 partitions[partNum].ShowDetails(blockSize);
1283 } else {
srs5694fed16d02010-01-27 23:03:40 -05001284 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001285 } // if
1286} // GPTData::ShowPartDetails()
1287
srs5694e4ac11e2009-08-31 10:13:04 -04001288/**************************************************************************
1289 * *
1290 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1291 * (some of these functions may require user interaction) *
1292 * *
1293 **************************************************************************/
1294
srs569408bb0da2010-02-19 17:19:55 -05001295// Examines the MBR & GPT data to determine which set of data to use: the
1296// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1297// a new set of partitions (use_new). A return value of use_abort indicates
1298// that this function couldn't determine what to do. Overriding functions
1299// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001300WhichToUse GPTData::UseWhichPartitions(void) {
1301 WhichToUse which = use_new;
1302 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001303
1304 mbrState = protectiveMBR.GetValidity();
1305
1306 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001307 cout << "\n***************************************************************\n"
1308 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001309 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001310 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001311 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001312 } // if
srs5694fed16d02010-01-27 23:03:40 -05001313 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001314 which = use_mbr;
1315 } // if
1316
1317 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001318 cout << "\n**********************************************************************\n"
1319 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1320 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001321 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001322 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001323 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1324 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001325 } // if
srs5694fed16d02010-01-27 23:03:40 -05001326 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001327 which = use_bsd;
1328 } // if
1329
1330 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001331 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001332 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001333 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001334 } // if
1335 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001336 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001337 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001338 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001339 } // if
1340 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001341 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001342 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001343 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001344 } // if
1345 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001346 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001347 } // if
1348
srs5694e4ac11e2009-08-31 10:13:04 -04001349 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001350 if (mbrState == gpt) {
1351 cout << "\a\a****************************************************************************\n"
1352 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1353 << "verification and recovery are STRONGLY recommended.\n"
1354 << "****************************************************************************\n";
1355 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001356 } else {
srs569408bb0da2010-02-19 17:19:55 -05001357 which = use_abort;
1358 } // if/else MBR says disk is GPT
1359 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001360
1361 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001362 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001363
1364 return which;
1365} // UseWhichPartitions()
1366
srs569408bb0da2010-02-19 17:19:55 -05001367// Convert MBR partition table into GPT form.
1368void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001369 int i, numToConvert;
1370 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001371
1372 // Clear out old data & prepare basics....
1373 ClearGPTData();
1374
1375 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001376 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001377 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001378 else
srs56940283dae2010-04-28 16:44:34 -04001379 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001380
1381 for (i = 0; i < numToConvert; i++) {
1382 origType = protectiveMBR.GetType(i);
1383 // don't waste CPU time trying to convert extended, hybrid protective, or
1384 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001385 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001386 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001387 partitions[i] = protectiveMBR.AsGPT(i);
1388 } // for
1389
1390 // Convert MBR into protective MBR
1391 protectiveMBR.MakeProtectiveMBR();
1392
1393 // Record that all original CRCs were OK so as not to raise flags
1394 // when doing a disk verification
1395 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001396} // GPTData::XFormPartitions()
1397
1398// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001399// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001400// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001401int GPTData::XFormDisklabel(uint32_t partNum) {
1402 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001403 int goOn = 1, numDone = 0;
1404 BSDData disklabel;
1405
srs569408bb0da2010-02-19 17:19:55 -05001406 if (GetPartRange(&low, &high) == 0) {
1407 goOn = 0;
1408 cout << "No partitions!\n";
1409 } // if
1410 if (partNum > high) {
1411 goOn = 0;
1412 cout << "Specified partition is invalid!\n";
1413 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001414
srs569408bb0da2010-02-19 17:19:55 -05001415 // If all is OK, read the disklabel and convert it.
1416 if (goOn) {
1417 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1418 partitions[partNum].GetLastLBA());
1419 if ((goOn) && (disklabel.IsDisklabel())) {
1420 numDone = XFormDisklabel(&disklabel);
1421 if (numDone == 1)
1422 cout << "Converted 1 BSD partition.\n";
1423 else
1424 cout << "Converted " << numDone << " BSD partitions.\n";
1425 } else {
1426 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1427 } // if/else
1428 } // if
1429 if (numDone > 0) { // converted partitions; delete carrier
1430 partitions[partNum].BlankPartition();
1431 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001432 return numDone;
srs569455d92612010-03-07 22:16:07 -05001433} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001434
1435// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001436int GPTData::XFormDisklabel(BSDData* disklabel) {
1437 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001438
srs569408bb0da2010-02-19 17:19:55 -05001439 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001440 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001441 partNum = FindFirstFreePart();
1442 if (partNum >= 0) {
1443 partitions[partNum] = disklabel->AsGPT(i);
1444 if (partitions[partNum].IsUsed())
1445 numDone++;
1446 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001447 } // for
srs569408bb0da2010-02-19 17:19:55 -05001448 if (partNum == -1)
1449 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001450 } // if
1451
1452 // Record that all original CRCs were OK so as not to raise flags
1453 // when doing a disk verification
1454 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1455
1456 return numDone;
1457} // GPTData::XFormDisklabel(BSDData* disklabel)
1458
srs569408bb0da2010-02-19 17:19:55 -05001459// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1460// partition has the active/bootable flag UNset and uses the GPT fdisk
1461// type code divided by 0x0100 as the MBR type code.
1462// Returns 1 if operation was 100% successful, 0 if there were ANY
1463// problems.
srs5694978041c2009-09-21 20:51:47 -04001464int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001465 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001466
srs5694978041c2009-09-21 20:51:47 -04001467 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001468 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001469 allOK = 0;
1470 } // if
srs56940283dae2010-04-28 16:44:34 -04001471 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001472 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001473 allOK = 0;
1474 } // if
1475 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001476 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001477 allOK = 0;
1478 } // if
1479 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1480 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1481 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001482 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1483 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001484 } // if
srs5694978041c2009-09-21 20:51:47 -04001485 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001486 (uint32_t) partitions[gptPart].GetLengthLBA(),
1487 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001488 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001489 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1490 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1491 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001492 allOK = 0;
1493 } // if/else
1494 return allOK;
1495} // GPTData::OnePartToMBR()
1496
srs569455d92612010-03-07 22:16:07 -05001497// Convert partitions to MBR form (primary and logical) and return
1498// the number done. Partitions are specified in a PartNotes variable,
1499// which includes pointers to GPT partition numbers. A partition number
1500// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1501// location in the table, and MBR_EMPTY means not to create a partition
1502// in that table position. If the partition type entry for a partition
1503// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001504// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001505// protective partitions or extended partitions.
1506int GPTData::PartsToMBR(PartNotes & notes) {
1507 int mbrNum = 0, numConverted = 0;
1508 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001509
srs569455d92612010-03-07 22:16:07 -05001510 protectiveMBR.EmptyMBR();
1511 protectiveMBR.SetDiskSize(diskSize);
1512 notes.Rewind();
1513 while (notes.GetNextInfo(&convInfo) >= 0) {
1514 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1515 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1516 if (convInfo.hexCode != 0)
1517 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1518 if (convInfo.active)
1519 protectiveMBR.SetPartBootable(mbrNum);
1520 mbrNum++;
1521 } // if
1522 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1523 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1524 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1525 protectiveMBR.SetHybrid();
1526 } else {
1527 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1528 } // if/else
1529 mbrNum++;
1530 } // if EFI GPT partition specified
1531 } // for
1532 // Now do logical partition(s)...
1533 protectiveMBR.SetDisk(&myDisk);
1534 numConverted += protectiveMBR.CreateLogicals(notes);
1535// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001536 return numConverted;
1537} // GPTData::PartsToMBR()
1538
srs5694e4ac11e2009-08-31 10:13:04 -04001539
1540/**********************************************************************
1541 * *
1542 * Functions that adjust GPT data structures WITHOUT user interaction *
1543 * (they may display information for the user's benefit, though) *
1544 * *
1545 **********************************************************************/
1546
1547// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001548// necessary, copies data if it already exists. Returns 1 if all goes
1549// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001550int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001551 GPTPart* newParts;
1552 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001553 uint32_t i, high, copyNum;
1554 int allOK = 1;
1555
1556 // First, adjust numEntries upward, if necessary, to get a number
1557 // that fills the allocated sectors
1558 i = blockSize / GPT_SIZE;
1559 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001560 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001561 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001562 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001563 } // if
1564
srs5694247657a2009-11-26 18:36:12 -05001565 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001566 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001567 // partition table, which causes problems when loading data from a RAID
1568 // array that's been expanded because this function is called when loading
1569 // data.
srs56940283dae2010-04-28 16:44:34 -04001570 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001571 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001572 if (newParts != NULL) {
1573 if (partitions != NULL) { // existing partitions; copy them over
1574 GetPartRange(&i, &high);
1575 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001576 cout << "The highest-numbered partition is " << high + 1
1577 << ", which is greater than the requested\n"
1578 << "partition table size of " << numEntries
1579 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001580 allOK = 0;
1581 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001582 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001583 copyNum = numEntries;
1584 else
srs56940283dae2010-04-28 16:44:34 -04001585 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001586 for (i = 0; i < copyNum; i++) {
1587 newParts[i] = partitions[i];
1588 } // for
1589 trash = partitions;
1590 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001591 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001592 } // if
1593 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001594 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001595 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001596 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001597 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1598 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1599 MoveSecondHeaderToEnd();
1600 if (diskSize > 0)
1601 CheckGPTSize();
1602 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001603 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001604 allOK = 0;
1605 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001606 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001607 mainHeader.numParts = numParts;
1608 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001609 return (allOK);
1610} // GPTData::SetGPTSize()
1611
1612// Blank the partition array
1613void GPTData::BlankPartitions(void) {
1614 uint32_t i;
1615
srs56940283dae2010-04-28 16:44:34 -04001616 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001617 partitions[i].BlankPartition();
1618 } // for
1619} // GPTData::BlankPartitions()
1620
srs5694ba00fed2010-01-12 18:18:36 -05001621// Delete a partition by number. Returns 1 if successful,
1622// 0 if there was a problem. Returns 1 if partition was in
1623// range, 0 if it was out of range.
1624int GPTData::DeletePartition(uint32_t partNum) {
1625 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001626 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001627
srs56940283dae2010-04-28 16:44:34 -04001628 numUsedParts = GetPartRange(&low, &high);
1629 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001630 // In case there's a protective MBR, look for & delete matching
1631 // MBR partition....
1632 startSector = partitions[partNum].GetFirstLBA();
1633 length = partitions[partNum].GetLengthLBA();
1634 protectiveMBR.DeleteByLocation(startSector, length);
1635
1636 // Now delete the GPT partition
1637 partitions[partNum].BlankPartition();
1638 } else {
srs5694fed16d02010-01-27 23:03:40 -05001639 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001640 retval = 0;
1641 } // if/else
1642 return retval;
1643} // GPTData::DeletePartition(uint32_t partNum)
1644
srs569408bb0da2010-02-19 17:19:55 -05001645// Non-interactively create a partition.
1646// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001647uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001648 int retval = 1; // assume there'll be no problems
1649
1650 if (IsFreePartNum(partNum)) {
1651 Align(&startSector); // Align sector to correct multiple
1652 if (IsFree(startSector) && (startSector <= endSector)) {
1653 if (FindLastInFree(startSector) >= endSector) {
1654 partitions[partNum].SetFirstLBA(startSector);
1655 partitions[partNum].SetLastLBA(endSector);
1656 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001657 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001658 } else retval = 0; // if free space until endSector
1659 } else retval = 0; // if startSector is free
1660 } else retval = 0; // if legal partition number
1661 return retval;
1662} // GPTData::CreatePartition(partNum, startSector, endSector)
1663
srs5694e4ac11e2009-08-31 10:13:04 -04001664// Sort the GPT entries, eliminating gaps and making for a logical
1665// ordering. Relies on QuickSortGPT() for the bulk of the work
1666void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001667 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001668
1669 // First, find the last partition with data, so as not to
1670 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001671 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001672
1673 // Now swap empties with the last partitions, to simplify the logic
1674 // in the Quicksort function....
1675 i = 0;
1676 while (i < lastPart) {
1677 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001678 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001679 do {
1680 lastPart--;
1681 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001682 } // if
1683 i++;
1684 } // while
1685
srs5694546a9c72010-01-26 16:00:26 -05001686 // If there are more empties than partitions in the range from 0 to lastPart,
1687 // the above leaves lastPart set too high, so we've got to adjust it to
1688 // prevent empties from migrating to the top of the list....
1689 GetPartRange(&firstPart, &lastPart);
1690
srs5694e4ac11e2009-08-31 10:13:04 -04001691 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001692 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001693} // GPTData::SortGPT()
1694
srs569408bb0da2010-02-19 17:19:55 -05001695// Recursive quick sort algorithm for GPT partitions. Note that if there
1696// are any empties in the specified range, they'll be sorted to the
1697// start, resulting in a sorted set of partitions that begins with
1698// partition 2, 3, or higher.
1699void GPTData::QuickSortGPT(int start, int finish) {
1700 uint64_t starterValue; // starting location of median partition
1701 int left, right;
1702
1703 left = start;
1704 right = finish;
1705 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1706 do {
1707 while (partitions[left].GetFirstLBA() < starterValue)
1708 left++;
1709 while (partitions[right].GetFirstLBA() > starterValue)
1710 right--;
1711 if (left <= right)
1712 SwapPartitions(left++, right--);
1713 } while (left <= right);
1714 if (start < right) QuickSortGPT(start, right);
1715 if (finish > left) QuickSortGPT(left, finish);
1716} // GPTData::QuickSortGPT()
1717
1718// Swap the contents of two partitions.
1719// Returns 1 if successful, 0 if either partition is out of range
1720// (that is, not a legal number; either or both can be empty).
1721// Note that if partNum1 = partNum2 and this number is in range,
1722// it will be considered successful.
1723int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1724 GPTPart temp;
1725 int allOK = 1;
1726
srs56940283dae2010-04-28 16:44:34 -04001727 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001728 if (partNum1 != partNum2) {
1729 temp = partitions[partNum1];
1730 partitions[partNum1] = partitions[partNum2];
1731 partitions[partNum2] = temp;
1732 } // if
1733 } else allOK = 0; // partition numbers are valid
1734 return allOK;
1735} // GPTData::SwapPartitions()
1736
srs5694e4ac11e2009-08-31 10:13:04 -04001737// Set up data structures for entirely new set of partitions on the
1738// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001739// Note that this function does NOT clear the protectiveMBR data
1740// structure, since it may hold the original MBR partitions if the
1741// program was launched on an MBR disk, and those may need to be
1742// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001743int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001744 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001745
1746 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001747 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001748 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001749 partitions = NULL;
1750 SetGPTSize(NUM_GPT_ENTRIES);
1751
1752 // Now initialize a bunch of stuff that's static....
1753 mainHeader.signature = GPT_SIGNATURE;
1754 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001755 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001756 mainHeader.reserved = 0;
1757 mainHeader.currentLBA = UINT64_C(1);
1758 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1759 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1760 for (i = 0; i < GPT_RESERVED; i++) {
1761 mainHeader.reserved2[i] = '\0';
1762 } // for
srs56948a4ddfc2010-03-21 19:05:49 -04001763 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001764
1765 // Now some semi-static items (computed based on end of disk)
1766 mainHeader.backupLBA = diskSize - UINT64_C(1);
1767 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1768
1769 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001770 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001771
1772 // Copy main header to backup header
1773 RebuildSecondHeader();
1774
1775 // Blank out the partitions array....
1776 BlankPartitions();
1777
1778 // Flag all CRCs as being OK....
1779 mainCrcOk = 1;
1780 secondCrcOk = 1;
1781 mainPartsCrcOk = 1;
1782 secondPartsCrcOk = 1;
1783
1784 return (goOn);
1785} // GPTData::ClearGPTData()
1786
srs5694247657a2009-11-26 18:36:12 -05001787// Set the location of the second GPT header data to the end of the disk.
1788// Used internally and called by the 'e' option on the recovery &
1789// transformation menu, to help users of RAID arrays who add disk space
1790// to their arrays.
1791void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001792 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1793 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1794 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1795} // GPTData::FixSecondHeaderLocation()
1796
srs56940a697312010-01-28 21:10:52 -05001797int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001798 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001799
1800 if (!IsFreePartNum(partNum)) {
1801 partitions[partNum].SetName(theName);
1802 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001803
1804 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001805} // GPTData::SetName
1806
1807// Set the disk GUID to the specified value. Note that the header CRCs must
1808// be recomputed after calling this function.
1809void GPTData::SetDiskGUID(GUIDData newGUID) {
1810 mainHeader.diskGUID = newGUID;
1811 secondHeader.diskGUID = newGUID;
1812} // SetDiskGUID()
1813
1814// Set the unique GUID of the specified partition. Returns 1 on
1815// successful completion, 0 if there were problems (invalid
1816// partition number).
1817int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1818 int retval = 0;
1819
srs56940283dae2010-04-28 16:44:34 -04001820 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001821 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1822 partitions[pn].SetUniqueGUID(theGUID);
1823 retval = 1;
1824 } // if
1825 } // if
1826 return retval;
1827} // GPTData::SetPartitionGUID()
1828
srs56949ba54212010-05-18 23:24:02 -04001829// Set new random GUIDs for the disk and all partitions. Intended to be used
1830// after disk cloning or similar operations that don't randomize the GUIDs.
1831void GPTData::RandomizeGUIDs(void) {
1832 uint32_t i;
1833
1834 mainHeader.diskGUID.Randomize();
1835 secondHeader.diskGUID = mainHeader.diskGUID;
1836 for (i = 0; i < numParts; i++)
1837 if (partitions[i].IsUsed())
1838 partitions[i].RandomizeUniqueGUID();
1839} // GPTData::RandomizeGUIDs()
1840
srs5694ba00fed2010-01-12 18:18:36 -05001841// Change partition type code non-interactively. Returns 1 if
1842// successful, 0 if not....
1843int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1844 int retval = 1;
1845
1846 if (!IsFreePartNum(partNum)) {
1847 partitions[partNum].SetType(hexCode);
1848 } else retval = 0;
1849 return retval;
1850} // GPTData::ChangePartType()
1851
srs56949ba54212010-05-18 23:24:02 -04001852// Recompute the CHS values of all the MBR partitions. Used to reset
1853// CHS values that some BIOSes require, despite the fact that the
1854// resulting CHS values violate the GPT standard.
1855void GPTData::RecomputeCHS(void) {
1856 int i;
1857
1858 for (i = 0; i < 4; i++)
1859 protectiveMBR.RecomputeCHS(i);
1860} // GPTData::RecomputeCHS()
1861
srs56941d1448a2009-12-31 21:20:19 -05001862// Adjust sector number so that it falls on a sector boundary that's a
1863// multiple of sectorAlignment. This is done to improve the performance
1864// of Western Digital Advanced Format disks and disks with similar
1865// technology from other companies, which use 4096-byte sectors
1866// internally although they translate to 512-byte sectors for the
1867// benefit of the OS. If partitions aren't properly aligned on these
1868// disks, some filesystem data structures can span multiple physical
1869// sectors, degrading performance. This function should be called
1870// only on the FIRST sector of the partition, not the last!
1871// This function returns 1 if the alignment was altered, 0 if it
1872// was unchanged.
1873int GPTData::Align(uint64_t* sector) {
1874 int retval = 0, sectorOK = 0;
1875 uint64_t earlier, later, testSector, original;
1876
1877 if ((*sector % sectorAlignment) != 0) {
1878 original = *sector;
1879 retval = 1;
1880 earlier = (*sector / sectorAlignment) * sectorAlignment;
1881 later = earlier + (uint64_t) sectorAlignment;
1882
1883 // Check to see that every sector between the earlier one and the
1884 // requested one is clear, and that it's not too early....
1885 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001886 sectorOK = 1;
1887 testSector = earlier;
1888 do {
1889 sectorOK = IsFree(testSector++);
1890 } while ((sectorOK == 1) && (testSector < *sector));
1891 if (sectorOK == 1) {
1892 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001893 } // if
1894 } // if firstUsableLBA check
1895
1896 // If couldn't move the sector earlier, try to move it later instead....
1897 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1898 sectorOK = 1;
1899 testSector = later;
1900 do {
1901 sectorOK = IsFree(testSector--);
1902 } while ((sectorOK == 1) && (testSector > *sector));
1903 if (sectorOK == 1) {
1904 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001905 } // if
1906 } // if
1907
1908 // If sector was changed successfully, inform the user of this fact.
1909 // Otherwise, notify the user that it couldn't be done....
1910 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001911 cout << "Information: Moved requested sector from " << original << " to "
srs56948a4ddfc2010-03-21 19:05:49 -04001912 << *sector << " in\norder to align on " << sectorAlignment
1913 << "-sector boundaries.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001914 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001915 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001916 } else {
srs5694fed16d02010-01-27 23:03:40 -05001917 cout << "Information: Sector not aligned on " << sectorAlignment
1918 << "-sector boundary and could not be moved.\n"
1919 << "If you're using a Western Digital Advanced Format or similar disk with\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001920 << "underlying 4096-byte sectors or certain types of RAID array, performance\n"
1921 << "may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001922 retval = 0;
1923 } // if/else
1924 } // if
1925 return retval;
1926} // GPTData::Align()
1927
srs5694e4ac11e2009-08-31 10:13:04 -04001928/********************************************************
1929 * *
1930 * Functions that return data about GPT data structures *
1931 * (most of these are inline in gpt.h) *
1932 * *
1933 ********************************************************/
1934
1935// Find the low and high used partition numbers (numbered from 0).
1936// Return value is the number of partitions found. Note that the
1937// *low and *high values are both set to 0 when no partitions
1938// are found, as well as when a single partition in the first
1939// position exists. Thus, the return value is the only way to
1940// tell when no partitions exist.
1941int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1942 uint32_t i;
1943 int numFound = 0;
1944
srs56940283dae2010-04-28 16:44:34 -04001945 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001946 *high = 0;
srs56940283dae2010-04-28 16:44:34 -04001947 if (numParts > 0) { // only try if partition table exists...
1948 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001949 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1950 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001951 // Set the low value only if it's not yet found...
srs56940283dae2010-04-28 16:44:34 -04001952 if (*low == (numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001953 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001954 } // if
1955 } // for
1956 } // if
1957
1958 // Above will leave *low pointing to its "not found" value if no partitions
1959 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001960 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001961 *low = 0;
1962 return numFound;
1963} // GPTData::GetPartRange()
1964
srs569408bb0da2010-02-19 17:19:55 -05001965// Returns the value of the first free partition, or -1 if none is
1966// unused.
1967int GPTData::FindFirstFreePart(void) {
1968 int i = 0;
1969
1970 if (partitions != NULL) {
srs56940283dae2010-04-28 16:44:34 -04001971 while ((partitions[i].IsUsed()) && (i < (int) numParts))
srs569408bb0da2010-02-19 17:19:55 -05001972 i++;
srs56940283dae2010-04-28 16:44:34 -04001973 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001974 i = -1;
1975 } else i = -1;
1976 return i;
1977} // GPTData::FindFirstFreePart()
1978
srs5694978041c2009-09-21 20:51:47 -04001979// Returns the number of defined partitions.
1980uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001981 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001982
srs56940283dae2010-04-28 16:44:34 -04001983 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001984 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001985 counted++;
1986 } // for
1987 return counted;
1988} // GPTData::CountParts()
1989
srs5694e4ac11e2009-08-31 10:13:04 -04001990/****************************************************
1991 * *
1992 * Functions that return data about disk free space *
1993 * *
1994 ****************************************************/
1995
1996// Find the first available block after the starting point; returns 0 if
1997// there are no available blocks left
1998uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1999 uint64_t first;
2000 uint32_t i;
2001 int firstMoved = 0;
2002
2003 // Begin from the specified starting point or from the first usable
2004 // LBA, whichever is greater...
2005 if (start < mainHeader.firstUsableLBA)
2006 first = mainHeader.firstUsableLBA;
2007 else
2008 first = start;
2009
2010 // ...now search through all partitions; if first is within an
2011 // existing partition, move it to the next sector after that
2012 // partition and repeat. If first was moved, set firstMoved
2013 // flag; repeat until firstMoved is not set, so as to catch
2014 // cases where partitions are out of sequential order....
2015 do {
2016 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002017 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002018 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002019 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002020 first = partitions[i].GetLastLBA() + 1;
2021 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002022 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002023 } // for
2024 } while (firstMoved == 1);
2025 if (first > mainHeader.lastUsableLBA)
2026 first = 0;
2027 return (first);
2028} // GPTData::FindFirstAvailable()
2029
2030// Finds the first available sector in the largest block of unallocated
2031// space on the disk. Returns 0 if there are no available blocks left
2032uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002033 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002034
2035 start = 0;
2036 do {
2037 firstBlock = FindFirstAvailable(start);
2038 if (firstBlock != UINT32_C(0)) { // something's free...
2039 lastBlock = FindLastInFree(firstBlock);
2040 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2041 if (segmentSize > selectedSize) {
2042 selectedSize = segmentSize;
2043 selectedSegment = firstBlock;
2044 } // if
2045 start = lastBlock + 1;
2046 } // if
2047 } while (firstBlock != 0);
2048 return selectedSegment;
2049} // GPTData::FindFirstInLargest()
2050
srs5694cb76c672010-02-11 22:22:22 -05002051// Find the last available block on the disk.
2052// Returns 0 if there are no available partitions
2053uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002054 uint64_t last;
2055 uint32_t i;
2056 int lastMoved = 0;
2057
2058 // Start by assuming the last usable LBA is available....
2059 last = mainHeader.lastUsableLBA;
2060
2061 // ...now, similar to algorithm in FindFirstAvailable(), search
2062 // through all partitions, moving last when it's in an existing
2063 // partition. Set the lastMoved flag so we repeat to catch cases
2064 // where partitions are out of logical order.
2065 do {
2066 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002067 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002068 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002069 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002070 last = partitions[i].GetFirstLBA() - 1;
2071 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002072 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002073 } // for
2074 } while (lastMoved == 1);
2075 if (last < mainHeader.firstUsableLBA)
2076 last = 0;
2077 return (last);
2078} // GPTData::FindLastAvailable()
2079
2080// Find the last available block in the free space pointed to by start.
2081uint64_t GPTData::FindLastInFree(uint64_t start) {
2082 uint64_t nearestStart;
2083 uint32_t i;
2084
2085 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002086 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002087 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002088 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002089 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002090 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002091 } // for
2092 return (nearestStart);
2093} // GPTData::FindLastInFree()
2094
2095// Finds the total number of free blocks, the number of segments in which
2096// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002097uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002098 uint64_t start = UINT64_C(0); // starting point for each search
2099 uint64_t totalFound = UINT64_C(0); // running total
2100 uint64_t firstBlock; // first block in a segment
2101 uint64_t lastBlock; // last block in a segment
2102 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002103 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002104
2105 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002106 if (diskSize > 0) {
2107 do {
2108 firstBlock = FindFirstAvailable(start);
2109 if (firstBlock != UINT64_C(0)) { // something's free...
2110 lastBlock = FindLastInFree(firstBlock);
2111 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2112 if (segmentSize > *largestSegment) {
2113 *largestSegment = segmentSize;
2114 } // if
2115 totalFound += segmentSize;
2116 num++;
2117 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002118 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002119 } while (firstBlock != 0);
2120 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002121 *numSegments = num;
2122 return totalFound;
2123} // GPTData::FindFreeBlocks()
2124
srs569455d92612010-03-07 22:16:07 -05002125// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2126// If it's allocated, return the partition number to which it's allocated
2127// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2128// returned in partNum if the sector is in use by basic GPT data structures.)
2129int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002130 int isFree = 1;
2131 uint32_t i;
2132
srs56940283dae2010-04-28 16:44:34 -04002133 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002134 if ((sector >= partitions[i].GetFirstLBA()) &&
2135 (sector <= partitions[i].GetLastLBA())) {
2136 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002137 if (partNum != NULL)
2138 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002139 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002140 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002141 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002142 (sector > mainHeader.lastUsableLBA)) {
2143 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002144 if (partNum != NULL)
2145 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002146 } // if
2147 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002148} // GPTData::IsFree()
2149
srs5694ba00fed2010-01-12 18:18:36 -05002150// Returns 1 if partNum is unused.
2151int GPTData::IsFreePartNum(uint32_t partNum) {
2152 int retval = 1;
2153
srs56940283dae2010-04-28 16:44:34 -04002154 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002155 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002156 retval = 0;
2157 } // if partition is in use
2158 } else retval = 0;
2159
2160 return retval;
2161} // GPTData::IsFreePartNum()
2162
srs5694a8582cf2010-03-19 14:21:59 -04002163
2164/***********************************************************
2165 * *
2166 * Change how functions work or return information on them *
2167 * *
2168 ***********************************************************/
2169
2170// Set partition alignment value; partitions will begin on multiples of
2171// the specified value
2172void GPTData::SetAlignment(uint32_t n) {
srs5694a8582cf2010-03-19 14:21:59 -04002173 sectorAlignment = n;
srs5694a8582cf2010-03-19 14:21:59 -04002174} // GPTData::SetAlignment()
2175
2176// Compute sector alignment based on the current partitions (if any). Each
2177// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56948a4ddfc2010-03-21 19:05:49 -04002178// value less than or equal to the DEFAULT_ALIGNMENT value, but not by the
2179// previously-located alignment value, then the alignment value is adjusted
2180// down. If the computed alignment is less than 8 and the disk is bigger than
2181// SMALLEST_ADVANCED_FORMAT, resets it to 8. This is a safety measure for WD
2182// Advanced Format and similar drives. If no partitions are defined, the
2183// alignment value is set to DEFAULT_ALIGNMENT (2048). The result is that new
2184// drives are aligned to 2048-sector multiples but the program won't complain
2185// about other alignments on existing disks unless a smaller-than-8 alignment
2186// is used on small disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002187// Returns the computed alignment value.
2188uint32_t GPTData::ComputeAlignment(void) {
2189 uint32_t i = 0, found, exponent = 31;
2190 uint64_t align = DEFAULT_ALIGNMENT;
2191
srs56948a4ddfc2010-03-21 19:05:49 -04002192 exponent = (uint32_t) log2(DEFAULT_ALIGNMENT);
srs56940283dae2010-04-28 16:44:34 -04002193 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002194 if (partitions[i].IsUsed()) {
2195 found = 0;
2196 while (!found) {
2197 align = PowerOf2(exponent);
2198 if ((partitions[i].GetFirstLBA() % align) == 0) {
2199 found = 1;
2200 } else {
2201 exponent--;
2202 } // if/else
2203 } // while
2204 } // if
2205 } // for
2206 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2207 align = 8;
srs5694a8582cf2010-03-19 14:21:59 -04002208 SetAlignment(align);
2209 return align;
2210} // GPTData::ComputeAlignment()
2211
srs5694e4ac11e2009-08-31 10:13:04 -04002212/********************************
2213 * *
2214 * Endianness support functions *
2215 * *
2216 ********************************/
2217
srs56942a9f5da2009-08-26 00:48:01 -04002218void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002219 ReverseBytes(&header->signature, 8);
2220 ReverseBytes(&header->revision, 4);
2221 ReverseBytes(&header->headerSize, 4);
2222 ReverseBytes(&header->headerCRC, 4);
2223 ReverseBytes(&header->reserved, 4);
2224 ReverseBytes(&header->currentLBA, 8);
2225 ReverseBytes(&header->backupLBA, 8);
2226 ReverseBytes(&header->firstUsableLBA, 8);
2227 ReverseBytes(&header->lastUsableLBA, 8);
2228 ReverseBytes(&header->partitionEntriesLBA, 8);
2229 ReverseBytes(&header->numParts, 4);
2230 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2231 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002232 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002233} // GPTData::ReverseHeaderBytes()
2234
srs56940283dae2010-04-28 16:44:34 -04002235// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002236void GPTData::ReversePartitionBytes() {
2237 uint32_t i;
2238
srs56940283dae2010-04-28 16:44:34 -04002239 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002240 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002241 } // for
2242} // GPTData::ReversePartitionBytes()
2243
2244/******************************************
2245 * *
2246 * Additional non-class support functions *
2247 * *
2248 ******************************************/
2249
srs5694e7b4ff92009-08-18 13:16:10 -04002250// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2251// never fail these tests, but the struct types may fail depending on compile options.
2252// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2253// sizes.
2254int SizesOK(void) {
2255 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002256
2257 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002258 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002259 allOK = 0;
2260 } // if
2261 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002262 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002263 allOK = 0;
2264 } // if
2265 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002266 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002267 allOK = 0;
2268 } // if
2269 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002270 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002271 allOK = 0;
2272 } // if
2273 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002274 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002275 allOK = 0;
2276 } // if
srs5694978041c2009-09-21 20:51:47 -04002277 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002278 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002279 allOK = 0;
2280 } // if
2281 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002282 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002283 allOK = 0;
2284 } // if
srs5694221e0872009-08-29 15:00:31 -04002285 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002286 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002287 allOK = 0;
2288 } // if
srs56946699b012010-02-04 00:55:30 -05002289 if (sizeof(GUIDData) != 16) {
2290 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2291 allOK = 0;
2292 } // if
2293 if (sizeof(PartType) != 16) {
2294 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2295 allOK = 0;
2296 } // if
srs5694fed16d02010-01-27 23:03:40 -05002297 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002298 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002299 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2300 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002301 } // if
2302 return (allOK);
2303} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002304