blob: 429203553b18ee622258eb09cb32f7a7fe31e398 [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
srs56949ba54212010-05-18 23:24:02 -040033#ifdef __FreeBSD__
34#define log2(x) (log(x) / M_LN2)
35#endif // __FreeBSD__
36
37
srs5694e7b4ff92009-08-18 13:16:10 -040038/****************************************
39 * *
40 * GPTData class and related structures *
41 * *
42 ****************************************/
43
srs5694e4ac11e2009-08-31 10:13:04 -040044// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040045GPTData::GPTData(void) {
46 blockSize = SECTOR_SIZE; // set a default
47 diskSize = 0;
48 partitions = NULL;
49 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050050 device = "";
srs56945d58fe02010-01-03 20:57:08 -050051 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040052 mainCrcOk = 0;
53 secondCrcOk = 0;
54 mainPartsCrcOk = 0;
55 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040056 apmFound = 0;
57 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050058 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050059 beQuiet = 0;
60 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040061 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050062 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040063 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040064 SetGPTSize(NUM_GPT_ENTRIES);
65} // GPTData default constructor
66
67// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050068GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040069 blockSize = SECTOR_SIZE; // set a default
70 diskSize = 0;
71 partitions = NULL;
72 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050073 device = "";
srs56945d58fe02010-01-03 20:57:08 -050074 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040075 mainCrcOk = 0;
76 secondCrcOk = 0;
77 mainPartsCrcOk = 0;
78 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040079 apmFound = 0;
80 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050081 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050082 beQuiet = 0;
83 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040084 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050085 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040086 numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050087 if (!LoadPartitions(filename))
88 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050089} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040090
srs5694e4ac11e2009-08-31 10:13:04 -040091// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040092GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050093 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040094} // GPTData destructor
95
srs5694e4ac11e2009-08-31 10:13:04 -040096/*********************************************************************
97 * *
98 * Begin functions that verify data, or that adjust the verification *
99 * information (compute CRCs, rebuild headers) *
100 * *
101 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400102
srs5694e4ac11e2009-08-31 10:13:04 -0400103// Perform detailed verification, reporting on any problems found, but
104// do *NOT* recover from these problems. Returns the total number of
105// problems identified.
106int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -0500107 int problems = 0;
108 uint32_t i, numSegments;
109 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400110
111 // First, check for CRC errors in the GPT data....
112 if (!mainCrcOk) {
113 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500114 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
115 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
116 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
117 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400118 } // if
119 if (!mainPartsCrcOk) {
120 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500121 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
122 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
123 << "transformation menu). This report may be a false alarm if you've already\n"
124 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400125 } // if
126 if (!secondCrcOk) {
127 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500128 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
129 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
130 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
131 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400132 } // if
133 if (!secondPartsCrcOk) {
134 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500135 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
136 << "be corrupt. This program will automatically create a new backup partition\n"
137 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400138 } // if
139
srs5694978041c2009-09-21 20:51:47 -0400140 // Now check that the main and backup headers both point to themselves....
141 if (mainHeader.currentLBA != 1) {
142 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500143 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
144 << "is being automatically corrected, but it may be a symptom of more serious\n"
145 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400146 mainHeader.currentLBA = 1;
147 } // if
148 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
149 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500150 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
151 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
152 << "option on the experts' menu to adjust the secondary header's and partition\n"
153 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400154 } // if
155
156 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400157 if (mainHeader.currentLBA != secondHeader.backupLBA) {
158 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500159 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
160 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
161 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (mainHeader.backupLBA != secondHeader.currentLBA) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
166 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
167 << secondHeader.currentLBA << ").\n"
168 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400169 } // if
170 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
171 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500172 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
173 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
174 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400175 } // if
176 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
177 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500178 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
179 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
180 << secondHeader.lastUsableLBA << ")\n"
181 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400182 } // if
srs56946699b012010-02-04 00:55:30 -0500183 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400184 problems++;
srs56946699b012010-02-04 00:55:30 -0500185 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500186 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500187 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500188 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
189 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400190 } // if
191 if (mainHeader.numParts != secondHeader.numParts) {
192 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500193 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
194 << ") doesn't\nmatch the backup GPT header's number of partitions ("
195 << secondHeader.numParts << ")\n"
196 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400197 } // if
198 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
199 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500200 cout << "\nProblem: main GPT header's size of partition entries ("
201 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
202 << "match the backup GPT header's size of partition entries ("
203 << secondHeader.sizeOfPartitionEntries << ")\n"
204 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
205 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400206 } // if
207
208 // Now check for a few other miscellaneous problems...
209 // Check that the disk size will hold the data...
210 if (mainHeader.backupLBA > diskSize) {
211 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500212 cout << "\nProblem: Disk is too small to hold all the data!\n"
213 << "(Disk size is " << diskSize << " sectors, needs to be "
214 << mainHeader.backupLBA << " sectors.)\n"
215 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400216 } // if
217
218 // Check for overlapping partitions....
219 problems += FindOverlaps();
220
srs569455d92612010-03-07 22:16:07 -0500221 // Check for insane partitions (start after end, hugely big, etc.)
222 problems += FindInsanePartitions();
223
srs5694e4ac11e2009-08-31 10:13:04 -0400224 // Check for mismatched MBR and GPT partitions...
225 problems += FindHybridMismatches();
226
227 // Verify that partitions don't run into GPT data areas....
228 problems += CheckGPTSize();
229
srs56941d1448a2009-12-31 21:20:19 -0500230 // Check that partitions are aligned on proper boundaries (for WD Advanced
231 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400232 for (i = 0; i < numParts; i++) {
srs56941d1448a2009-12-31 21:20:19 -0500233 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500234 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
235 << sectorAlignment << "-sector boundary. This may\nresult "
236 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500237 } // if
238 } // for
239
srs5694e4ac11e2009-08-31 10:13:04 -0400240 // Now compute available space, but only if no problems found, since
241 // problems could affect the results
242 if (problems == 0) {
243 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500244 cout << "No problems found. " << totalFree << " free sectors ("
245 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
246 << numSegments << "\nsegments, the largest of which is "
247 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
srs56940283dae2010-04-28 16:44:34 -0400248 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400249 } else {
srs56940a697312010-01-28 21:10:52 -0500250 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400251 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400252
253 return (problems);
254} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400255
256// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400257// do, issues a warning but takes no action. Returns number of problems
258// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400259int GPTData::CheckGPTSize(void) {
260 uint64_t overlap, firstUsedBlock, lastUsedBlock;
261 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400262 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400263
264 // first, locate the first & last used blocks
265 firstUsedBlock = UINT64_MAX;
266 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400267 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400268 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400269 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400270 firstUsedBlock = partitions[i].GetFirstLBA();
271 if (partitions[i].GetLastLBA() > lastUsedBlock)
272 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400273 } // for
274
275 // If the disk size is 0 (the default), then it means that various
276 // variables aren't yet set, so the below tests will be useless;
277 // therefore we should skip everything
278 if (diskSize != 0) {
279 if (mainHeader.firstUsableLBA > firstUsedBlock) {
280 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500281 cout << "Warning! Main partition table overlaps the first partition by "
282 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400283 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500284 cout << "Try reducing the partition table size by " << overlap * 4
285 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400286 } else {
srs5694fed16d02010-01-27 23:03:40 -0500287 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400288 } // if/else
289 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400290 } // Problem at start of disk
291 if (mainHeader.lastUsableLBA < lastUsedBlock) {
292 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500293 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500294 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400295 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500296 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400297 } else {
srs5694fed16d02010-01-27 23:03:40 -0500298 cout << "Try reducing the partition table size by " << overlap * 4
299 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400300 } // if/else
301 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400302 } // Problem at end of disk
303 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400304 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400305} // GPTData::CheckGPTSize()
306
srs5694e7b4ff92009-08-18 13:16:10 -0400307// Check the validity of the GPT header. Returns 1 if the main header
308// is valid, 2 if the backup header is valid, 3 if both are valid, and
309// 0 if neither is valid. Note that this function just checks the GPT
310// signature and revision numbers, not CRCs or other data.
311int GPTData::CheckHeaderValidity(void) {
312 int valid = 3;
313
srs5694fed16d02010-01-27 23:03:40 -0500314 cout.setf(ios::uppercase);
315 cout.fill('0');
316
317 // Note: failed GPT signature checks produce no error message because
318 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400319 if (mainHeader.signature != GPT_SIGNATURE) {
320 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400321 } else if ((mainHeader.revision != 0x00010000) && valid) {
322 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500323 cout << "Unsupported GPT version in main header; read 0x";
324 cout.width(8);
325 cout << hex << mainHeader.revision << ", should be\n0x";
326 cout.width(8);
327 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400328 } // if/else/if
329
330 if (secondHeader.signature != GPT_SIGNATURE) {
331 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400332 } else if ((secondHeader.revision != 0x00010000) && valid) {
333 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500334 cout << "Unsupported GPT version in backup header; read 0x";
335 cout.width(8);
336 cout << hex << secondHeader.revision << ", should be\n0x";
337 cout.width(8);
338 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400339 } // if/else/if
340
srs56942a9f5da2009-08-26 00:48:01 -0400341 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400342 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400343 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400344 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400345 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500346 } // if
srs5694fed16d02010-01-27 23:03:40 -0500347 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400348
srs5694fed16d02010-01-27 23:03:40 -0500349 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400350} // GPTData::CheckHeaderValidity()
351
352// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500353// Note: Must be called with header in LITTLE-ENDIAN
354// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400355int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400356 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400357
srs56942a9f5da2009-08-26 00:48:01 -0400358 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400359 // computation to be valid
360 oldCRC = header->headerCRC;
361 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400362 hSize = header->headerSize;
363
364 // If big-endian system, reverse byte order
365 if (IsLittleEndian() == 0) {
366 ReverseBytes(&oldCRC, 4);
367 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400368
369 // Initialize CRC functions...
370 chksum_crc32gentab();
371
372 // Compute CRC, restore original, and return result of comparison
373 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400374 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400375 return (oldCRC == newCRC);
376} // GPTData::CheckHeaderCRC()
377
srs56946699b012010-02-04 00:55:30 -0500378// Recompute all the CRCs. Must be called before saving if any changes have
379// been made. Must be called on platform-ordered data (this function reverses
380// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400381void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400382 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400383 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400384
385 // Initialize CRC functions...
386 chksum_crc32gentab();
387
srs56946699b012010-02-04 00:55:30 -0500388 // Save some key data from header before reversing byte order....
srs5694978041c2009-09-21 20:51:47 -0400389 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500390
391 if ((littleEndian = IsLittleEndian()) == 0) {
392 ReversePartitionBytes();
393 ReverseHeaderBytes(&mainHeader);
394 ReverseHeaderBytes(&secondHeader);
395 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400396
srs5694e7b4ff92009-08-18 13:16:10 -0400397 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400398 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400399 mainHeader.partitionEntriesCRC = crc;
400 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400401 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400402 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
403 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400404 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400405
406 // Zero out GPT tables' own CRCs (required for correct computation)
407 mainHeader.headerCRC = 0;
408 secondHeader.headerCRC = 0;
409
410 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400411 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400412 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400413 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400414 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400415 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400416 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400417 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400418 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500419
420 if ((littleEndian = IsLittleEndian()) == 0) {
421 ReverseHeaderBytes(&mainHeader);
422 ReverseHeaderBytes(&secondHeader);
423 ReversePartitionBytes();
424 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400425} // GPTData::RecomputeCRCs()
426
srs5694e7b4ff92009-08-18 13:16:10 -0400427// Rebuild the main GPT header, using the secondary header as a model.
428// Typically called when the main header has been found to be corrupt.
429void GPTData::RebuildMainHeader(void) {
430 int i;
431
432 mainHeader.signature = GPT_SIGNATURE;
433 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400434 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400435 mainHeader.headerCRC = UINT32_C(0);
436 mainHeader.reserved = secondHeader.reserved;
437 mainHeader.currentLBA = secondHeader.backupLBA;
438 mainHeader.backupLBA = secondHeader.currentLBA;
439 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
440 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500441 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400442 mainHeader.partitionEntriesLBA = UINT64_C(2);
443 mainHeader.numParts = secondHeader.numParts;
444 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
445 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
446 for (i = 0 ; i < GPT_RESERVED; i++)
447 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500448 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400449 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400450} // GPTData::RebuildMainHeader()
451
452// Rebuild the secondary GPT header, using the main header as a model.
453void GPTData::RebuildSecondHeader(void) {
454 int i;
455
456 secondHeader.signature = GPT_SIGNATURE;
457 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400458 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400459 secondHeader.headerCRC = UINT32_C(0);
460 secondHeader.reserved = mainHeader.reserved;
461 secondHeader.currentLBA = mainHeader.backupLBA;
462 secondHeader.backupLBA = mainHeader.currentLBA;
463 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
464 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500465 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400466 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
467 secondHeader.numParts = mainHeader.numParts;
468 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
469 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
470 for (i = 0 ; i < GPT_RESERVED; i++)
471 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500472 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400473 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400474} // GPTData::RebuildSecondHeader()
475
476// Search for hybrid MBR entries that have no corresponding GPT partition.
477// Returns number of such mismatches found
478int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500479 int i, found, numFound = 0;
480 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400481 uint64_t mbrFirst, mbrLast;
482
483 for (i = 0; i < 4; i++) {
484 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
485 j = 0;
486 found = 0;
487 do {
488 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
489 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
490 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
491 (partitions[j].GetLastLBA() == mbrLast))
492 found = 1;
493 j++;
srs56940283dae2010-04-28 16:44:34 -0400494 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400495 if (!found) {
496 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500497 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
498 << i + 1 << ", of type 0x";
499 cout.fill('0');
500 cout.setf(ios::uppercase);
501 cout.width(2);
502 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
503 << "has no corresponding GPT partition! You may continue, but this condition\n"
504 << "might cause data loss in the future!\a\n" << dec;
505 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400506 } // if
507 } // if
508 } // for
509 return numFound;
510} // GPTData::FindHybridMismatches
511
512// Find overlapping partitions and warn user about them. Returns number of
513// overlapping partitions.
514int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500515 int problems = 0;
516 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400517
srs56940283dae2010-04-28 16:44:34 -0400518 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400519 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500520 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400521 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500522 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
523 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
524 << " to " << partitions[i].GetLastLBA() << "\n";
525 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
526 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400527 } // if
528 } // for j...
529 } // for i...
530 return problems;
531} // GPTData::FindOverlaps()
532
srs569455d92612010-03-07 22:16:07 -0500533// Find partitions that are insane -- they start after they end or are too
534// big for the disk. (The latter should duplicate detection of overlaps
535// with GPT backup data structures, but better to err on the side of
536// redundant tests than to miss something....)
537int GPTData::FindInsanePartitions(void) {
538 uint32_t i;
539 int problems = 0;
540
srs56940283dae2010-04-28 16:44:34 -0400541 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500542 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
543 problems++;
srs56940283dae2010-04-28 16:44:34 -0400544 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500545 } // if
546 if (partitions[i].GetLastLBA() >= diskSize) {
547 problems++;
srs56940283dae2010-04-28 16:44:34 -0400548 cout << "\nProblem: partition " << i + 1<< " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500549 } // if
550 } // for
551 return problems;
552} // GPTData::FindInsanePartitions(void)
553
554
srs5694e4ac11e2009-08-31 10:13:04 -0400555/******************************************************************
556 * *
557 * Begin functions that load data from disk or save data to disk. *
558 * *
559 ******************************************************************/
560
561// Scan for partition data. This function loads the MBR data (regular MBR or
562// protective MBR) and loads BSD disklabel data (which is probably invalid).
563// It also looks for APM data, forces a load of GPT data, and summarizes
564// the results.
srs5694546a9c72010-01-26 16:00:26 -0500565void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400566 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400567
568 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500569 protectiveMBR.ReadMBRData(&myDisk);
570 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400571
572 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500573 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500574
575 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500576 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500577 protectiveMBR.ShowState();
578 bsdDisklabel.ShowState();
579 ShowAPMState(); // Show whether there's an Apple Partition Map present
580 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500581 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500582 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400583
584 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500585 cout << "\n*******************************************************************\n"
586 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500587 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500588 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500589 } // if
srs5694fed16d02010-01-27 23:03:40 -0500590 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400591 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400592} // GPTData::PartitionScan()
593
594// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500595int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500596 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500597 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500598 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400599
srs5694546a9c72010-01-26 16:00:26 -0500600 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500601 err = myDisk.OpenForWrite(deviceFilename);
602 if ((err == 0) && (!justLooking)) {
603 cout << "\aNOTE: Write test failed with error number " << errno
604 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
605#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
606 cout << "You may be able to enable writes by exiting this program, typing\n"
607 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
608 << "program.\n";
609#endif
610 cout << "\n";
611 } // if
612 myDisk.Close(); // Close and re-open read-only in case of bugs
613 } else allOK = 0; // if
614
615 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400616 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500617 diskSize = myDisk.DiskSize(&err);
618 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500619 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500620 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400621
srs5694ba00fed2010-01-12 18:18:36 -0500622 whichWasUsed = UseWhichPartitions();
623 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400624 case use_mbr:
625 XFormPartitions();
626 break;
627 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500628 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400629// bsdDisklabel.DisplayBSDData();
630 ClearGPTData();
631 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500632 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400633 break;
634 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500635 mbrState = protectiveMBR.GetValidity();
636 if ((mbrState == invalid) || (mbrState == mbr))
637 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400638 break;
639 case use_new:
640 ClearGPTData();
641 protectiveMBR.MakeProtectiveMBR();
642 break;
srs56943c0af382010-01-15 19:19:18 -0500643 case use_abort:
644 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500645 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500646 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400647 } // switch
648
srs569455d92612010-03-07 22:16:07 -0500649 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500650 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500651 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400652 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400653 } else {
654 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400655 } // if/else
656 return (allOK);
657} // GPTData::LoadPartitions()
658
659// Loads the GPT, as much as possible. Returns 1 if this seems to have
660// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500661int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500662 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400663
srs5694cb76c672010-02-11 22:22:22 -0500664 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400665
srs5694cb76c672010-02-11 22:22:22 -0500666 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
667 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
668 } else {
srs569408bb0da2010-02-19 17:19:55 -0500669 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
670 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500671 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
672 << "secondary header from the last sector of the disk! You should use 'v' to\n"
673 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
674 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500675 } // if/else
676 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400677 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400678
679 // Return valid headers code: 0 = both headers bad; 1 = main header
680 // good, backup bad; 2 = backup header good, main header bad;
681 // 3 = both headers good. Note these codes refer to valid GPT
682 // signatures and version numbers; more subtle problems will elude
683 // this check!
684 validHeaders = CheckHeaderValidity();
685
686 // Read partitions (from primary array)
687 if (validHeaders > 0) { // if at least one header is OK....
688 // GPT appears to be valid....
689 state = gpt_valid;
690
691 // We're calling the GPT valid, but there's a possibility that one
692 // of the two headers is corrupt. If so, use the one that seems to
693 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500694 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500695 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
696 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400697 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500698 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400699 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500700 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500701 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
702 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500703 RebuildMainHeader();
704 state = gpt_corrupt;
705 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400706 } // if/else/if
707
srs5694546a9c72010-01-26 16:00:26 -0500708 // Figure out which partition table to load....
709 // Load the main partition table, since either its header's CRC is OK or the
710 // backup header's CRC is not OK....
711 if (mainCrcOk || !secondCrcOk) {
712 if (LoadMainTable() == 0)
713 allOK = 0;
714 } else { // bad main header CRC and backup header CRC is OK
715 state = gpt_corrupt;
716 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500717 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500718 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500719 } else { // backup table bad, bad main header CRC, but try main table in desperation....
720 if (LoadMainTable() == 0) {
721 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500722 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500723 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500724 } // if
725 } // if/else (LoadSecondTableAsMain())
726 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400727
srs5694cb76c672010-02-11 22:22:22 -0500728 if (loadedTable == 1)
729 secondPartsCrcOk = CheckTable(&secondHeader);
730 else if (loadedTable == 2)
731 mainPartsCrcOk = CheckTable(&mainHeader);
732 else
733 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400734
srs5694546a9c72010-01-26 16:00:26 -0500735 // Problem with main partition table; if backup is OK, use it instead....
736 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
737 state = gpt_corrupt;
738 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500739 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500740 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
741 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500742 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500743
srs5694e4ac11e2009-08-31 10:13:04 -0400744 // Check for valid CRCs and warn if there are problems
745 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
746 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500747 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400748 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500749 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400750 } else {
751 state = gpt_invalid;
752 } // if/else
753 return allOK;
754} // GPTData::ForceLoadGPTData()
755
srs5694247657a2009-11-26 18:36:12 -0500756// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400757// main GPT header in memory MUST be valid for this call to do anything
758// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500759// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400760int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500761 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400762} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400763
764// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500765// table. Used in repair functions, and when starting up if the main
766// partition table is damaged.
767// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
768int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500769 return LoadPartitionTable(secondHeader, myDisk);
770} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400771
srs5694cb76c672010-02-11 22:22:22 -0500772// Load a single GPT header (main or backup) from the specified disk device and
773// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
774// value appropriately.
775// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
776// failure.
777int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
778 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500779 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500780
781 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500782 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500783 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
784 allOK = 0;
785 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500786 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500787
srs56941c6f8b02010-02-21 11:09:20 -0500788 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500789 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500790 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500791 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500792
srs56940283dae2010-04-28 16:44:34 -0400793 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500794 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500795 }
srs56941c6f8b02010-02-21 11:09:20 -0500796
797 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500798 return allOK;
799} // GPTData::LoadHeader
800
801// Load a partition table (either main or secondary) from the specified disk,
802// using header as a reference for what to load. If sector != 0 (the default
803// is 0), loads from the specified sector; otherwise loads from the sector
804// indicated in header.
805// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
806int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
807 uint32_t sizeOfParts, newCRC;
808 int retval;
809
810 if (disk.OpenForRead()) {
811 if (sector == 0) {
812 retval = disk.Seek(header.partitionEntriesLBA);
813 } else {
814 retval = disk.Seek(sector);
815 } // if/else
srs569455d92612010-03-07 22:16:07 -0500816 if (retval == 1)
817 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500818 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500819 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
820 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500821 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500822 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500823 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400824 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500825 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400826 if (IsLittleEndian() == 0)
827 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500828 if (!mainPartsCrcOk) {
829 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400830 } // if
831 } else {
srs5694cb76c672010-02-11 22:22:22 -0500832 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400833 } // if/else
834 } else {
srs5694fed16d02010-01-27 23:03:40 -0500835 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500836 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500837 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400838 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500839 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500840} // GPTData::LoadPartitionsTable()
841
842// Check the partition table pointed to by header, but don't keep it
843// around.
844// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
845int GPTData::CheckTable(struct GPTHeader *header) {
846 uint32_t sizeOfParts, newCRC;
847 uint8_t *storage;
848 int newCrcOk = 0;
849
srs56940283dae2010-04-28 16:44:34 -0400850 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500851 // its CRC and store the results, then discard this temporary
852 // storage, since we don't use it in any but recovery operations
853 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400854 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500855 storage = new uint8_t[sizeOfParts];
856 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400857 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500858 } else {
859 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
860 newCrcOk = (newCRC == header->partitionEntriesCRC);
861 } // if/else
862 delete[] storage;
863 } // if
864 return newCrcOk;
865} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400866
srs5694e7b4ff92009-08-18 13:16:10 -0400867// Writes GPT (and protective MBR) to disk. Returns 1 on successful
868// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500869int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500870 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500871 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400872
srs56946699b012010-02-04 00:55:30 -0500873 littleEndian = IsLittleEndian();
874
srs5694fed16d02010-01-27 23:03:40 -0500875 if (device == "") {
876 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400877 } // if
878
879 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500880
881 // This test should only fail on read-only disks....
882 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500883 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500884 allOK = 0;
885 } // if
886
srs5694e7b4ff92009-08-18 13:16:10 -0400887 // Is there enough space to hold the GPT headers and partition tables,
888 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400889 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400890 allOK = 0;
891 } // if
892
893 // Check that disk is really big enough to handle this...
894 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500895 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
896 << "problem (or it might not). Aborting!\n(Disk size is "
897 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400898 allOK = 0;
899 } // if
srs5694247657a2009-11-26 18:36:12 -0500900 // Check that second header is properly placed. Warn and ask if this should
901 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500902 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500903 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
904 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500905 if (GetYN() == 'Y') {
906 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500907 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500908 } else {
srs5694fed16d02010-01-27 23:03:40 -0500909 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500910 } // if correction requested
911 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400912
srs569455d92612010-03-07 22:16:07 -0500913 // Check for overlapping or insane partitions....
914 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400915 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500916 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400917 } // if
918
919 // Check for mismatched MBR and GPT data, but let it pass if found
920 // (function displays warning message)
921 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400922
923 RecomputeCRCs();
924
srs5694ba00fed2010-01-12 18:18:36 -0500925 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500926 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
927 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500928 answer = GetYN();
929 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500930 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400931 } else {
932 allOK = 0;
933 } // if/else
934 } // if
935
936 // Do it!
937 if (allOK) {
srs56948a4ddfc2010-03-21 19:05:49 -0400938 if (myDisk.OpenForWrite(device)) {
939 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -0500940 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
941 if (!allOK)
942 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
943 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400944
945 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -0400946 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
947
948 // Now write the main partition tables...
949 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
950
951 // Now write the main GPT header...
952 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
953
954 // To top it off, write the protective MBR...
955 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400956
957 // re-read the partition table
958 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500959 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400960 } // if
961
962 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500963 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400964 } else {
srs5694fed16d02010-01-27 23:03:40 -0500965 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -0400966 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400967 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -0400968
srs5694546a9c72010-01-26 16:00:26 -0500969 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400970 } else {
srs5694fed16d02010-01-27 23:03:40 -0500971 cerr << "Unable to open device " << device << " for writing! Errno is "
972 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400973 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400974 } // if/else
975 } else {
srs5694fed16d02010-01-27 23:03:40 -0500976 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400977 } // if
978
979 return (allOK);
980} // GPTData::SaveGPTData()
981
982// Save GPT data to a backup file. This function does much less error
983// checking than SaveGPTData(). It can therefore preserve many types of
984// corruption for later analysis; however, it preserves only the MBR,
985// the main GPT header, the backup GPT header, and the main partition
986// table; it discards the backup partition table, since it should be
987// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500988int GPTData::SaveGPTBackup(const string & filename) {
989 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500990 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400991
srs5694546a9c72010-01-26 16:00:26 -0500992 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500993 // Recomputing the CRCs is likely to alter them, which could be bad
994 // if the intent is to save a potentially bad GPT for later analysis;
995 // but if we don't do this, we get bogus errors when we load the
996 // backup. I'm favoring misses over false alarms....
997 RecomputeCRCs();
998
srs5694546a9c72010-01-26 16:00:26 -0500999 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001000
srs5694cb76c672010-02-11 22:22:22 -05001001 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001002 // MBR write closed disk, so re-open and seek to end....
1003 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001004 allOK = SaveHeader(&mainHeader, backupFile, 1);
1005 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001006
srs5694e7b4ff92009-08-18 13:16:10 -04001007 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001008 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001009
srs5694cb76c672010-02-11 22:22:22 -05001010 if (allOK)
1011 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001012
1013 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001014 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001015 } else {
srs5694fed16d02010-01-27 23:03:40 -05001016 cerr << "Warning! An error was reported when writing the backup file.\n"
1017 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001018 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001019 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001020 } else {
srs5694fed16d02010-01-27 23:03:40 -05001021 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001022 allOK = 0;
1023 } // if/else
1024 return allOK;
1025} // GPTData::SaveGPTBackup()
1026
srs5694cb76c672010-02-11 22:22:22 -05001027// Write a GPT header (main or backup) to the specified sector. Used by both
1028// the SaveGPTData() and SaveGPTBackup() functions.
1029// Should be passed an architecture-appropriate header (DO NOT call
1030// ReverseHeaderBytes() on the header before calling this function)
1031// Returns 1 on success, 0 on failure
1032int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1033 int littleEndian, allOK = 1;
1034
1035 littleEndian = IsLittleEndian();
1036 if (!littleEndian)
1037 ReverseHeaderBytes(header);
1038 if (disk.Seek(sector)) {
1039 if (disk.Write(header, 512) == -1)
1040 allOK = 0;
1041 } else allOK = 0; // if (disk.Seek()...)
1042 if (!littleEndian)
1043 ReverseHeaderBytes(header);
1044 return allOK;
1045} // GPTData::SaveHeader()
1046
1047// Save the partitions to the specified sector. Used by both the SaveGPTData()
1048// and SaveGPTBackup() functions.
1049// Should be passed an architecture-appropriate header (DO NOT call
1050// ReverseHeaderBytes() on the header before calling this function)
1051// Returns 1 on success, 0 on failure
1052int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1053 int littleEndian, allOK = 1;
1054
1055 littleEndian = IsLittleEndian();
1056 if (disk.Seek(sector)) {
1057 if (!littleEndian)
1058 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001059 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001060 allOK = 0;
1061 if (!littleEndian)
1062 ReversePartitionBytes();
1063 } else allOK = 0; // if (myDisk.Seek()...)
1064 return allOK;
1065} // GPTData::SavePartitionTable()
1066
srs5694e7b4ff92009-08-18 13:16:10 -04001067// Load GPT data from a backup file created by SaveGPTBackup(). This function
1068// does minimal error checking. It returns 1 if it completed successfully,
1069// 0 if there was a problem. In the latter case, it creates a new empty
1070// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001071int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001072 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001073 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001074 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001075 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001076
srs5694546a9c72010-01-26 16:00:26 -05001077 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001078 if (IsLittleEndian() == 0)
1079 littleEndian = 0;
1080
srs5694e7b4ff92009-08-18 13:16:10 -04001081 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001082 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001083
srs5694cb76c672010-02-11 22:22:22 -05001084 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001085
srs5694cb76c672010-02-11 22:22:22 -05001086 // Check backup file size and rebuild second header if file is right
1087 // size to be direct dd copy of MBR, main header, and main partition
1088 // table; if other size, treat it like a GPT fdisk-generated backup
1089 // file
1090 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1091 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1092 if (shortBackup) {
1093 RebuildSecondHeader();
1094 secondCrcOk = mainCrcOk;
1095 } else {
1096 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1097 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001098
srs5694e7b4ff92009-08-18 13:16:10 -04001099 // Return valid headers code: 0 = both headers bad; 1 = main header
1100 // good, backup bad; 2 = backup header good, main header bad;
1101 // 3 = both headers good. Note these codes refer to valid GPT
1102 // signatures and version numbers; more subtle problems will elude
1103 // this check!
1104 if ((val = CheckHeaderValidity()) > 0) {
1105 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001106 SetGPTSize(secondHeader.numParts);
1107// numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001108 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001109 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001110 SetGPTSize(mainHeader.numParts);
1111// numParts = mainHeader.numParts;
srs5694e7b4ff92009-08-18 13:16:10 -04001112 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1113 } // if/else
1114
srs56940283dae2010-04-28 16:44:34 -04001115// SetGPTSize(numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001116
srs5694e7b4ff92009-08-18 13:16:10 -04001117 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001118 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1119 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001120 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001121 } // if
1122
srs5694cb76c672010-02-11 22:22:22 -05001123 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1124 cerr << "Warning! Read error " << errno
1125 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001126 } else {
1127 allOK = 0;
1128 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001129 // Something went badly wrong, so blank out partitions
1130 if (allOK == 0) {
1131 cerr << "Improper backup file! Clearing all partition data!\n";
1132 ClearGPTData();
1133 protectiveMBR.MakeProtectiveMBR();
1134 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001135 } else {
1136 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001137 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001138 } // if/else
1139
srs5694e7b4ff92009-08-18 13:16:10 -04001140 return allOK;
1141} // GPTData::LoadGPTBackup()
1142
srs569408bb0da2010-02-19 17:19:55 -05001143int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001144 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001145} // GPTData::SaveMBR()
1146
1147// This function destroys the on-disk GPT structures, but NOT the on-disk
1148// MBR.
1149// Returns 1 if the operation succeeds, 0 if not.
1150int GPTData::DestroyGPT(void) {
1151 int i, sum, tableSize, allOK = 1;
1152 uint8_t blankSector[512];
1153 uint8_t* emptyTable;
1154
1155 for (i = 0; i < 512; i++) {
1156 blankSector[i] = 0;
1157 } // for
1158
1159 if (myDisk.OpenForWrite()) {
1160 if (!myDisk.Seek(mainHeader.currentLBA))
1161 allOK = 0;
1162 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1163 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1164 allOK = 0;
1165 } // if
1166 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1167 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001168 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001169 emptyTable = new uint8_t[tableSize];
1170 for (i = 0; i < tableSize; i++)
1171 emptyTable[i] = 0;
1172 if (allOK) {
1173 sum = myDisk.Write(emptyTable, tableSize);
1174 if (sum != tableSize) {
1175 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1176 allOK = 0;
1177 } // if write failed
1178 } // if
1179 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1180 allOK = 0;
1181 if (allOK) {
1182 sum = myDisk.Write(emptyTable, tableSize);
1183 if (sum != tableSize) {
1184 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1185 << errno << "\n";
1186 allOK = 0;
1187 } // if wrong size written
1188 } // if
1189 if (!myDisk.Seek(secondHeader.currentLBA))
1190 allOK = 0;
1191 if (allOK) {
1192 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1193 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1194 allOK = 0;
1195 } // if
1196 } // if
1197 myDisk.DiskSync();
1198 myDisk.Close();
1199 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1200 << "other utilities.\n";
1201 delete[] emptyTable;
1202 } else {
1203 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1204 } // if/else (fd != -1)
1205 return (allOK);
1206} // GPTDataTextUI::DestroyGPT()
1207
1208// Wipe MBR data from the disk (zero it out completely)
1209// Returns 1 on success, 0 on failure.
1210int GPTData::DestroyMBR(void) {
1211 int allOK = 1, i;
1212 uint8_t blankSector[512];
1213
1214 for (i = 0; i < 512; i++)
1215 blankSector[i] = 0;
1216
1217 if (myDisk.OpenForWrite()) {
1218 if (myDisk.Seek(0)) {
1219 if (myDisk.Write(blankSector, 512) != 512)
1220 allOK = 0;
1221 } else allOK = 0;
1222 } else allOK = 0;
1223 if (!allOK)
1224 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1225 return allOK;
1226} // GPTData::DestroyMBR(void)
1227
srs5694e4ac11e2009-08-31 10:13:04 -04001228// Tell user whether Apple Partition Map (APM) was discovered....
1229void GPTData::ShowAPMState(void) {
1230 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001231 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001232 else
srs5694fed16d02010-01-27 23:03:40 -05001233 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001234} // GPTData::ShowAPMState()
1235
1236// Tell user about the state of the GPT data....
1237void GPTData::ShowGPTState(void) {
1238 switch (state) {
1239 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001240 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001241 break;
1242 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001243 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001244 break;
1245 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001246 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001247 break;
1248 default:
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001250 break;
1251 } // switch
1252} // GPTData::ShowGPTState()
1253
1254// Display the basic GPT data
1255void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001256 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001257 uint64_t temp, totalFree;
1258
srs5694fed16d02010-01-27 23:03:40 -05001259 cout << "Disk " << device << ": " << diskSize << " sectors, "
1260 << BytesToSI(diskSize * blockSize) << "\n";
1261 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001262 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs56940283dae2010-04-28 16:44:34 -04001263 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001264 cout << "First usable sector is " << mainHeader.firstUsableLBA
1265 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001266 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001267 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001268 cout << "Total free space is " << totalFree << " sectors ("
1269 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1270 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001271 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001272 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001273 } // for
1274} // GPTData::DisplayGPTData()
1275
srs5694e4ac11e2009-08-31 10:13:04 -04001276// Show detailed information on the specified partition
1277void GPTData::ShowPartDetails(uint32_t partNum) {
1278 if (partitions[partNum].GetFirstLBA() != 0) {
1279 partitions[partNum].ShowDetails(blockSize);
1280 } else {
srs5694fed16d02010-01-27 23:03:40 -05001281 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001282 } // if
1283} // GPTData::ShowPartDetails()
1284
srs5694e4ac11e2009-08-31 10:13:04 -04001285/**************************************************************************
1286 * *
1287 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1288 * (some of these functions may require user interaction) *
1289 * *
1290 **************************************************************************/
1291
srs569408bb0da2010-02-19 17:19:55 -05001292// Examines the MBR & GPT data to determine which set of data to use: the
1293// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1294// a new set of partitions (use_new). A return value of use_abort indicates
1295// that this function couldn't determine what to do. Overriding functions
1296// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001297WhichToUse GPTData::UseWhichPartitions(void) {
1298 WhichToUse which = use_new;
1299 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001300
1301 mbrState = protectiveMBR.GetValidity();
1302
1303 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001304 cout << "\n***************************************************************\n"
1305 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001306 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001307 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001308 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001309 } // if
srs5694fed16d02010-01-27 23:03:40 -05001310 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001311 which = use_mbr;
1312 } // if
1313
1314 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001315 cout << "\n**********************************************************************\n"
1316 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1317 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001318 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001319 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001320 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1321 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001322 } // if
srs5694fed16d02010-01-27 23:03:40 -05001323 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001324 which = use_bsd;
1325 } // if
1326
1327 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001328 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001329 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001330 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001331 } // if
1332 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001333 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001334 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001335 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001336 } // if
1337 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001338 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001339 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001340 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001341 } // if
1342 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001343 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001344 } // if
1345
srs5694e4ac11e2009-08-31 10:13:04 -04001346 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001347 if (mbrState == gpt) {
1348 cout << "\a\a****************************************************************************\n"
1349 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1350 << "verification and recovery are STRONGLY recommended.\n"
1351 << "****************************************************************************\n";
1352 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001353 } else {
srs569408bb0da2010-02-19 17:19:55 -05001354 which = use_abort;
1355 } // if/else MBR says disk is GPT
1356 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001357
1358 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001359 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001360
1361 return which;
1362} // UseWhichPartitions()
1363
srs569408bb0da2010-02-19 17:19:55 -05001364// Convert MBR partition table into GPT form.
1365void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001366 int i, numToConvert;
1367 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001368
1369 // Clear out old data & prepare basics....
1370 ClearGPTData();
1371
1372 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001373 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001374 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001375 else
srs56940283dae2010-04-28 16:44:34 -04001376 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001377
1378 for (i = 0; i < numToConvert; i++) {
1379 origType = protectiveMBR.GetType(i);
1380 // don't waste CPU time trying to convert extended, hybrid protective, or
1381 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001382 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001383 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001384 partitions[i] = protectiveMBR.AsGPT(i);
1385 } // for
1386
1387 // Convert MBR into protective MBR
1388 protectiveMBR.MakeProtectiveMBR();
1389
1390 // Record that all original CRCs were OK so as not to raise flags
1391 // when doing a disk verification
1392 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001393} // GPTData::XFormPartitions()
1394
1395// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001396// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001397// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001398int GPTData::XFormDisklabel(uint32_t partNum) {
1399 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001400 int goOn = 1, numDone = 0;
1401 BSDData disklabel;
1402
srs569408bb0da2010-02-19 17:19:55 -05001403 if (GetPartRange(&low, &high) == 0) {
1404 goOn = 0;
1405 cout << "No partitions!\n";
1406 } // if
1407 if (partNum > high) {
1408 goOn = 0;
1409 cout << "Specified partition is invalid!\n";
1410 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001411
srs569408bb0da2010-02-19 17:19:55 -05001412 // If all is OK, read the disklabel and convert it.
1413 if (goOn) {
1414 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1415 partitions[partNum].GetLastLBA());
1416 if ((goOn) && (disklabel.IsDisklabel())) {
1417 numDone = XFormDisklabel(&disklabel);
1418 if (numDone == 1)
1419 cout << "Converted 1 BSD partition.\n";
1420 else
1421 cout << "Converted " << numDone << " BSD partitions.\n";
1422 } else {
1423 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1424 } // if/else
1425 } // if
1426 if (numDone > 0) { // converted partitions; delete carrier
1427 partitions[partNum].BlankPartition();
1428 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001429 return numDone;
srs569455d92612010-03-07 22:16:07 -05001430} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001431
1432// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001433int GPTData::XFormDisklabel(BSDData* disklabel) {
1434 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001435
srs569408bb0da2010-02-19 17:19:55 -05001436 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001437 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001438 partNum = FindFirstFreePart();
1439 if (partNum >= 0) {
1440 partitions[partNum] = disklabel->AsGPT(i);
1441 if (partitions[partNum].IsUsed())
1442 numDone++;
1443 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001444 } // for
srs569408bb0da2010-02-19 17:19:55 -05001445 if (partNum == -1)
1446 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001447 } // if
1448
1449 // Record that all original CRCs were OK so as not to raise flags
1450 // when doing a disk verification
1451 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1452
1453 return numDone;
1454} // GPTData::XFormDisklabel(BSDData* disklabel)
1455
srs569408bb0da2010-02-19 17:19:55 -05001456// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1457// partition has the active/bootable flag UNset and uses the GPT fdisk
1458// type code divided by 0x0100 as the MBR type code.
1459// Returns 1 if operation was 100% successful, 0 if there were ANY
1460// problems.
srs5694978041c2009-09-21 20:51:47 -04001461int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001462 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001463
srs5694978041c2009-09-21 20:51:47 -04001464 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001465 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001466 allOK = 0;
1467 } // if
srs56940283dae2010-04-28 16:44:34 -04001468 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001469 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001470 allOK = 0;
1471 } // if
1472 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001473 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001474 allOK = 0;
1475 } // if
1476 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1477 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1478 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001479 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1480 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001481 } // if
srs5694978041c2009-09-21 20:51:47 -04001482 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001483 (uint32_t) partitions[gptPart].GetLengthLBA(),
1484 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001485 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001486 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1487 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1488 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001489 allOK = 0;
1490 } // if/else
1491 return allOK;
1492} // GPTData::OnePartToMBR()
1493
srs569455d92612010-03-07 22:16:07 -05001494// Convert partitions to MBR form (primary and logical) and return
1495// the number done. Partitions are specified in a PartNotes variable,
1496// which includes pointers to GPT partition numbers. A partition number
1497// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1498// location in the table, and MBR_EMPTY means not to create a partition
1499// in that table position. If the partition type entry for a partition
1500// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001501// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001502// protective partitions or extended partitions.
1503int GPTData::PartsToMBR(PartNotes & notes) {
1504 int mbrNum = 0, numConverted = 0;
1505 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001506
srs569455d92612010-03-07 22:16:07 -05001507 protectiveMBR.EmptyMBR();
1508 protectiveMBR.SetDiskSize(diskSize);
1509 notes.Rewind();
1510 while (notes.GetNextInfo(&convInfo) >= 0) {
1511 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1512 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1513 if (convInfo.hexCode != 0)
1514 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1515 if (convInfo.active)
1516 protectiveMBR.SetPartBootable(mbrNum);
1517 mbrNum++;
1518 } // if
1519 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1520 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1521 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1522 protectiveMBR.SetHybrid();
1523 } else {
1524 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1525 } // if/else
1526 mbrNum++;
1527 } // if EFI GPT partition specified
1528 } // for
1529 // Now do logical partition(s)...
1530 protectiveMBR.SetDisk(&myDisk);
1531 numConverted += protectiveMBR.CreateLogicals(notes);
1532// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001533 return numConverted;
1534} // GPTData::PartsToMBR()
1535
srs5694e4ac11e2009-08-31 10:13:04 -04001536
1537/**********************************************************************
1538 * *
1539 * Functions that adjust GPT data structures WITHOUT user interaction *
1540 * (they may display information for the user's benefit, though) *
1541 * *
1542 **********************************************************************/
1543
1544// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001545// necessary, copies data if it already exists. Returns 1 if all goes
1546// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001547int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001548 GPTPart* newParts;
1549 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001550 uint32_t i, high, copyNum;
1551 int allOK = 1;
1552
1553 // First, adjust numEntries upward, if necessary, to get a number
1554 // that fills the allocated sectors
1555 i = blockSize / GPT_SIZE;
1556 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001557 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001558 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001559 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001560 } // if
1561
srs5694247657a2009-11-26 18:36:12 -05001562 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001563 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001564 // partition table, which causes problems when loading data from a RAID
1565 // array that's been expanded because this function is called when loading
1566 // data.
srs56940283dae2010-04-28 16:44:34 -04001567 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001568 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001569 if (newParts != NULL) {
1570 if (partitions != NULL) { // existing partitions; copy them over
1571 GetPartRange(&i, &high);
1572 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001573 cout << "The highest-numbered partition is " << high + 1
1574 << ", which is greater than the requested\n"
1575 << "partition table size of " << numEntries
1576 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001577 allOK = 0;
1578 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001579 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001580 copyNum = numEntries;
1581 else
srs56940283dae2010-04-28 16:44:34 -04001582 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001583 for (i = 0; i < copyNum; i++) {
1584 newParts[i] = partitions[i];
1585 } // for
1586 trash = partitions;
1587 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001588 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001589 } // if
1590 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001591 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001592 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001593 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001594 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1595 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1596 MoveSecondHeaderToEnd();
1597 if (diskSize > 0)
1598 CheckGPTSize();
1599 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001600 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001601 allOK = 0;
1602 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001603 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001604 mainHeader.numParts = numParts;
1605 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001606 return (allOK);
1607} // GPTData::SetGPTSize()
1608
1609// Blank the partition array
1610void GPTData::BlankPartitions(void) {
1611 uint32_t i;
1612
srs56940283dae2010-04-28 16:44:34 -04001613 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001614 partitions[i].BlankPartition();
1615 } // for
1616} // GPTData::BlankPartitions()
1617
srs5694ba00fed2010-01-12 18:18:36 -05001618// Delete a partition by number. Returns 1 if successful,
1619// 0 if there was a problem. Returns 1 if partition was in
1620// range, 0 if it was out of range.
1621int GPTData::DeletePartition(uint32_t partNum) {
1622 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001623 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001624
srs56940283dae2010-04-28 16:44:34 -04001625 numUsedParts = GetPartRange(&low, &high);
1626 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001627 // In case there's a protective MBR, look for & delete matching
1628 // MBR partition....
1629 startSector = partitions[partNum].GetFirstLBA();
1630 length = partitions[partNum].GetLengthLBA();
1631 protectiveMBR.DeleteByLocation(startSector, length);
1632
1633 // Now delete the GPT partition
1634 partitions[partNum].BlankPartition();
1635 } else {
srs5694fed16d02010-01-27 23:03:40 -05001636 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001637 retval = 0;
1638 } // if/else
1639 return retval;
1640} // GPTData::DeletePartition(uint32_t partNum)
1641
srs569408bb0da2010-02-19 17:19:55 -05001642// Non-interactively create a partition.
1643// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001644uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001645 int retval = 1; // assume there'll be no problems
1646
1647 if (IsFreePartNum(partNum)) {
1648 Align(&startSector); // Align sector to correct multiple
1649 if (IsFree(startSector) && (startSector <= endSector)) {
1650 if (FindLastInFree(startSector) >= endSector) {
1651 partitions[partNum].SetFirstLBA(startSector);
1652 partitions[partNum].SetLastLBA(endSector);
1653 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001654 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001655 } else retval = 0; // if free space until endSector
1656 } else retval = 0; // if startSector is free
1657 } else retval = 0; // if legal partition number
1658 return retval;
1659} // GPTData::CreatePartition(partNum, startSector, endSector)
1660
srs5694e4ac11e2009-08-31 10:13:04 -04001661// Sort the GPT entries, eliminating gaps and making for a logical
1662// ordering. Relies on QuickSortGPT() for the bulk of the work
1663void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001664 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001665
1666 // First, find the last partition with data, so as not to
1667 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001668 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001669
1670 // Now swap empties with the last partitions, to simplify the logic
1671 // in the Quicksort function....
1672 i = 0;
1673 while (i < lastPart) {
1674 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001675 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001676 do {
1677 lastPart--;
1678 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001679 } // if
1680 i++;
1681 } // while
1682
srs5694546a9c72010-01-26 16:00:26 -05001683 // If there are more empties than partitions in the range from 0 to lastPart,
1684 // the above leaves lastPart set too high, so we've got to adjust it to
1685 // prevent empties from migrating to the top of the list....
1686 GetPartRange(&firstPart, &lastPart);
1687
srs5694e4ac11e2009-08-31 10:13:04 -04001688 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001689 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001690} // GPTData::SortGPT()
1691
srs569408bb0da2010-02-19 17:19:55 -05001692// Recursive quick sort algorithm for GPT partitions. Note that if there
1693// are any empties in the specified range, they'll be sorted to the
1694// start, resulting in a sorted set of partitions that begins with
1695// partition 2, 3, or higher.
1696void GPTData::QuickSortGPT(int start, int finish) {
1697 uint64_t starterValue; // starting location of median partition
1698 int left, right;
1699
1700 left = start;
1701 right = finish;
1702 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1703 do {
1704 while (partitions[left].GetFirstLBA() < starterValue)
1705 left++;
1706 while (partitions[right].GetFirstLBA() > starterValue)
1707 right--;
1708 if (left <= right)
1709 SwapPartitions(left++, right--);
1710 } while (left <= right);
1711 if (start < right) QuickSortGPT(start, right);
1712 if (finish > left) QuickSortGPT(left, finish);
1713} // GPTData::QuickSortGPT()
1714
1715// Swap the contents of two partitions.
1716// Returns 1 if successful, 0 if either partition is out of range
1717// (that is, not a legal number; either or both can be empty).
1718// Note that if partNum1 = partNum2 and this number is in range,
1719// it will be considered successful.
1720int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1721 GPTPart temp;
1722 int allOK = 1;
1723
srs56940283dae2010-04-28 16:44:34 -04001724 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001725 if (partNum1 != partNum2) {
1726 temp = partitions[partNum1];
1727 partitions[partNum1] = partitions[partNum2];
1728 partitions[partNum2] = temp;
1729 } // if
1730 } else allOK = 0; // partition numbers are valid
1731 return allOK;
1732} // GPTData::SwapPartitions()
1733
srs5694e4ac11e2009-08-31 10:13:04 -04001734// Set up data structures for entirely new set of partitions on the
1735// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001736// Note that this function does NOT clear the protectiveMBR data
1737// structure, since it may hold the original MBR partitions if the
1738// program was launched on an MBR disk, and those may need to be
1739// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001740int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001741 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001742
1743 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001744 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001745 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001746 partitions = NULL;
1747 SetGPTSize(NUM_GPT_ENTRIES);
1748
1749 // Now initialize a bunch of stuff that's static....
1750 mainHeader.signature = GPT_SIGNATURE;
1751 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001752 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001753 mainHeader.reserved = 0;
1754 mainHeader.currentLBA = UINT64_C(1);
1755 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1756 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1757 for (i = 0; i < GPT_RESERVED; i++) {
1758 mainHeader.reserved2[i] = '\0';
1759 } // for
srs56948a4ddfc2010-03-21 19:05:49 -04001760 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001761
1762 // Now some semi-static items (computed based on end of disk)
1763 mainHeader.backupLBA = diskSize - UINT64_C(1);
1764 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1765
1766 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001767 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001768
1769 // Copy main header to backup header
1770 RebuildSecondHeader();
1771
1772 // Blank out the partitions array....
1773 BlankPartitions();
1774
1775 // Flag all CRCs as being OK....
1776 mainCrcOk = 1;
1777 secondCrcOk = 1;
1778 mainPartsCrcOk = 1;
1779 secondPartsCrcOk = 1;
1780
1781 return (goOn);
1782} // GPTData::ClearGPTData()
1783
srs5694247657a2009-11-26 18:36:12 -05001784// Set the location of the second GPT header data to the end of the disk.
1785// Used internally and called by the 'e' option on the recovery &
1786// transformation menu, to help users of RAID arrays who add disk space
1787// to their arrays.
1788void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001789 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1790 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1791 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1792} // GPTData::FixSecondHeaderLocation()
1793
srs56940a697312010-01-28 21:10:52 -05001794int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001795 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001796
1797 if (!IsFreePartNum(partNum)) {
1798 partitions[partNum].SetName(theName);
1799 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001800
1801 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001802} // GPTData::SetName
1803
1804// Set the disk GUID to the specified value. Note that the header CRCs must
1805// be recomputed after calling this function.
1806void GPTData::SetDiskGUID(GUIDData newGUID) {
1807 mainHeader.diskGUID = newGUID;
1808 secondHeader.diskGUID = newGUID;
1809} // SetDiskGUID()
1810
1811// Set the unique GUID of the specified partition. Returns 1 on
1812// successful completion, 0 if there were problems (invalid
1813// partition number).
1814int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1815 int retval = 0;
1816
srs56940283dae2010-04-28 16:44:34 -04001817 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001818 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1819 partitions[pn].SetUniqueGUID(theGUID);
1820 retval = 1;
1821 } // if
1822 } // if
1823 return retval;
1824} // GPTData::SetPartitionGUID()
1825
srs56949ba54212010-05-18 23:24:02 -04001826// Set new random GUIDs for the disk and all partitions. Intended to be used
1827// after disk cloning or similar operations that don't randomize the GUIDs.
1828void GPTData::RandomizeGUIDs(void) {
1829 uint32_t i;
1830
1831 mainHeader.diskGUID.Randomize();
1832 secondHeader.diskGUID = mainHeader.diskGUID;
1833 for (i = 0; i < numParts; i++)
1834 if (partitions[i].IsUsed())
1835 partitions[i].RandomizeUniqueGUID();
1836} // GPTData::RandomizeGUIDs()
1837
srs5694ba00fed2010-01-12 18:18:36 -05001838// Change partition type code non-interactively. Returns 1 if
1839// successful, 0 if not....
1840int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1841 int retval = 1;
1842
1843 if (!IsFreePartNum(partNum)) {
1844 partitions[partNum].SetType(hexCode);
1845 } else retval = 0;
1846 return retval;
1847} // GPTData::ChangePartType()
1848
srs56949ba54212010-05-18 23:24:02 -04001849// Recompute the CHS values of all the MBR partitions. Used to reset
1850// CHS values that some BIOSes require, despite the fact that the
1851// resulting CHS values violate the GPT standard.
1852void GPTData::RecomputeCHS(void) {
1853 int i;
1854
1855 for (i = 0; i < 4; i++)
1856 protectiveMBR.RecomputeCHS(i);
1857} // GPTData::RecomputeCHS()
1858
srs56941d1448a2009-12-31 21:20:19 -05001859// Adjust sector number so that it falls on a sector boundary that's a
1860// multiple of sectorAlignment. This is done to improve the performance
1861// of Western Digital Advanced Format disks and disks with similar
1862// technology from other companies, which use 4096-byte sectors
1863// internally although they translate to 512-byte sectors for the
1864// benefit of the OS. If partitions aren't properly aligned on these
1865// disks, some filesystem data structures can span multiple physical
1866// sectors, degrading performance. This function should be called
1867// only on the FIRST sector of the partition, not the last!
1868// This function returns 1 if the alignment was altered, 0 if it
1869// was unchanged.
1870int GPTData::Align(uint64_t* sector) {
1871 int retval = 0, sectorOK = 0;
1872 uint64_t earlier, later, testSector, original;
1873
1874 if ((*sector % sectorAlignment) != 0) {
1875 original = *sector;
1876 retval = 1;
1877 earlier = (*sector / sectorAlignment) * sectorAlignment;
1878 later = earlier + (uint64_t) sectorAlignment;
1879
1880 // Check to see that every sector between the earlier one and the
1881 // requested one is clear, and that it's not too early....
1882 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001883 sectorOK = 1;
1884 testSector = earlier;
1885 do {
1886 sectorOK = IsFree(testSector++);
1887 } while ((sectorOK == 1) && (testSector < *sector));
1888 if (sectorOK == 1) {
1889 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001890 } // if
1891 } // if firstUsableLBA check
1892
1893 // If couldn't move the sector earlier, try to move it later instead....
1894 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1895 sectorOK = 1;
1896 testSector = later;
1897 do {
1898 sectorOK = IsFree(testSector--);
1899 } while ((sectorOK == 1) && (testSector > *sector));
1900 if (sectorOK == 1) {
1901 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001902 } // if
1903 } // if
1904
1905 // If sector was changed successfully, inform the user of this fact.
1906 // Otherwise, notify the user that it couldn't be done....
1907 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001908 cout << "Information: Moved requested sector from " << original << " to "
srs56948a4ddfc2010-03-21 19:05:49 -04001909 << *sector << " in\norder to align on " << sectorAlignment
1910 << "-sector boundaries.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001911 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001912 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001913 } else {
srs5694fed16d02010-01-27 23:03:40 -05001914 cout << "Information: Sector not aligned on " << sectorAlignment
1915 << "-sector boundary and could not be moved.\n"
1916 << "If you're using a Western Digital Advanced Format or similar disk with\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001917 << "underlying 4096-byte sectors or certain types of RAID array, performance\n"
1918 << "may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001919 retval = 0;
1920 } // if/else
1921 } // if
1922 return retval;
1923} // GPTData::Align()
1924
srs5694e4ac11e2009-08-31 10:13:04 -04001925/********************************************************
1926 * *
1927 * Functions that return data about GPT data structures *
1928 * (most of these are inline in gpt.h) *
1929 * *
1930 ********************************************************/
1931
1932// Find the low and high used partition numbers (numbered from 0).
1933// Return value is the number of partitions found. Note that the
1934// *low and *high values are both set to 0 when no partitions
1935// are found, as well as when a single partition in the first
1936// position exists. Thus, the return value is the only way to
1937// tell when no partitions exist.
1938int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1939 uint32_t i;
1940 int numFound = 0;
1941
srs56940283dae2010-04-28 16:44:34 -04001942 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001943 *high = 0;
srs56940283dae2010-04-28 16:44:34 -04001944 if (numParts > 0) { // only try if partition table exists...
1945 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001946 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1947 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001948 // Set the low value only if it's not yet found...
srs56940283dae2010-04-28 16:44:34 -04001949 if (*low == (numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001950 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001951 } // if
1952 } // for
1953 } // if
1954
1955 // Above will leave *low pointing to its "not found" value if no partitions
1956 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001957 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001958 *low = 0;
1959 return numFound;
1960} // GPTData::GetPartRange()
1961
srs569408bb0da2010-02-19 17:19:55 -05001962// Returns the value of the first free partition, or -1 if none is
1963// unused.
1964int GPTData::FindFirstFreePart(void) {
1965 int i = 0;
1966
1967 if (partitions != NULL) {
srs56940283dae2010-04-28 16:44:34 -04001968 while ((partitions[i].IsUsed()) && (i < (int) numParts))
srs569408bb0da2010-02-19 17:19:55 -05001969 i++;
srs56940283dae2010-04-28 16:44:34 -04001970 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001971 i = -1;
1972 } else i = -1;
1973 return i;
1974} // GPTData::FindFirstFreePart()
1975
srs5694978041c2009-09-21 20:51:47 -04001976// Returns the number of defined partitions.
1977uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001978 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001979
srs56940283dae2010-04-28 16:44:34 -04001980 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001981 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001982 counted++;
1983 } // for
1984 return counted;
1985} // GPTData::CountParts()
1986
srs5694e4ac11e2009-08-31 10:13:04 -04001987/****************************************************
1988 * *
1989 * Functions that return data about disk free space *
1990 * *
1991 ****************************************************/
1992
1993// Find the first available block after the starting point; returns 0 if
1994// there are no available blocks left
1995uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1996 uint64_t first;
1997 uint32_t i;
1998 int firstMoved = 0;
1999
2000 // Begin from the specified starting point or from the first usable
2001 // LBA, whichever is greater...
2002 if (start < mainHeader.firstUsableLBA)
2003 first = mainHeader.firstUsableLBA;
2004 else
2005 first = start;
2006
2007 // ...now search through all partitions; if first is within an
2008 // existing partition, move it to the next sector after that
2009 // partition and repeat. If first was moved, set firstMoved
2010 // flag; repeat until firstMoved is not set, so as to catch
2011 // cases where partitions are out of sequential order....
2012 do {
2013 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002014 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002015 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002016 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002017 first = partitions[i].GetLastLBA() + 1;
2018 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002019 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002020 } // for
2021 } while (firstMoved == 1);
2022 if (first > mainHeader.lastUsableLBA)
2023 first = 0;
2024 return (first);
2025} // GPTData::FindFirstAvailable()
2026
2027// Finds the first available sector in the largest block of unallocated
2028// space on the disk. Returns 0 if there are no available blocks left
2029uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002030 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002031
2032 start = 0;
2033 do {
2034 firstBlock = FindFirstAvailable(start);
2035 if (firstBlock != UINT32_C(0)) { // something's free...
2036 lastBlock = FindLastInFree(firstBlock);
2037 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2038 if (segmentSize > selectedSize) {
2039 selectedSize = segmentSize;
2040 selectedSegment = firstBlock;
2041 } // if
2042 start = lastBlock + 1;
2043 } // if
2044 } while (firstBlock != 0);
2045 return selectedSegment;
2046} // GPTData::FindFirstInLargest()
2047
srs5694cb76c672010-02-11 22:22:22 -05002048// Find the last available block on the disk.
2049// Returns 0 if there are no available partitions
2050uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002051 uint64_t last;
2052 uint32_t i;
2053 int lastMoved = 0;
2054
2055 // Start by assuming the last usable LBA is available....
2056 last = mainHeader.lastUsableLBA;
2057
2058 // ...now, similar to algorithm in FindFirstAvailable(), search
2059 // through all partitions, moving last when it's in an existing
2060 // partition. Set the lastMoved flag so we repeat to catch cases
2061 // where partitions are out of logical order.
2062 do {
2063 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002064 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002065 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002066 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002067 last = partitions[i].GetFirstLBA() - 1;
2068 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002069 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002070 } // for
2071 } while (lastMoved == 1);
2072 if (last < mainHeader.firstUsableLBA)
2073 last = 0;
2074 return (last);
2075} // GPTData::FindLastAvailable()
2076
2077// Find the last available block in the free space pointed to by start.
2078uint64_t GPTData::FindLastInFree(uint64_t start) {
2079 uint64_t nearestStart;
2080 uint32_t i;
2081
2082 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002083 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002084 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002085 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002086 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002087 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002088 } // for
2089 return (nearestStart);
2090} // GPTData::FindLastInFree()
2091
2092// Finds the total number of free blocks, the number of segments in which
2093// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002094uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002095 uint64_t start = UINT64_C(0); // starting point for each search
2096 uint64_t totalFound = UINT64_C(0); // running total
2097 uint64_t firstBlock; // first block in a segment
2098 uint64_t lastBlock; // last block in a segment
2099 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002100 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002101
2102 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002103 if (diskSize > 0) {
2104 do {
2105 firstBlock = FindFirstAvailable(start);
2106 if (firstBlock != UINT64_C(0)) { // something's free...
2107 lastBlock = FindLastInFree(firstBlock);
2108 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2109 if (segmentSize > *largestSegment) {
2110 *largestSegment = segmentSize;
2111 } // if
2112 totalFound += segmentSize;
2113 num++;
2114 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002115 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002116 } while (firstBlock != 0);
2117 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002118 *numSegments = num;
2119 return totalFound;
2120} // GPTData::FindFreeBlocks()
2121
srs569455d92612010-03-07 22:16:07 -05002122// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2123// If it's allocated, return the partition number to which it's allocated
2124// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2125// returned in partNum if the sector is in use by basic GPT data structures.)
2126int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002127 int isFree = 1;
2128 uint32_t i;
2129
srs56940283dae2010-04-28 16:44:34 -04002130 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002131 if ((sector >= partitions[i].GetFirstLBA()) &&
2132 (sector <= partitions[i].GetLastLBA())) {
2133 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002134 if (partNum != NULL)
2135 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002136 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002137 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002138 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002139 (sector > mainHeader.lastUsableLBA)) {
2140 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002141 if (partNum != NULL)
2142 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002143 } // if
2144 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002145} // GPTData::IsFree()
2146
srs5694ba00fed2010-01-12 18:18:36 -05002147// Returns 1 if partNum is unused.
2148int GPTData::IsFreePartNum(uint32_t partNum) {
2149 int retval = 1;
2150
srs56940283dae2010-04-28 16:44:34 -04002151 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002152 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002153 retval = 0;
2154 } // if partition is in use
2155 } else retval = 0;
2156
2157 return retval;
2158} // GPTData::IsFreePartNum()
2159
srs5694a8582cf2010-03-19 14:21:59 -04002160
2161/***********************************************************
2162 * *
2163 * Change how functions work or return information on them *
2164 * *
2165 ***********************************************************/
2166
2167// Set partition alignment value; partitions will begin on multiples of
2168// the specified value
2169void GPTData::SetAlignment(uint32_t n) {
srs5694a8582cf2010-03-19 14:21:59 -04002170 sectorAlignment = n;
srs5694a8582cf2010-03-19 14:21:59 -04002171} // GPTData::SetAlignment()
2172
2173// Compute sector alignment based on the current partitions (if any). Each
2174// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56948a4ddfc2010-03-21 19:05:49 -04002175// value less than or equal to the DEFAULT_ALIGNMENT value, but not by the
2176// previously-located alignment value, then the alignment value is adjusted
2177// down. If the computed alignment is less than 8 and the disk is bigger than
2178// SMALLEST_ADVANCED_FORMAT, resets it to 8. This is a safety measure for WD
2179// Advanced Format and similar drives. If no partitions are defined, the
2180// alignment value is set to DEFAULT_ALIGNMENT (2048). The result is that new
2181// drives are aligned to 2048-sector multiples but the program won't complain
2182// about other alignments on existing disks unless a smaller-than-8 alignment
2183// is used on small disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002184// Returns the computed alignment value.
2185uint32_t GPTData::ComputeAlignment(void) {
2186 uint32_t i = 0, found, exponent = 31;
2187 uint64_t align = DEFAULT_ALIGNMENT;
2188
srs56948a4ddfc2010-03-21 19:05:49 -04002189 exponent = (uint32_t) log2(DEFAULT_ALIGNMENT);
srs56940283dae2010-04-28 16:44:34 -04002190 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002191 if (partitions[i].IsUsed()) {
2192 found = 0;
2193 while (!found) {
2194 align = PowerOf2(exponent);
2195 if ((partitions[i].GetFirstLBA() % align) == 0) {
2196 found = 1;
2197 } else {
2198 exponent--;
2199 } // if/else
2200 } // while
2201 } // if
2202 } // for
2203 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2204 align = 8;
srs5694a8582cf2010-03-19 14:21:59 -04002205 SetAlignment(align);
2206 return align;
2207} // GPTData::ComputeAlignment()
2208
srs5694e4ac11e2009-08-31 10:13:04 -04002209/********************************
2210 * *
2211 * Endianness support functions *
2212 * *
2213 ********************************/
2214
srs56942a9f5da2009-08-26 00:48:01 -04002215void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002216 ReverseBytes(&header->signature, 8);
2217 ReverseBytes(&header->revision, 4);
2218 ReverseBytes(&header->headerSize, 4);
2219 ReverseBytes(&header->headerCRC, 4);
2220 ReverseBytes(&header->reserved, 4);
2221 ReverseBytes(&header->currentLBA, 8);
2222 ReverseBytes(&header->backupLBA, 8);
2223 ReverseBytes(&header->firstUsableLBA, 8);
2224 ReverseBytes(&header->lastUsableLBA, 8);
2225 ReverseBytes(&header->partitionEntriesLBA, 8);
2226 ReverseBytes(&header->numParts, 4);
2227 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2228 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002229 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002230} // GPTData::ReverseHeaderBytes()
2231
srs56940283dae2010-04-28 16:44:34 -04002232// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002233void GPTData::ReversePartitionBytes() {
2234 uint32_t i;
2235
srs56940283dae2010-04-28 16:44:34 -04002236 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002237 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002238 } // for
2239} // GPTData::ReversePartitionBytes()
2240
2241/******************************************
2242 * *
2243 * Additional non-class support functions *
2244 * *
2245 ******************************************/
2246
srs5694e7b4ff92009-08-18 13:16:10 -04002247// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2248// never fail these tests, but the struct types may fail depending on compile options.
2249// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2250// sizes.
2251int SizesOK(void) {
2252 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002253
2254 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002255 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002256 allOK = 0;
2257 } // if
2258 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002259 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002260 allOK = 0;
2261 } // if
2262 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002263 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002264 allOK = 0;
2265 } // if
2266 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002267 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002268 allOK = 0;
2269 } // if
2270 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002271 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002272 allOK = 0;
2273 } // if
srs5694978041c2009-09-21 20:51:47 -04002274 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002275 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002276 allOK = 0;
2277 } // if
2278 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002279 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002280 allOK = 0;
2281 } // if
srs5694221e0872009-08-29 15:00:31 -04002282 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002283 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002284 allOK = 0;
2285 } // if
srs56946699b012010-02-04 00:55:30 -05002286 if (sizeof(GUIDData) != 16) {
2287 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2288 allOK = 0;
2289 } // if
2290 if (sizeof(PartType) != 16) {
2291 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2292 allOK = 0;
2293 } // if
srs5694fed16d02010-01-27 23:03:40 -05002294 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002295 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002296 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2297 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002298 } // if
2299 return (allOK);
2300} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002301