blob: 5ce5b7f88533e86cdb7505ba57a66df9b92a33ef [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>
17#include <time.h>
18#include <sys/stat.h>
19#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050020#include <iostream>
srs5694e7b4ff92009-08-18 13:16:10 -040021#include "crc32.h"
22#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040023#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040024#include "support.h"
25#include "parttypes.h"
26#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050027#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040028
29using namespace std;
30
31/****************************************
32 * *
33 * GPTData class and related structures *
34 * *
35 ****************************************/
36
srs5694e4ac11e2009-08-31 10:13:04 -040037// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040038GPTData::GPTData(void) {
39 blockSize = SECTOR_SIZE; // set a default
40 diskSize = 0;
41 partitions = NULL;
42 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050043 device = "";
srs56945d58fe02010-01-03 20:57:08 -050044 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040045 mainCrcOk = 0;
46 secondCrcOk = 0;
47 mainPartsCrcOk = 0;
48 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040049 apmFound = 0;
50 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050051 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050052 beQuiet = 0;
53 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040054 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050055 mainHeader.numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040056 SetGPTSize(NUM_GPT_ENTRIES);
57} // GPTData default constructor
58
59// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050060GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040061 blockSize = SECTOR_SIZE; // set a default
62 diskSize = 0;
63 partitions = NULL;
64 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050065 device = "";
srs56945d58fe02010-01-03 20:57:08 -050066 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040067 mainCrcOk = 0;
68 secondCrcOk = 0;
69 mainPartsCrcOk = 0;
70 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040071 apmFound = 0;
72 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050073 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050074 beQuiet = 0;
75 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040076 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050077 mainHeader.numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050078 if (!LoadPartitions(filename))
79 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050080} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040081
srs5694e4ac11e2009-08-31 10:13:04 -040082// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040083GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050084 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040085} // GPTData destructor
86
srs5694e4ac11e2009-08-31 10:13:04 -040087/*********************************************************************
88 * *
89 * Begin functions that verify data, or that adjust the verification *
90 * information (compute CRCs, rebuild headers) *
91 * *
92 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040093
srs5694e4ac11e2009-08-31 10:13:04 -040094// Perform detailed verification, reporting on any problems found, but
95// do *NOT* recover from these problems. Returns the total number of
96// problems identified.
97int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -050098 int problems = 0;
99 uint32_t i, numSegments;
100 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400101
102 // First, check for CRC errors in the GPT data....
103 if (!mainCrcOk) {
104 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500105 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
106 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
107 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
108 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400109 } // if
110 if (!mainPartsCrcOk) {
111 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500112 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
113 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
114 << "transformation menu). This report may be a false alarm if you've already\n"
115 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400116 } // if
117 if (!secondCrcOk) {
118 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500119 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
120 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
121 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
122 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400123 } // if
124 if (!secondPartsCrcOk) {
125 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500126 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
127 << "be corrupt. This program will automatically create a new backup partition\n"
128 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400129 } // if
130
srs5694978041c2009-09-21 20:51:47 -0400131 // Now check that the main and backup headers both point to themselves....
132 if (mainHeader.currentLBA != 1) {
133 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500134 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
135 << "is being automatically corrected, but it may be a symptom of more serious\n"
136 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400137 mainHeader.currentLBA = 1;
138 } // if
139 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
140 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500141 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
142 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
143 << "option on the experts' menu to adjust the secondary header's and partition\n"
144 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400145 } // if
146
147 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400148 if (mainHeader.currentLBA != secondHeader.backupLBA) {
149 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500150 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
151 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
152 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400153 } // if
154 if (mainHeader.backupLBA != secondHeader.currentLBA) {
155 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500156 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
157 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
158 << secondHeader.currentLBA << ").\n"
159 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400160 } // if
161 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
162 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500163 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
164 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
165 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400166 } // if
167 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
168 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500169 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
170 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
171 << secondHeader.lastUsableLBA << ")\n"
172 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400173 } // if
srs56946699b012010-02-04 00:55:30 -0500174 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400175 problems++;
srs56946699b012010-02-04 00:55:30 -0500176 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500177 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500178 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500179 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
180 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400181 } // if
182 if (mainHeader.numParts != secondHeader.numParts) {
183 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500184 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
185 << ") doesn't\nmatch the backup GPT header's number of partitions ("
186 << secondHeader.numParts << ")\n"
187 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400188 } // if
189 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
190 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500191 cout << "\nProblem: main GPT header's size of partition entries ("
192 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
193 << "match the backup GPT header's size of partition entries ("
194 << secondHeader.sizeOfPartitionEntries << ")\n"
195 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
196 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400197 } // if
198
199 // Now check for a few other miscellaneous problems...
200 // Check that the disk size will hold the data...
201 if (mainHeader.backupLBA > diskSize) {
202 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500203 cout << "\nProblem: Disk is too small to hold all the data!\n"
204 << "(Disk size is " << diskSize << " sectors, needs to be "
205 << mainHeader.backupLBA << " sectors.)\n"
206 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400207 } // if
208
209 // Check for overlapping partitions....
210 problems += FindOverlaps();
211
212 // Check for mismatched MBR and GPT partitions...
213 problems += FindHybridMismatches();
214
215 // Verify that partitions don't run into GPT data areas....
216 problems += CheckGPTSize();
217
srs56941d1448a2009-12-31 21:20:19 -0500218 // Check that partitions are aligned on proper boundaries (for WD Advanced
219 // Format and similar disks)....
220 for (i = 0; i < mainHeader.numParts; i++) {
221 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500222 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
223 << sectorAlignment << "-sector boundary. This may\nresult "
224 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500225 } // if
226 } // for
227
srs5694e4ac11e2009-08-31 10:13:04 -0400228 // Now compute available space, but only if no problems found, since
229 // problems could affect the results
230 if (problems == 0) {
231 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500232 cout << "No problems found. " << totalFree << " free sectors ("
233 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
234 << numSegments << "\nsegments, the largest of which is "
235 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
236 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400237 } else {
srs56940a697312010-01-28 21:10:52 -0500238 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400239 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400240
241 return (problems);
242} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400243
244// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400245// do, issues a warning but takes no action. Returns number of problems
246// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400247int GPTData::CheckGPTSize(void) {
248 uint64_t overlap, firstUsedBlock, lastUsedBlock;
249 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400250 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400251
252 // first, locate the first & last used blocks
253 firstUsedBlock = UINT64_MAX;
254 lastUsedBlock = 0;
255 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400256 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400257 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400258 firstUsedBlock = partitions[i].GetFirstLBA();
259 if (partitions[i].GetLastLBA() > lastUsedBlock)
260 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400261 } // for
262
263 // If the disk size is 0 (the default), then it means that various
264 // variables aren't yet set, so the below tests will be useless;
265 // therefore we should skip everything
266 if (diskSize != 0) {
267 if (mainHeader.firstUsableLBA > firstUsedBlock) {
268 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500269 cout << "Warning! Main partition table overlaps the first partition by "
270 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400271 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500272 cout << "Try reducing the partition table size by " << overlap * 4
273 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400274 } else {
srs5694fed16d02010-01-27 23:03:40 -0500275 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400276 } // if/else
277 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400278 } // Problem at start of disk
279 if (mainHeader.lastUsableLBA < lastUsedBlock) {
280 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs5694fed16d02010-01-27 23:03:40 -0500281 cout << "Warning! Secondary partition table overlaps the last partition by "
282 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400283 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500284 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400285 } else {
srs5694fed16d02010-01-27 23:03:40 -0500286 cout << "Try reducing the partition table size by " << overlap * 4
287 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400288 } // if/else
289 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400290 } // Problem at end of disk
291 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400292 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400293} // GPTData::CheckGPTSize()
294
srs5694e7b4ff92009-08-18 13:16:10 -0400295// Check the validity of the GPT header. Returns 1 if the main header
296// is valid, 2 if the backup header is valid, 3 if both are valid, and
297// 0 if neither is valid. Note that this function just checks the GPT
298// signature and revision numbers, not CRCs or other data.
299int GPTData::CheckHeaderValidity(void) {
300 int valid = 3;
301
srs5694fed16d02010-01-27 23:03:40 -0500302 cout.setf(ios::uppercase);
303 cout.fill('0');
304
305 // Note: failed GPT signature checks produce no error message because
306 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400307 if (mainHeader.signature != GPT_SIGNATURE) {
308 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400309 } else if ((mainHeader.revision != 0x00010000) && valid) {
310 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500311 cout << "Unsupported GPT version in main header; read 0x";
312 cout.width(8);
313 cout << hex << mainHeader.revision << ", should be\n0x";
314 cout.width(8);
315 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400316 } // if/else/if
317
318 if (secondHeader.signature != GPT_SIGNATURE) {
319 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400320 } else if ((secondHeader.revision != 0x00010000) && valid) {
321 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500322 cout << "Unsupported GPT version in backup header; read 0x";
323 cout.width(8);
324 cout << hex << secondHeader.revision << ", should be\n0x";
325 cout.width(8);
326 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400327 } // if/else/if
328
srs56942a9f5da2009-08-26 00:48:01 -0400329 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400330 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400331 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400332 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400333 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500334 } // if
srs5694fed16d02010-01-27 23:03:40 -0500335 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400336
srs5694fed16d02010-01-27 23:03:40 -0500337 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400338} // GPTData::CheckHeaderValidity()
339
340// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500341// Note: Must be called with header in LITTLE-ENDIAN
342// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400343int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400344 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400345
srs56942a9f5da2009-08-26 00:48:01 -0400346 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400347 // computation to be valid
348 oldCRC = header->headerCRC;
349 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400350 hSize = header->headerSize;
351
352 // If big-endian system, reverse byte order
353 if (IsLittleEndian() == 0) {
354 ReverseBytes(&oldCRC, 4);
355 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400356
357 // Initialize CRC functions...
358 chksum_crc32gentab();
359
360 // Compute CRC, restore original, and return result of comparison
361 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400362 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400363 return (oldCRC == newCRC);
364} // GPTData::CheckHeaderCRC()
365
srs56946699b012010-02-04 00:55:30 -0500366// Recompute all the CRCs. Must be called before saving if any changes have
367// been made. Must be called on platform-ordered data (this function reverses
368// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400369void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400370 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400371 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400372
373 // Initialize CRC functions...
374 chksum_crc32gentab();
375
srs56946699b012010-02-04 00:55:30 -0500376 // Save some key data from header before reversing byte order....
377 trueNumParts = mainHeader.numParts;
srs5694978041c2009-09-21 20:51:47 -0400378 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500379
380 if ((littleEndian = IsLittleEndian()) == 0) {
381 ReversePartitionBytes();
382 ReverseHeaderBytes(&mainHeader);
383 ReverseHeaderBytes(&secondHeader);
384 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400385
srs5694e7b4ff92009-08-18 13:16:10 -0400386 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400387 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400388 mainHeader.partitionEntriesCRC = crc;
389 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400390 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400391 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
392 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400393 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400394
395 // Zero out GPT tables' own CRCs (required for correct computation)
396 mainHeader.headerCRC = 0;
397 secondHeader.headerCRC = 0;
398
399 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400400 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400401 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400402 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400403 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400404 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400405 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400406 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400407 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500408
409 if ((littleEndian = IsLittleEndian()) == 0) {
410 ReverseHeaderBytes(&mainHeader);
411 ReverseHeaderBytes(&secondHeader);
412 ReversePartitionBytes();
413 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400414} // GPTData::RecomputeCRCs()
415
srs5694e7b4ff92009-08-18 13:16:10 -0400416// Rebuild the main GPT header, using the secondary header as a model.
417// Typically called when the main header has been found to be corrupt.
418void GPTData::RebuildMainHeader(void) {
419 int i;
420
421 mainHeader.signature = GPT_SIGNATURE;
422 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400423 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400424 mainHeader.headerCRC = UINT32_C(0);
425 mainHeader.reserved = secondHeader.reserved;
426 mainHeader.currentLBA = secondHeader.backupLBA;
427 mainHeader.backupLBA = secondHeader.currentLBA;
428 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
429 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500430 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400431 mainHeader.partitionEntriesLBA = UINT64_C(2);
432 mainHeader.numParts = secondHeader.numParts;
433 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
434 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
435 for (i = 0 ; i < GPT_RESERVED; i++)
436 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500437 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400438} // GPTData::RebuildMainHeader()
439
440// Rebuild the secondary GPT header, using the main header as a model.
441void GPTData::RebuildSecondHeader(void) {
442 int i;
443
444 secondHeader.signature = GPT_SIGNATURE;
445 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400446 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400447 secondHeader.headerCRC = UINT32_C(0);
448 secondHeader.reserved = mainHeader.reserved;
449 secondHeader.currentLBA = mainHeader.backupLBA;
450 secondHeader.backupLBA = mainHeader.currentLBA;
451 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
452 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500453 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400454 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
455 secondHeader.numParts = mainHeader.numParts;
456 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
457 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
458 for (i = 0 ; i < GPT_RESERVED; i++)
459 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500460 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400461} // GPTData::RebuildSecondHeader()
462
463// Search for hybrid MBR entries that have no corresponding GPT partition.
464// Returns number of such mismatches found
465int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500466 int i, found, numFound = 0;
467 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400468 uint64_t mbrFirst, mbrLast;
469
470 for (i = 0; i < 4; i++) {
471 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
472 j = 0;
473 found = 0;
474 do {
475 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
476 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
477 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
478 (partitions[j].GetLastLBA() == mbrLast))
479 found = 1;
480 j++;
481 } while ((!found) && (j < mainHeader.numParts));
482 if (!found) {
483 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500484 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
485 << i + 1 << ", of type 0x";
486 cout.fill('0');
487 cout.setf(ios::uppercase);
488 cout.width(2);
489 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
490 << "has no corresponding GPT partition! You may continue, but this condition\n"
491 << "might cause data loss in the future!\a\n" << dec;
492 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400493 } // if
494 } // if
495 } // for
496 return numFound;
497} // GPTData::FindHybridMismatches
498
499// Find overlapping partitions and warn user about them. Returns number of
500// overlapping partitions.
501int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500502 int problems = 0;
503 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400504
505 for (i = 1; i < mainHeader.numParts; i++) {
506 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500507 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400508 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500509 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
510 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
511 << " to " << partitions[i].GetLastLBA() << "\n";
512 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
513 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400514 } // if
515 } // for j...
516 } // for i...
517 return problems;
518} // GPTData::FindOverlaps()
519
520/******************************************************************
521 * *
522 * Begin functions that load data from disk or save data to disk. *
523 * *
524 ******************************************************************/
525
526// Scan for partition data. This function loads the MBR data (regular MBR or
527// protective MBR) and loads BSD disklabel data (which is probably invalid).
528// It also looks for APM data, forces a load of GPT data, and summarizes
529// the results.
srs5694546a9c72010-01-26 16:00:26 -0500530void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400531 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400532
533 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500534 protectiveMBR.ReadMBRData(&myDisk);
535 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400536
537 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500538 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500539
540 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500541 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500542 protectiveMBR.ShowState();
543 bsdDisklabel.ShowState();
544 ShowAPMState(); // Show whether there's an Apple Partition Map present
545 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500546 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500547 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400548
549 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500550 cout << "\n*******************************************************************\n"
551 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500552 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500553 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500554 } // if
srs5694fed16d02010-01-27 23:03:40 -0500555 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400556 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400557} // GPTData::PartitionScan()
558
559// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500560int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500561 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500562 int err, allOK = 1;
563 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -0400564 uint64_t firstBlock, lastBlock;
srs5694fed16d02010-01-27 23:03:40 -0500565 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400566
567 // First, do a test to see if writing will be possible later....
srs5694fed16d02010-01-27 23:03:40 -0500568 err = myDisk.OpenForWrite(deviceFilename);
569 if ((err == 0) && (!justLooking)) {
570 cout << "\aNOTE: Write test failed with error number " << errno
571 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
srs569408bb0da2010-02-19 17:19:55 -0500572#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694fed16d02010-01-27 23:03:40 -0500573 cout << "You may be able to enable writes by exiting this program, typing\n"
574 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
575 << "program.\n";
srs56947dbb9322010-01-20 16:56:30 -0500576#endif
srs5694fed16d02010-01-27 23:03:40 -0500577 cout << "\n";
srs56945d58fe02010-01-03 20:57:08 -0500578 } // if
srs5694546a9c72010-01-26 16:00:26 -0500579 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400580
srs5694546a9c72010-01-26 16:00:26 -0500581 if (myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400582 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500583 diskSize = myDisk.DiskSize(&err);
584 blockSize = (uint32_t) myDisk.GetBlockSize();
585 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500586 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500587 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400588
srs5694ba00fed2010-01-12 18:18:36 -0500589 whichWasUsed = UseWhichPartitions();
590 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400591 case use_mbr:
592 XFormPartitions();
593 break;
594 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500595 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400596// bsdDisklabel.DisplayBSDData();
597 ClearGPTData();
598 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500599 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400600 break;
601 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500602 mbrState = protectiveMBR.GetValidity();
603 if ((mbrState == invalid) || (mbrState == mbr))
604 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400605 break;
606 case use_new:
607 ClearGPTData();
608 protectiveMBR.MakeProtectiveMBR();
609 break;
srs56943c0af382010-01-15 19:19:18 -0500610 case use_abort:
611 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500612 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500613 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400614 } // switch
615
616 // Now find the first and last sectors used by partitions...
617 if (allOK) {
618 firstBlock = mainHeader.backupLBA; // start high
619 lastBlock = 0; // start low
620 for (i = 0; i < mainHeader.numParts; i++) {
621 if ((partitions[i].GetFirstLBA() < firstBlock) &&
622 (partitions[i].GetFirstLBA() > 0))
623 firstBlock = partitions[i].GetFirstLBA();
624 if (partitions[i].GetLastLBA() > lastBlock)
625 lastBlock = partitions[i].GetLastLBA();
626 } // for
srs56943c0af382010-01-15 19:19:18 -0500627 CheckGPTSize();
srs5694e4ac11e2009-08-31 10:13:04 -0400628 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400629 } else {
630 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500631 cerr << "Problem opening " << deviceFilename << " for reading! Error is "
632 << errno << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400633 if (errno == EACCES) { // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -0500634 cerr << "You must run this program as root or use sudo!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400635 } // if
636 } // if/else
637 return (allOK);
638} // GPTData::LoadPartitions()
639
640// Loads the GPT, as much as possible. Returns 1 if this seems to have
641// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500642int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500643 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400644
srs5694cb76c672010-02-11 22:22:22 -0500645 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400646
srs5694cb76c672010-02-11 22:22:22 -0500647 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
648 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
649 } else {
srs569408bb0da2010-02-19 17:19:55 -0500650 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
651 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500652 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
653 << "secondary header from the last sector of the disk! You should use 'v' to\n"
654 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
655 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500656 } // if/else
657 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400658 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400659
660 // Return valid headers code: 0 = both headers bad; 1 = main header
661 // good, backup bad; 2 = backup header good, main header bad;
662 // 3 = both headers good. Note these codes refer to valid GPT
663 // signatures and version numbers; more subtle problems will elude
664 // this check!
665 validHeaders = CheckHeaderValidity();
666
667 // Read partitions (from primary array)
668 if (validHeaders > 0) { // if at least one header is OK....
669 // GPT appears to be valid....
670 state = gpt_valid;
671
672 // We're calling the GPT valid, but there's a possibility that one
673 // of the two headers is corrupt. If so, use the one that seems to
674 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500675 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500676 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
677 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400678 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500679 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400680 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500681 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500682 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
683 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500684 RebuildMainHeader();
685 state = gpt_corrupt;
686 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400687 } // if/else/if
688
srs5694546a9c72010-01-26 16:00:26 -0500689 // Figure out which partition table to load....
690 // Load the main partition table, since either its header's CRC is OK or the
691 // backup header's CRC is not OK....
692 if (mainCrcOk || !secondCrcOk) {
693 if (LoadMainTable() == 0)
694 allOK = 0;
695 } else { // bad main header CRC and backup header CRC is OK
696 state = gpt_corrupt;
697 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500698 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500699 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500700 } else { // backup table bad, bad main header CRC, but try main table in desperation....
701 if (LoadMainTable() == 0) {
702 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500703 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500704 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500705 } // if
706 } // if/else (LoadSecondTableAsMain())
707 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400708
srs5694cb76c672010-02-11 22:22:22 -0500709 if (loadedTable == 1)
710 secondPartsCrcOk = CheckTable(&secondHeader);
711 else if (loadedTable == 2)
712 mainPartsCrcOk = CheckTable(&mainHeader);
713 else
714 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400715
srs5694546a9c72010-01-26 16:00:26 -0500716 // Problem with main partition table; if backup is OK, use it instead....
717 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
718 state = gpt_corrupt;
719 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500720 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500721 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
722 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500723 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500724
srs5694e4ac11e2009-08-31 10:13:04 -0400725 // Check for valid CRCs and warn if there are problems
726 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
727 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500728 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400729 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500730 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400731 } else {
732 state = gpt_invalid;
733 } // if/else
734 return allOK;
735} // GPTData::ForceLoadGPTData()
736
srs5694247657a2009-11-26 18:36:12 -0500737// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400738// main GPT header in memory MUST be valid for this call to do anything
739// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500740// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400741int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500742 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400743} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400744
745// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500746// table. Used in repair functions, and when starting up if the main
747// partition table is damaged.
748// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
749int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500750 return LoadPartitionTable(secondHeader, myDisk);
751} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400752
srs5694cb76c672010-02-11 22:22:22 -0500753// Load a single GPT header (main or backup) from the specified disk device and
754// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
755// value appropriately.
756// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
757// failure.
758int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
759 int allOK = 1;
760
761 disk.Seek(sector);
762 if (disk.Read(header, 512) != 512) {
763 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
764 allOK = 0;
765 } // if
766 *crcOk = CheckHeaderCRC(header);
767
768 // Reverse byte order, if necessary
769 if (IsLittleEndian() == 0) {
770 ReverseHeaderBytes(header);
771 } // if
772 return allOK;
773} // GPTData::LoadHeader
774
775// Load a partition table (either main or secondary) from the specified disk,
776// using header as a reference for what to load. If sector != 0 (the default
777// is 0), loads from the specified sector; otherwise loads from the sector
778// indicated in header.
779// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
780int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
781 uint32_t sizeOfParts, newCRC;
782 int retval;
783
784 if (disk.OpenForRead()) {
785 if (sector == 0) {
786 retval = disk.Seek(header.partitionEntriesLBA);
787 } else {
788 retval = disk.Seek(sector);
789 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500790 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500791 SetGPTSize(header.numParts);
792 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
793 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500794 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500795 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500796 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400797 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500798 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400799 if (IsLittleEndian() == 0)
800 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500801 if (!mainPartsCrcOk) {
802 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400803 } // if
804 } else {
srs5694cb76c672010-02-11 22:22:22 -0500805 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400806 } // if/else
807 } else {
srs5694fed16d02010-01-27 23:03:40 -0500808 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500809 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500810 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400811 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500812 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500813} // GPTData::LoadPartitionsTable()
814
815// Check the partition table pointed to by header, but don't keep it
816// around.
817// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
818int GPTData::CheckTable(struct GPTHeader *header) {
819 uint32_t sizeOfParts, newCRC;
820 uint8_t *storage;
821 int newCrcOk = 0;
822
823 // Load backup partition table into temporary storage to check
824 // its CRC and store the results, then discard this temporary
825 // storage, since we don't use it in any but recovery operations
826 if (myDisk.Seek(header->partitionEntriesLBA)) {
827 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
828 storage = new uint8_t[sizeOfParts];
829 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
830 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
831 } else {
832 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
833 newCrcOk = (newCRC == header->partitionEntriesCRC);
834 } // if/else
835 delete[] storage;
836 } // if
837 return newCrcOk;
838} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400839
srs5694e7b4ff92009-08-18 13:16:10 -0400840// Writes GPT (and protective MBR) to disk. Returns 1 on successful
841// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500842int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500843 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500844 char answer;
srs56942a9f5da2009-08-26 00:48:01 -0400845 uint32_t numParts;
srs5694e7b4ff92009-08-18 13:16:10 -0400846
srs56946699b012010-02-04 00:55:30 -0500847 littleEndian = IsLittleEndian();
848
srs5694fed16d02010-01-27 23:03:40 -0500849 if (device == "") {
850 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400851 } // if
852
853 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500854
855 // This test should only fail on read-only disks....
856 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500857 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500858 allOK = 0;
859 } // if
860
srs5694e7b4ff92009-08-18 13:16:10 -0400861 // Is there enough space to hold the GPT headers and partition tables,
862 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400863 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400864 allOK = 0;
865 } // if
866
867 // Check that disk is really big enough to handle this...
868 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500869 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
870 << "problem (or it might not). Aborting!\n(Disk size is "
871 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400872 allOK = 0;
873 } // if
srs5694247657a2009-11-26 18:36:12 -0500874 // Check that second header is properly placed. Warn and ask if this should
875 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500876 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500877 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
878 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500879 if (GetYN() == 'Y') {
880 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500881 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500882 } else {
srs5694fed16d02010-01-27 23:03:40 -0500883 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500884 } // if correction requested
885 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400886
887 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400888 if (FindOverlaps() > 0) {
889 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500890 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400891 } // if
892
893 // Check for mismatched MBR and GPT data, but let it pass if found
894 // (function displays warning message)
895 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400896
srs56942a9f5da2009-08-26 00:48:01 -0400897 // Pull out some data that's needed before doing byte-order reversal on
898 // big-endian systems....
899 numParts = mainHeader.numParts;
srs5694cb76c672010-02-11 22:22:22 -0500900
srs5694e7b4ff92009-08-18 13:16:10 -0400901 RecomputeCRCs();
902
srs5694ba00fed2010-01-12 18:18:36 -0500903 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500904 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
905 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500906 answer = GetYN();
907 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500908 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400909 } else {
910 allOK = 0;
911 } // if/else
912 } // if
913
914 // Do it!
915 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500916 // First, write the protective MBR...
917 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400918
srs5694546a9c72010-01-26 16:00:26 -0500919 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400920 // Now write the main GPT header...
srs5694cb76c672010-02-11 22:22:22 -0500921 allOK = SaveHeader(&mainHeader, myDisk, 1);
srs5694e7b4ff92009-08-18 13:16:10 -0400922
923 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400924 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500925 allOK = SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
srs56941e093722010-01-05 00:14:19 -0500926 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400927
928 // Now seek to near the end to write the secondary GPT....
srs5694cb76c672010-02-11 22:22:22 -0500929 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
930 if (!allOK)
931 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
932 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400933
934 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500935 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500936 allOK = SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
srs56946699b012010-02-04 00:55:30 -0500937 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400938
939 // re-read the partition table
940 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500941 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400942 } // if
943
944 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500945 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400946 } else {
srs5694fed16d02010-01-27 23:03:40 -0500947 cerr << "Warning! An error was reported when writing the partition table! This error\n"
948 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
949 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400950 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500951 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400952 } else {
srs5694fed16d02010-01-27 23:03:40 -0500953 cerr << "Unable to open device " << device << " for writing! Errno is "
954 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400955 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400956 } // if/else
957 } else {
srs5694fed16d02010-01-27 23:03:40 -0500958 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400959 } // if
960
961 return (allOK);
962} // GPTData::SaveGPTData()
963
964// Save GPT data to a backup file. This function does much less error
965// checking than SaveGPTData(). It can therefore preserve many types of
966// corruption for later analysis; however, it preserves only the MBR,
967// the main GPT header, the backup GPT header, and the main partition
968// table; it discards the backup partition table, since it should be
969// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500970int GPTData::SaveGPTBackup(const string & filename) {
971 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500972 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400973
srs5694546a9c72010-01-26 16:00:26 -0500974 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500975 // Recomputing the CRCs is likely to alter them, which could be bad
976 // if the intent is to save a potentially bad GPT for later analysis;
977 // but if we don't do this, we get bogus errors when we load the
978 // backup. I'm favoring misses over false alarms....
979 RecomputeCRCs();
980
srs5694546a9c72010-01-26 16:00:26 -0500981 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400982
srs5694cb76c672010-02-11 22:22:22 -0500983 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500984 // MBR write closed disk, so re-open and seek to end....
985 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500986 allOK = SaveHeader(&mainHeader, backupFile, 1);
987 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400988
srs5694e7b4ff92009-08-18 13:16:10 -0400989 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -0500990 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -0400991
srs5694cb76c672010-02-11 22:22:22 -0500992 if (allOK)
993 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -0400994
995 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500996 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400997 } else {
srs5694fed16d02010-01-27 23:03:40 -0500998 cerr << "Warning! An error was reported when writing the backup file.\n"
999 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001000 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001001 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001002 } else {
srs5694fed16d02010-01-27 23:03:40 -05001003 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001004 allOK = 0;
1005 } // if/else
1006 return allOK;
1007} // GPTData::SaveGPTBackup()
1008
srs5694cb76c672010-02-11 22:22:22 -05001009// Write a GPT header (main or backup) to the specified sector. Used by both
1010// the SaveGPTData() and SaveGPTBackup() functions.
1011// Should be passed an architecture-appropriate header (DO NOT call
1012// ReverseHeaderBytes() on the header before calling this function)
1013// Returns 1 on success, 0 on failure
1014int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1015 int littleEndian, allOK = 1;
1016
1017 littleEndian = IsLittleEndian();
1018 if (!littleEndian)
1019 ReverseHeaderBytes(header);
1020 if (disk.Seek(sector)) {
1021 if (disk.Write(header, 512) == -1)
1022 allOK = 0;
1023 } else allOK = 0; // if (disk.Seek()...)
1024 if (!littleEndian)
1025 ReverseHeaderBytes(header);
1026 return allOK;
1027} // GPTData::SaveHeader()
1028
1029// Save the partitions to the specified sector. Used by both the SaveGPTData()
1030// and SaveGPTBackup() functions.
1031// Should be passed an architecture-appropriate header (DO NOT call
1032// ReverseHeaderBytes() on the header before calling this function)
1033// Returns 1 on success, 0 on failure
1034int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1035 int littleEndian, allOK = 1;
1036
1037 littleEndian = IsLittleEndian();
1038 if (disk.Seek(sector)) {
1039 if (!littleEndian)
1040 ReversePartitionBytes();
1041 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1042 allOK = 0;
1043 if (!littleEndian)
1044 ReversePartitionBytes();
1045 } else allOK = 0; // if (myDisk.Seek()...)
1046 return allOK;
1047} // GPTData::SavePartitionTable()
1048
srs5694e7b4ff92009-08-18 13:16:10 -04001049// Load GPT data from a backup file created by SaveGPTBackup(). This function
1050// does minimal error checking. It returns 1 if it completed successfully,
1051// 0 if there was a problem. In the latter case, it creates a new empty
1052// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001053int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001054 int allOK = 1, val, err;
1055 uint32_t numParts, sizeOfEntries;
1056 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001057 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001058
srs5694546a9c72010-01-26 16:00:26 -05001059 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001060 if (IsLittleEndian() == 0)
1061 littleEndian = 0;
1062
srs5694e7b4ff92009-08-18 13:16:10 -04001063 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001064 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001065
srs5694cb76c672010-02-11 22:22:22 -05001066 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001067
srs5694cb76c672010-02-11 22:22:22 -05001068 // Check backup file size and rebuild second header if file is right
1069 // size to be direct dd copy of MBR, main header, and main partition
1070 // table; if other size, treat it like a GPT fdisk-generated backup
1071 // file
1072 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1073 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1074 if (shortBackup) {
1075 RebuildSecondHeader();
1076 secondCrcOk = mainCrcOk;
1077 } else {
1078 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1079 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001080
srs5694e7b4ff92009-08-18 13:16:10 -04001081 // Return valid headers code: 0 = both headers bad; 1 = main header
1082 // good, backup bad; 2 = backup header good, main header bad;
1083 // 3 = both headers good. Note these codes refer to valid GPT
1084 // signatures and version numbers; more subtle problems will elude
1085 // this check!
1086 if ((val = CheckHeaderValidity()) > 0) {
1087 if (val == 2) { // only backup header seems to be good
1088 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001089 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001090 } else { // main header is OK
1091 numParts = mainHeader.numParts;
1092 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1093 } // if/else
1094
1095 SetGPTSize(numParts);
1096
srs5694e7b4ff92009-08-18 13:16:10 -04001097 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001098 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1099 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001100 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001101 } // if
1102
srs5694cb76c672010-02-11 22:22:22 -05001103 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1104 cerr << "Warning! Read error " << errno
1105 << " loading partition table; strange behavior now likely!\n";
srs56942a9f5da2009-08-26 00:48:01 -04001106
srs5694e7b4ff92009-08-18 13:16:10 -04001107 } else {
1108 allOK = 0;
1109 } // if/else
1110 } else {
1111 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001112 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001113 } // if/else
1114
1115 // Something went badly wrong, so blank out partitions
1116 if (allOK == 0) {
1117 ClearGPTData();
1118 protectiveMBR.MakeProtectiveMBR();
1119 } // if
1120 return allOK;
1121} // GPTData::LoadGPTBackup()
1122
srs569408bb0da2010-02-19 17:19:55 -05001123int GPTData::SaveMBR(void) {
1124 return protectiveMBR.WriteMBRData();
1125} // GPTData::SaveMBR()
1126
1127// This function destroys the on-disk GPT structures, but NOT the on-disk
1128// MBR.
1129// Returns 1 if the operation succeeds, 0 if not.
1130int GPTData::DestroyGPT(void) {
1131 int i, sum, tableSize, allOK = 1;
1132 uint8_t blankSector[512];
1133 uint8_t* emptyTable;
1134
1135 for (i = 0; i < 512; i++) {
1136 blankSector[i] = 0;
1137 } // for
1138
1139 if (myDisk.OpenForWrite()) {
1140 if (!myDisk.Seek(mainHeader.currentLBA))
1141 allOK = 0;
1142 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1143 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1144 allOK = 0;
1145 } // if
1146 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1147 allOK = 0;
1148 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
1149 emptyTable = new uint8_t[tableSize];
1150 for (i = 0; i < tableSize; i++)
1151 emptyTable[i] = 0;
1152 if (allOK) {
1153 sum = myDisk.Write(emptyTable, tableSize);
1154 if (sum != tableSize) {
1155 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1156 allOK = 0;
1157 } // if write failed
1158 } // if
1159 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1160 allOK = 0;
1161 if (allOK) {
1162 sum = myDisk.Write(emptyTable, tableSize);
1163 if (sum != tableSize) {
1164 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1165 << errno << "\n";
1166 allOK = 0;
1167 } // if wrong size written
1168 } // if
1169 if (!myDisk.Seek(secondHeader.currentLBA))
1170 allOK = 0;
1171 if (allOK) {
1172 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1173 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1174 allOK = 0;
1175 } // if
1176 } // if
1177 myDisk.DiskSync();
1178 myDisk.Close();
1179 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1180 << "other utilities.\n";
1181 delete[] emptyTable;
1182 } else {
1183 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1184 } // if/else (fd != -1)
1185 return (allOK);
1186} // GPTDataTextUI::DestroyGPT()
1187
1188// Wipe MBR data from the disk (zero it out completely)
1189// Returns 1 on success, 0 on failure.
1190int GPTData::DestroyMBR(void) {
1191 int allOK = 1, i;
1192 uint8_t blankSector[512];
1193
1194 for (i = 0; i < 512; i++)
1195 blankSector[i] = 0;
1196
1197 if (myDisk.OpenForWrite()) {
1198 if (myDisk.Seek(0)) {
1199 if (myDisk.Write(blankSector, 512) != 512)
1200 allOK = 0;
1201 } else allOK = 0;
1202 } else allOK = 0;
1203 if (!allOK)
1204 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1205 return allOK;
1206} // GPTData::DestroyMBR(void)
1207
srs5694e4ac11e2009-08-31 10:13:04 -04001208// Tell user whether Apple Partition Map (APM) was discovered....
1209void GPTData::ShowAPMState(void) {
1210 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001211 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001212 else
srs5694fed16d02010-01-27 23:03:40 -05001213 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001214} // GPTData::ShowAPMState()
1215
1216// Tell user about the state of the GPT data....
1217void GPTData::ShowGPTState(void) {
1218 switch (state) {
1219 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001220 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001221 break;
1222 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001223 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001224 break;
1225 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001227 break;
1228 default:
srs5694fed16d02010-01-27 23:03:40 -05001229 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001230 break;
1231 } // switch
1232} // GPTData::ShowGPTState()
1233
1234// Display the basic GPT data
1235void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001236 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001237 uint64_t temp, totalFree;
1238
srs5694fed16d02010-01-27 23:03:40 -05001239 cout << "Disk " << device << ": " << diskSize << " sectors, "
1240 << BytesToSI(diskSize * blockSize) << "\n";
1241 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001242 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001243 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1244 cout << "First usable sector is " << mainHeader.firstUsableLBA
1245 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001246 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001247 cout << "Total free space is " << totalFree << " sectors ("
1248 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1249 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001250 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001251 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001252 } // for
1253} // GPTData::DisplayGPTData()
1254
srs5694e4ac11e2009-08-31 10:13:04 -04001255// Show detailed information on the specified partition
1256void GPTData::ShowPartDetails(uint32_t partNum) {
1257 if (partitions[partNum].GetFirstLBA() != 0) {
1258 partitions[partNum].ShowDetails(blockSize);
1259 } else {
srs5694fed16d02010-01-27 23:03:40 -05001260 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001261 } // if
1262} // GPTData::ShowPartDetails()
1263
srs5694e4ac11e2009-08-31 10:13:04 -04001264/**************************************************************************
1265 * *
1266 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1267 * (some of these functions may require user interaction) *
1268 * *
1269 **************************************************************************/
1270
srs569408bb0da2010-02-19 17:19:55 -05001271// Examines the MBR & GPT data to determine which set of data to use: the
1272// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1273// a new set of partitions (use_new). A return value of use_abort indicates
1274// that this function couldn't determine what to do. Overriding functions
1275// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001276WhichToUse GPTData::UseWhichPartitions(void) {
1277 WhichToUse which = use_new;
1278 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001279
1280 mbrState = protectiveMBR.GetValidity();
1281
1282 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001283 cout << "\n***************************************************************\n"
1284 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001285 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001286 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1287 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001288 } // if
srs5694fed16d02010-01-27 23:03:40 -05001289 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001290 which = use_mbr;
1291 } // if
1292
1293 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001294 cout << "\n**********************************************************************\n"
1295 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1296 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001297 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001298 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1299 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1300 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001301 } // if
srs5694fed16d02010-01-27 23:03:40 -05001302 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001303 which = use_bsd;
1304 } // if
1305
1306 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001307 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001308 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001309 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001310 } // if
1311 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001312 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001313 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001314 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001315 } // if
1316 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001317 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001318 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001319 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001320 } // if
1321 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001322 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001323 } // if
1324
srs5694e4ac11e2009-08-31 10:13:04 -04001325 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001326 if (mbrState == gpt) {
1327 cout << "\a\a****************************************************************************\n"
1328 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1329 << "verification and recovery are STRONGLY recommended.\n"
1330 << "****************************************************************************\n";
1331 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001332 } else {
srs569408bb0da2010-02-19 17:19:55 -05001333 which = use_abort;
1334 } // if/else MBR says disk is GPT
1335 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001336
1337 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001338 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001339
1340 return which;
1341} // UseWhichPartitions()
1342
srs569408bb0da2010-02-19 17:19:55 -05001343// Convert MBR partition table into GPT form.
1344void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001345 int i, numToConvert;
1346 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001347
1348 // Clear out old data & prepare basics....
1349 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001350 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001351
1352 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001353 if (mainHeader.numParts > (MAX_MBR_PARTS))
1354 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001355 else
1356 numToConvert = mainHeader.numParts;
1357
1358 for (i = 0; i < numToConvert; i++) {
1359 origType = protectiveMBR.GetType(i);
1360 // don't waste CPU time trying to convert extended, hybrid protective, or
1361 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001362 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001363 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001364 partitions[i] = protectiveMBR.AsGPT(i);
1365 } // for
1366
1367 // Convert MBR into protective MBR
1368 protectiveMBR.MakeProtectiveMBR();
1369
1370 // Record that all original CRCs were OK so as not to raise flags
1371 // when doing a disk verification
1372 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001373} // GPTData::XFormPartitions()
1374
1375// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001376// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001377// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001378int GPTData::XFormDisklabel(uint32_t partNum) {
1379 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001380 int goOn = 1, numDone = 0;
1381 BSDData disklabel;
1382
srs569408bb0da2010-02-19 17:19:55 -05001383 if (GetPartRange(&low, &high) == 0) {
1384 goOn = 0;
1385 cout << "No partitions!\n";
1386 } // if
1387 if (partNum > high) {
1388 goOn = 0;
1389 cout << "Specified partition is invalid!\n";
1390 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001391
srs569408bb0da2010-02-19 17:19:55 -05001392 // If all is OK, read the disklabel and convert it.
1393 if (goOn) {
1394 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1395 partitions[partNum].GetLastLBA());
1396 if ((goOn) && (disklabel.IsDisklabel())) {
1397 numDone = XFormDisklabel(&disklabel);
1398 if (numDone == 1)
1399 cout << "Converted 1 BSD partition.\n";
1400 else
1401 cout << "Converted " << numDone << " BSD partitions.\n";
1402 } else {
1403 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1404 } // if/else
1405 } // if
1406 if (numDone > 0) { // converted partitions; delete carrier
1407 partitions[partNum].BlankPartition();
1408 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001409 return numDone;
1410} // GPTData::XFormDisklable(int i)
1411
1412// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001413int GPTData::XFormDisklabel(BSDData* disklabel) {
1414 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001415
srs569408bb0da2010-02-19 17:19:55 -05001416 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001417 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001418 partNum = FindFirstFreePart();
1419 if (partNum >= 0) {
1420 partitions[partNum] = disklabel->AsGPT(i);
1421 if (partitions[partNum].IsUsed())
1422 numDone++;
1423 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001424 } // for
srs569408bb0da2010-02-19 17:19:55 -05001425 if (partNum == -1)
1426 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001427 } // if
1428
1429 // Record that all original CRCs were OK so as not to raise flags
1430 // when doing a disk verification
1431 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1432
1433 return numDone;
1434} // GPTData::XFormDisklabel(BSDData* disklabel)
1435
srs569408bb0da2010-02-19 17:19:55 -05001436// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1437// partition has the active/bootable flag UNset and uses the GPT fdisk
1438// type code divided by 0x0100 as the MBR type code.
1439// Returns 1 if operation was 100% successful, 0 if there were ANY
1440// problems.
srs5694978041c2009-09-21 20:51:47 -04001441int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001442 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001443
srs5694978041c2009-09-21 20:51:47 -04001444 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001445 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001446 allOK = 0;
1447 } // if
1448 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001449 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001450 allOK = 0;
1451 } // if
1452 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001453 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001454 allOK = 0;
1455 } // if
1456 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1457 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1458 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001459 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1460 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001461 } // if
srs5694978041c2009-09-21 20:51:47 -04001462 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001463 (uint32_t) partitions[gptPart].GetLengthLBA(),
1464 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001465 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001466 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1467 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1468 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001469 allOK = 0;
1470 } // if/else
1471 return allOK;
1472} // GPTData::OnePartToMBR()
1473
srs569408bb0da2010-02-19 17:19:55 -05001474// Convert up to four partitions to MBR form and return the number done.
1475// Partitions are specified in an array of GPT partition numbers,
1476// with an associated array of partition type codes. Both must be
1477// at least four elements in size (longer is OK, but will be ignored).
1478// A partition number of MBR_EFI_GPT means to place an EFI GPT
1479// protective partition in that location in the table (the associated
1480// mbrType[] should be 0xEE), and MBR_EMPTY means not to create a
1481// partition in that table position. If the mbrType[] entry for a
1482// partition is 0, a default entry is used, based on the GPT
1483// partition type code.
1484// Returns the number of partitions converted, NOT counting EFI GPT
1485// protective partitions.
1486int GPTData::PartsToMBR(const int *gptParts, const int *mbrTypes) {
1487 int i, numConverted = 0;
srs5694978041c2009-09-21 20:51:47 -04001488
srs569408bb0da2010-02-19 17:19:55 -05001489 if ((gptParts != NULL) && (mbrTypes != NULL)) {
1490 protectiveMBR.EmptyMBR();
srs5694e4ac11e2009-08-31 10:13:04 -04001491 protectiveMBR.SetDiskSize(diskSize);
srs569408bb0da2010-02-19 17:19:55 -05001492 // Do two passes, one to get "real" partitions and
1493 // the next to create EFI GPT protective partition(s)
srs5694e4ac11e2009-08-31 10:13:04 -04001494 for (i = 0; i < 4; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001495 if (gptParts[i] >= 0) {
1496 numConverted += OnePartToMBR((uint32_t) gptParts[i], i);
1497 if (mbrTypes[i] != 0)
1498 protectiveMBR.SetPartType(i, mbrTypes[i]);
1499 } // if
1500 } // for (regular partition pass)
1501 for (i = 0; i < 4; i++) {
1502 if (gptParts[i] == MBR_EFI_GPT) {
1503 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1504 protectiveMBR.MakePart(i, 1, protectiveMBR.FindLastInFree(1), mbrTypes[i]);
1505 protectiveMBR.SetHybrid();
1506 } else {
1507 protectiveMBR.MakeBiggestPart(i, mbrTypes[i]);
1508 } // if/else
1509 } // if EFI GPT partition specified
1510 } // for (0xEE pass)
1511 } // if arrays were passed
1512 return numConverted;
1513} // GPTData::PartsToMBR()
1514
srs5694e4ac11e2009-08-31 10:13:04 -04001515
1516/**********************************************************************
1517 * *
1518 * Functions that adjust GPT data structures WITHOUT user interaction *
1519 * (they may display information for the user's benefit, though) *
1520 * *
1521 **********************************************************************/
1522
1523// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001524// necessary, copies data if it already exists. Returns 1 if all goes
1525// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001526int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001527 GPTPart* newParts;
1528 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001529 uint32_t i, high, copyNum;
1530 int allOK = 1;
1531
1532 // First, adjust numEntries upward, if necessary, to get a number
1533 // that fills the allocated sectors
1534 i = blockSize / GPT_SIZE;
1535 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001536 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001537 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001538 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001539 } // if
1540
srs5694247657a2009-11-26 18:36:12 -05001541 // Do the work only if the # of partitions is changing. Along with being
1542 // efficient, this prevents mucking the with location of the secondary
1543 // partition table, which causes problems when loading data from a RAID
1544 // array that's been expanded because this function is called when loading
1545 // data.
srs5694546a9c72010-01-26 16:00:26 -05001546 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1547 || (partitions == NULL)) {
srs5694cb76c672010-02-11 22:22:22 -05001548 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001549 if (newParts != NULL) {
1550 if (partitions != NULL) { // existing partitions; copy them over
1551 GetPartRange(&i, &high);
1552 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001553 cout << "The highest-numbered partition is " << high + 1
1554 << ", which is greater than the requested\n"
1555 << "partition table size of " << numEntries
1556 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001557 allOK = 0;
1558 } else { // go ahead with copy
1559 if (numEntries < mainHeader.numParts)
1560 copyNum = numEntries;
1561 else
1562 copyNum = mainHeader.numParts;
1563 for (i = 0; i < copyNum; i++) {
1564 newParts[i] = partitions[i];
1565 } // for
1566 trash = partitions;
1567 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001568 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001569 } // if
1570 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001571 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001572 } // if/else existing partitions
1573 mainHeader.numParts = numEntries;
1574 secondHeader.numParts = numEntries;
1575 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1576 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1577 MoveSecondHeaderToEnd();
1578 if (diskSize > 0)
1579 CheckGPTSize();
1580 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001581 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001582 allOK = 0;
1583 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001584 } // if/else
1585 return (allOK);
1586} // GPTData::SetGPTSize()
1587
1588// Blank the partition array
1589void GPTData::BlankPartitions(void) {
1590 uint32_t i;
1591
1592 for (i = 0; i < mainHeader.numParts; i++) {
1593 partitions[i].BlankPartition();
1594 } // for
1595} // GPTData::BlankPartitions()
1596
srs5694ba00fed2010-01-12 18:18:36 -05001597// Delete a partition by number. Returns 1 if successful,
1598// 0 if there was a problem. Returns 1 if partition was in
1599// range, 0 if it was out of range.
1600int GPTData::DeletePartition(uint32_t partNum) {
1601 uint64_t startSector, length;
1602 uint32_t low, high, numParts, retval = 1;;
1603
1604 numParts = GetPartRange(&low, &high);
1605 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1606 // In case there's a protective MBR, look for & delete matching
1607 // MBR partition....
1608 startSector = partitions[partNum].GetFirstLBA();
1609 length = partitions[partNum].GetLengthLBA();
1610 protectiveMBR.DeleteByLocation(startSector, length);
1611
1612 // Now delete the GPT partition
1613 partitions[partNum].BlankPartition();
1614 } else {
srs5694fed16d02010-01-27 23:03:40 -05001615 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001616 retval = 0;
1617 } // if/else
1618 return retval;
1619} // GPTData::DeletePartition(uint32_t partNum)
1620
srs569408bb0da2010-02-19 17:19:55 -05001621// Non-interactively create a partition.
1622// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001623uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001624 int retval = 1; // assume there'll be no problems
1625
1626 if (IsFreePartNum(partNum)) {
1627 Align(&startSector); // Align sector to correct multiple
1628 if (IsFree(startSector) && (startSector <= endSector)) {
1629 if (FindLastInFree(startSector) >= endSector) {
1630 partitions[partNum].SetFirstLBA(startSector);
1631 partitions[partNum].SetLastLBA(endSector);
1632 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001633 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001634 } else retval = 0; // if free space until endSector
1635 } else retval = 0; // if startSector is free
1636 } else retval = 0; // if legal partition number
1637 return retval;
1638} // GPTData::CreatePartition(partNum, startSector, endSector)
1639
srs5694e4ac11e2009-08-31 10:13:04 -04001640// Sort the GPT entries, eliminating gaps and making for a logical
1641// ordering. Relies on QuickSortGPT() for the bulk of the work
1642void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001643 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001644
1645 // First, find the last partition with data, so as not to
1646 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001647 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001648
1649 // Now swap empties with the last partitions, to simplify the logic
1650 // in the Quicksort function....
1651 i = 0;
1652 while (i < lastPart) {
1653 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001654 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001655 do {
1656 lastPart--;
1657 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001658 } // if
1659 i++;
1660 } // while
1661
srs5694546a9c72010-01-26 16:00:26 -05001662 // If there are more empties than partitions in the range from 0 to lastPart,
1663 // the above leaves lastPart set too high, so we've got to adjust it to
1664 // prevent empties from migrating to the top of the list....
1665 GetPartRange(&firstPart, &lastPart);
1666
srs5694e4ac11e2009-08-31 10:13:04 -04001667 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001668 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001669} // GPTData::SortGPT()
1670
srs569408bb0da2010-02-19 17:19:55 -05001671// Recursive quick sort algorithm for GPT partitions. Note that if there
1672// are any empties in the specified range, they'll be sorted to the
1673// start, resulting in a sorted set of partitions that begins with
1674// partition 2, 3, or higher.
1675void GPTData::QuickSortGPT(int start, int finish) {
1676 uint64_t starterValue; // starting location of median partition
1677 int left, right;
1678
1679 left = start;
1680 right = finish;
1681 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1682 do {
1683 while (partitions[left].GetFirstLBA() < starterValue)
1684 left++;
1685 while (partitions[right].GetFirstLBA() > starterValue)
1686 right--;
1687 if (left <= right)
1688 SwapPartitions(left++, right--);
1689 } while (left <= right);
1690 if (start < right) QuickSortGPT(start, right);
1691 if (finish > left) QuickSortGPT(left, finish);
1692} // GPTData::QuickSortGPT()
1693
1694// Swap the contents of two partitions.
1695// Returns 1 if successful, 0 if either partition is out of range
1696// (that is, not a legal number; either or both can be empty).
1697// Note that if partNum1 = partNum2 and this number is in range,
1698// it will be considered successful.
1699int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1700 GPTPart temp;
1701 int allOK = 1;
1702
1703 if ((partNum1 < mainHeader.numParts) && (partNum2 < mainHeader.numParts)) {
1704 if (partNum1 != partNum2) {
1705 temp = partitions[partNum1];
1706 partitions[partNum1] = partitions[partNum2];
1707 partitions[partNum2] = temp;
1708 } // if
1709 } else allOK = 0; // partition numbers are valid
1710 return allOK;
1711} // GPTData::SwapPartitions()
1712
srs5694e4ac11e2009-08-31 10:13:04 -04001713// Set up data structures for entirely new set of partitions on the
1714// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001715// Note that this function does NOT clear the protectiveMBR data
1716// structure, since it may hold the original MBR partitions if the
1717// program was launched on an MBR disk, and those may need to be
1718// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001719int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001720 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001721
1722 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001723 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001724 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001725 partitions = NULL;
1726 SetGPTSize(NUM_GPT_ENTRIES);
1727
1728 // Now initialize a bunch of stuff that's static....
1729 mainHeader.signature = GPT_SIGNATURE;
1730 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001731 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001732 mainHeader.reserved = 0;
1733 mainHeader.currentLBA = UINT64_C(1);
1734 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1735 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1736 for (i = 0; i < GPT_RESERVED; i++) {
1737 mainHeader.reserved2[i] = '\0';
1738 } // for
1739
1740 // Now some semi-static items (computed based on end of disk)
1741 mainHeader.backupLBA = diskSize - UINT64_C(1);
1742 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1743
1744 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001745 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001746
1747 // Copy main header to backup header
1748 RebuildSecondHeader();
1749
1750 // Blank out the partitions array....
1751 BlankPartitions();
1752
1753 // Flag all CRCs as being OK....
1754 mainCrcOk = 1;
1755 secondCrcOk = 1;
1756 mainPartsCrcOk = 1;
1757 secondPartsCrcOk = 1;
1758
1759 return (goOn);
1760} // GPTData::ClearGPTData()
1761
srs5694247657a2009-11-26 18:36:12 -05001762// Set the location of the second GPT header data to the end of the disk.
1763// Used internally and called by the 'e' option on the recovery &
1764// transformation menu, to help users of RAID arrays who add disk space
1765// to their arrays.
1766void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001767 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1768 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1769 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1770} // GPTData::FixSecondHeaderLocation()
1771
srs56940a697312010-01-28 21:10:52 -05001772int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001773 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001774
1775 if (!IsFreePartNum(partNum)) {
1776 partitions[partNum].SetName(theName);
1777 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001778
1779 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001780} // GPTData::SetName
1781
1782// Set the disk GUID to the specified value. Note that the header CRCs must
1783// be recomputed after calling this function.
1784void GPTData::SetDiskGUID(GUIDData newGUID) {
1785 mainHeader.diskGUID = newGUID;
1786 secondHeader.diskGUID = newGUID;
1787} // SetDiskGUID()
1788
1789// Set the unique GUID of the specified partition. Returns 1 on
1790// successful completion, 0 if there were problems (invalid
1791// partition number).
1792int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1793 int retval = 0;
1794
1795 if (pn < mainHeader.numParts) {
1796 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1797 partitions[pn].SetUniqueGUID(theGUID);
1798 retval = 1;
1799 } // if
1800 } // if
1801 return retval;
1802} // GPTData::SetPartitionGUID()
1803
srs5694ba00fed2010-01-12 18:18:36 -05001804// Change partition type code non-interactively. Returns 1 if
1805// successful, 0 if not....
1806int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1807 int retval = 1;
1808
1809 if (!IsFreePartNum(partNum)) {
1810 partitions[partNum].SetType(hexCode);
1811 } else retval = 0;
1812 return retval;
1813} // GPTData::ChangePartType()
1814
srs56941d1448a2009-12-31 21:20:19 -05001815// Adjust sector number so that it falls on a sector boundary that's a
1816// multiple of sectorAlignment. This is done to improve the performance
1817// of Western Digital Advanced Format disks and disks with similar
1818// technology from other companies, which use 4096-byte sectors
1819// internally although they translate to 512-byte sectors for the
1820// benefit of the OS. If partitions aren't properly aligned on these
1821// disks, some filesystem data structures can span multiple physical
1822// sectors, degrading performance. This function should be called
1823// only on the FIRST sector of the partition, not the last!
1824// This function returns 1 if the alignment was altered, 0 if it
1825// was unchanged.
1826int GPTData::Align(uint64_t* sector) {
1827 int retval = 0, sectorOK = 0;
1828 uint64_t earlier, later, testSector, original;
1829
1830 if ((*sector % sectorAlignment) != 0) {
1831 original = *sector;
1832 retval = 1;
1833 earlier = (*sector / sectorAlignment) * sectorAlignment;
1834 later = earlier + (uint64_t) sectorAlignment;
1835
1836 // Check to see that every sector between the earlier one and the
1837 // requested one is clear, and that it's not too early....
1838 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001839 sectorOK = 1;
1840 testSector = earlier;
1841 do {
1842 sectorOK = IsFree(testSector++);
1843 } while ((sectorOK == 1) && (testSector < *sector));
1844 if (sectorOK == 1) {
1845 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001846 } // if
1847 } // if firstUsableLBA check
1848
1849 // If couldn't move the sector earlier, try to move it later instead....
1850 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1851 sectorOK = 1;
1852 testSector = later;
1853 do {
1854 sectorOK = IsFree(testSector--);
1855 } while ((sectorOK == 1) && (testSector > *sector));
1856 if (sectorOK == 1) {
1857 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001858 } // if
1859 } // if
1860
1861 // If sector was changed successfully, inform the user of this fact.
1862 // Otherwise, notify the user that it couldn't be done....
1863 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001864 cout << "Information: Moved requested sector from " << original << " to "
1865 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001866 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001867 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001868 } else {
srs5694fed16d02010-01-27 23:03:40 -05001869 cout << "Information: Sector not aligned on " << sectorAlignment
1870 << "-sector boundary and could not be moved.\n"
1871 << "If you're using a Western Digital Advanced Format or similar disk with\n"
1872 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001873 retval = 0;
1874 } // if/else
1875 } // if
1876 return retval;
1877} // GPTData::Align()
1878
srs5694e4ac11e2009-08-31 10:13:04 -04001879/********************************************************
1880 * *
1881 * Functions that return data about GPT data structures *
1882 * (most of these are inline in gpt.h) *
1883 * *
1884 ********************************************************/
1885
1886// Find the low and high used partition numbers (numbered from 0).
1887// Return value is the number of partitions found. Note that the
1888// *low and *high values are both set to 0 when no partitions
1889// are found, as well as when a single partition in the first
1890// position exists. Thus, the return value is the only way to
1891// tell when no partitions exist.
1892int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1893 uint32_t i;
1894 int numFound = 0;
1895
1896 *low = mainHeader.numParts + 1; // code for "not found"
1897 *high = 0;
1898 if (mainHeader.numParts > 0) { // only try if partition table exists...
1899 for (i = 0; i < mainHeader.numParts; i++) {
1900 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1901 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001902 // Set the low value only if it's not yet found...
srs5694e4ac11e2009-08-31 10:13:04 -04001903 if (*low == (mainHeader.numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001904 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001905 } // if
1906 } // for
1907 } // if
1908
1909 // Above will leave *low pointing to its "not found" value if no partitions
1910 // are defined, so reset to 0 if this is the case....
1911 if (*low == (mainHeader.numParts + 1))
1912 *low = 0;
1913 return numFound;
1914} // GPTData::GetPartRange()
1915
srs569408bb0da2010-02-19 17:19:55 -05001916// Returns the value of the first free partition, or -1 if none is
1917// unused.
1918int GPTData::FindFirstFreePart(void) {
1919 int i = 0;
1920
1921 if (partitions != NULL) {
1922 while ((partitions[i].IsUsed()) && (i < (int) mainHeader.numParts))
1923 i++;
1924 if (i >= (int) mainHeader.numParts)
1925 i = -1;
1926 } else i = -1;
1927 return i;
1928} // GPTData::FindFirstFreePart()
1929
srs5694978041c2009-09-21 20:51:47 -04001930// Returns the number of defined partitions.
1931uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001932 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001933
1934 for (i = 0; i < mainHeader.numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001935 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001936 counted++;
1937 } // for
1938 return counted;
1939} // GPTData::CountParts()
1940
srs5694e4ac11e2009-08-31 10:13:04 -04001941/****************************************************
1942 * *
1943 * Functions that return data about disk free space *
1944 * *
1945 ****************************************************/
1946
1947// Find the first available block after the starting point; returns 0 if
1948// there are no available blocks left
1949uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1950 uint64_t first;
1951 uint32_t i;
1952 int firstMoved = 0;
1953
1954 // Begin from the specified starting point or from the first usable
1955 // LBA, whichever is greater...
1956 if (start < mainHeader.firstUsableLBA)
1957 first = mainHeader.firstUsableLBA;
1958 else
1959 first = start;
1960
1961 // ...now search through all partitions; if first is within an
1962 // existing partition, move it to the next sector after that
1963 // partition and repeat. If first was moved, set firstMoved
1964 // flag; repeat until firstMoved is not set, so as to catch
1965 // cases where partitions are out of sequential order....
1966 do {
1967 firstMoved = 0;
1968 for (i = 0; i < mainHeader.numParts; i++) {
1969 if ((first >= partitions[i].GetFirstLBA()) &&
1970 (first <= partitions[i].GetLastLBA())) { // in existing part.
1971 first = partitions[i].GetLastLBA() + 1;
1972 firstMoved = 1;
1973 } // if
1974 } // for
1975 } while (firstMoved == 1);
1976 if (first > mainHeader.lastUsableLBA)
1977 first = 0;
1978 return (first);
1979} // GPTData::FindFirstAvailable()
1980
1981// Finds the first available sector in the largest block of unallocated
1982// space on the disk. Returns 0 if there are no available blocks left
1983uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001984 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001985
1986 start = 0;
1987 do {
1988 firstBlock = FindFirstAvailable(start);
1989 if (firstBlock != UINT32_C(0)) { // something's free...
1990 lastBlock = FindLastInFree(firstBlock);
1991 segmentSize = lastBlock - firstBlock + UINT32_C(1);
1992 if (segmentSize > selectedSize) {
1993 selectedSize = segmentSize;
1994 selectedSegment = firstBlock;
1995 } // if
1996 start = lastBlock + 1;
1997 } // if
1998 } while (firstBlock != 0);
1999 return selectedSegment;
2000} // GPTData::FindFirstInLargest()
2001
srs5694cb76c672010-02-11 22:22:22 -05002002// Find the last available block on the disk.
2003// Returns 0 if there are no available partitions
2004uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002005 uint64_t last;
2006 uint32_t i;
2007 int lastMoved = 0;
2008
2009 // Start by assuming the last usable LBA is available....
2010 last = mainHeader.lastUsableLBA;
2011
2012 // ...now, similar to algorithm in FindFirstAvailable(), search
2013 // through all partitions, moving last when it's in an existing
2014 // partition. Set the lastMoved flag so we repeat to catch cases
2015 // where partitions are out of logical order.
2016 do {
2017 lastMoved = 0;
2018 for (i = 0; i < mainHeader.numParts; i++) {
2019 if ((last >= partitions[i].GetFirstLBA()) &&
2020 (last <= partitions[i].GetLastLBA())) { // in existing part.
2021 last = partitions[i].GetFirstLBA() - 1;
2022 lastMoved = 1;
2023 } // if
2024 } // for
2025 } while (lastMoved == 1);
2026 if (last < mainHeader.firstUsableLBA)
2027 last = 0;
2028 return (last);
2029} // GPTData::FindLastAvailable()
2030
2031// Find the last available block in the free space pointed to by start.
2032uint64_t GPTData::FindLastInFree(uint64_t start) {
2033 uint64_t nearestStart;
2034 uint32_t i;
2035
2036 nearestStart = mainHeader.lastUsableLBA;
2037 for (i = 0; i < mainHeader.numParts; i++) {
2038 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2039 (partitions[i].GetFirstLBA() > start)) {
2040 nearestStart = partitions[i].GetFirstLBA() - 1;
2041 } // if
2042 } // for
2043 return (nearestStart);
2044} // GPTData::FindLastInFree()
2045
2046// Finds the total number of free blocks, the number of segments in which
2047// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002048uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002049 uint64_t start = UINT64_C(0); // starting point for each search
2050 uint64_t totalFound = UINT64_C(0); // running total
2051 uint64_t firstBlock; // first block in a segment
2052 uint64_t lastBlock; // last block in a segment
2053 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002054 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002055
2056 *largestSegment = UINT64_C(0);
2057 do {
2058 firstBlock = FindFirstAvailable(start);
2059 if (firstBlock != UINT64_C(0)) { // something's free...
2060 lastBlock = FindLastInFree(firstBlock);
2061 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2062 if (segmentSize > *largestSegment) {
2063 *largestSegment = segmentSize;
2064 } // if
2065 totalFound += segmentSize;
2066 num++;
2067 start = lastBlock + 1;
2068 } // if
2069 } while (firstBlock != 0);
2070 *numSegments = num;
2071 return totalFound;
2072} // GPTData::FindFreeBlocks()
2073
2074// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2075int GPTData::IsFree(uint64_t sector) {
2076 int isFree = 1;
2077 uint32_t i;
2078
2079 for (i = 0; i < mainHeader.numParts; i++) {
2080 if ((sector >= partitions[i].GetFirstLBA()) &&
2081 (sector <= partitions[i].GetLastLBA())) {
2082 isFree = 0;
srs569408bb0da2010-02-19 17:19:55 -05002083 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002084 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002085 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002086 (sector > mainHeader.lastUsableLBA)) {
2087 isFree = 0;
srs569408bb0da2010-02-19 17:19:55 -05002088 } // if
2089 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002090} // GPTData::IsFree()
2091
srs5694ba00fed2010-01-12 18:18:36 -05002092// Returns 1 if partNum is unused.
2093int GPTData::IsFreePartNum(uint32_t partNum) {
2094 int retval = 1;
2095
srs569408bb0da2010-02-19 17:19:55 -05002096 if ((partNum < mainHeader.numParts) && (partitions != NULL)) {
2097 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002098 retval = 0;
2099 } // if partition is in use
2100 } else retval = 0;
2101
2102 return retval;
2103} // GPTData::IsFreePartNum()
2104
srs5694e4ac11e2009-08-31 10:13:04 -04002105/********************************
2106 * *
2107 * Endianness support functions *
2108 * *
2109 ********************************/
2110
srs56942a9f5da2009-08-26 00:48:01 -04002111void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002112 ReverseBytes(&header->signature, 8);
2113 ReverseBytes(&header->revision, 4);
2114 ReverseBytes(&header->headerSize, 4);
2115 ReverseBytes(&header->headerCRC, 4);
2116 ReverseBytes(&header->reserved, 4);
2117 ReverseBytes(&header->currentLBA, 8);
2118 ReverseBytes(&header->backupLBA, 8);
2119 ReverseBytes(&header->firstUsableLBA, 8);
2120 ReverseBytes(&header->lastUsableLBA, 8);
2121 ReverseBytes(&header->partitionEntriesLBA, 8);
2122 ReverseBytes(&header->numParts, 4);
2123 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2124 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002125 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002126} // GPTData::ReverseHeaderBytes()
2127
2128// IMPORTANT NOTE: This function requires non-reversed mainHeader
2129// structure!
2130void GPTData::ReversePartitionBytes() {
2131 uint32_t i;
2132
2133 // Check GPT signature on big-endian systems; this will mismatch
2134 // if the function is called out of order. Unfortunately, it'll also
2135 // mismatch if there's data corruption.
2136 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002137 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2138 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002139 } // if signature mismatch....
2140 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002141 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002142 } // for
2143} // GPTData::ReversePartitionBytes()
2144
2145/******************************************
2146 * *
2147 * Additional non-class support functions *
2148 * *
2149 ******************************************/
2150
srs5694e7b4ff92009-08-18 13:16:10 -04002151// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2152// never fail these tests, but the struct types may fail depending on compile options.
2153// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2154// sizes.
2155int SizesOK(void) {
2156 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002157
2158 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002159 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002160 allOK = 0;
2161 } // if
2162 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002163 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002164 allOK = 0;
2165 } // if
2166 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002167 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002168 allOK = 0;
2169 } // if
2170 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002171 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002172 allOK = 0;
2173 } // if
2174 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002175 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002176 allOK = 0;
2177 } // if
srs5694978041c2009-09-21 20:51:47 -04002178 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002179 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002180 allOK = 0;
2181 } // if
2182 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002183 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002184 allOK = 0;
2185 } // if
srs5694221e0872009-08-29 15:00:31 -04002186 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002187 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002188 allOK = 0;
2189 } // if
srs56946699b012010-02-04 00:55:30 -05002190 if (sizeof(GUIDData) != 16) {
2191 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2192 allOK = 0;
2193 } // if
2194 if (sizeof(PartType) != 16) {
2195 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2196 allOK = 0;
2197 } // if
srs5694fed16d02010-01-27 23:03:40 -05002198 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002199 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002200 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2201 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002202 } // if
2203 return (allOK);
2204} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002205