blob: e2132053fba665536d08ada3eecaa1ac8ef5a52d [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;
srs56941c6f8b02010-02-21 11:09:20 -0500760 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500761
762 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500763 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500764 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
765 allOK = 0;
766 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500767 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500768
srs56941c6f8b02010-02-21 11:09:20 -0500769 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500770 if (IsLittleEndian() == 0) {
771 ReverseHeaderBytes(header);
772 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500773
774 if (allOK && mainHeader.numParts != tempHeader.numParts)
775 allOK = SetGPTSize(tempHeader.numParts);
776
777 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500778 return allOK;
779} // GPTData::LoadHeader
780
781// Load a partition table (either main or secondary) from the specified disk,
782// using header as a reference for what to load. If sector != 0 (the default
783// is 0), loads from the specified sector; otherwise loads from the sector
784// indicated in header.
785// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
786int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
787 uint32_t sizeOfParts, newCRC;
788 int retval;
789
790 if (disk.OpenForRead()) {
791 if (sector == 0) {
792 retval = disk.Seek(header.partitionEntriesLBA);
793 } else {
794 retval = disk.Seek(sector);
795 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500796 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500797 SetGPTSize(header.numParts);
798 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
799 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500800 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500801 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500802 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400803 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500804 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400805 if (IsLittleEndian() == 0)
806 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500807 if (!mainPartsCrcOk) {
808 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400809 } // if
810 } else {
srs5694cb76c672010-02-11 22:22:22 -0500811 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400812 } // if/else
813 } else {
srs5694fed16d02010-01-27 23:03:40 -0500814 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500815 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500816 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400817 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500818 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500819} // GPTData::LoadPartitionsTable()
820
821// Check the partition table pointed to by header, but don't keep it
822// around.
823// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
824int GPTData::CheckTable(struct GPTHeader *header) {
825 uint32_t sizeOfParts, newCRC;
826 uint8_t *storage;
827 int newCrcOk = 0;
828
829 // Load backup partition table into temporary storage to check
830 // its CRC and store the results, then discard this temporary
831 // storage, since we don't use it in any but recovery operations
832 if (myDisk.Seek(header->partitionEntriesLBA)) {
833 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
834 storage = new uint8_t[sizeOfParts];
835 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
836 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
837 } else {
838 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
839 newCrcOk = (newCRC == header->partitionEntriesCRC);
840 } // if/else
841 delete[] storage;
842 } // if
843 return newCrcOk;
844} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400845
srs5694e7b4ff92009-08-18 13:16:10 -0400846// Writes GPT (and protective MBR) to disk. Returns 1 on successful
847// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500848int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500849 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500850 char answer;
srs56942a9f5da2009-08-26 00:48:01 -0400851 uint32_t numParts;
srs5694e7b4ff92009-08-18 13:16:10 -0400852
srs56946699b012010-02-04 00:55:30 -0500853 littleEndian = IsLittleEndian();
854
srs5694fed16d02010-01-27 23:03:40 -0500855 if (device == "") {
856 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400857 } // if
858
859 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500860
861 // This test should only fail on read-only disks....
862 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500863 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500864 allOK = 0;
865 } // if
866
srs5694e7b4ff92009-08-18 13:16:10 -0400867 // Is there enough space to hold the GPT headers and partition tables,
868 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400869 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400870 allOK = 0;
871 } // if
872
873 // Check that disk is really big enough to handle this...
874 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500875 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
876 << "problem (or it might not). Aborting!\n(Disk size is "
877 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400878 allOK = 0;
879 } // if
srs5694247657a2009-11-26 18:36:12 -0500880 // Check that second header is properly placed. Warn and ask if this should
881 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500882 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500883 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
884 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500885 if (GetYN() == 'Y') {
886 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500887 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500888 } else {
srs5694fed16d02010-01-27 23:03:40 -0500889 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500890 } // if correction requested
891 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400892
893 // Check for overlapping partitions....
srs5694e4ac11e2009-08-31 10:13:04 -0400894 if (FindOverlaps() > 0) {
895 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500896 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400897 } // if
898
899 // Check for mismatched MBR and GPT data, but let it pass if found
900 // (function displays warning message)
901 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400902
srs56942a9f5da2009-08-26 00:48:01 -0400903 // Pull out some data that's needed before doing byte-order reversal on
904 // big-endian systems....
905 numParts = mainHeader.numParts;
srs5694cb76c672010-02-11 22:22:22 -0500906
srs5694e7b4ff92009-08-18 13:16:10 -0400907 RecomputeCRCs();
908
srs5694ba00fed2010-01-12 18:18:36 -0500909 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500910 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
911 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500912 answer = GetYN();
913 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500914 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400915 } else {
916 allOK = 0;
917 } // if/else
918 } // if
919
920 // Do it!
921 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500922 // First, write the protective MBR...
923 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400924
srs5694546a9c72010-01-26 16:00:26 -0500925 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400926 // Now write the main GPT header...
srs5694cb76c672010-02-11 22:22:22 -0500927 allOK = SaveHeader(&mainHeader, myDisk, 1);
srs5694e7b4ff92009-08-18 13:16:10 -0400928
929 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400930 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500931 allOK = SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
srs56941e093722010-01-05 00:14:19 -0500932 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400933
934 // Now seek to near the end to write the secondary GPT....
srs5694cb76c672010-02-11 22:22:22 -0500935 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
936 if (!allOK)
937 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
938 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400939
940 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500941 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500942 allOK = SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
srs56946699b012010-02-04 00:55:30 -0500943 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400944
945 // re-read the partition table
946 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500947 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400948 } // if
949
950 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500951 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400952 } else {
srs5694fed16d02010-01-27 23:03:40 -0500953 cerr << "Warning! An error was reported when writing the partition table! This error\n"
954 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
955 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400956 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500957 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400958 } else {
srs5694fed16d02010-01-27 23:03:40 -0500959 cerr << "Unable to open device " << device << " for writing! Errno is "
960 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400961 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400962 } // if/else
963 } else {
srs5694fed16d02010-01-27 23:03:40 -0500964 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } // if
966
967 return (allOK);
968} // GPTData::SaveGPTData()
969
970// Save GPT data to a backup file. This function does much less error
971// checking than SaveGPTData(). It can therefore preserve many types of
972// corruption for later analysis; however, it preserves only the MBR,
973// the main GPT header, the backup GPT header, and the main partition
974// table; it discards the backup partition table, since it should be
975// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500976int GPTData::SaveGPTBackup(const string & filename) {
977 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500978 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400979
srs5694546a9c72010-01-26 16:00:26 -0500980 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500981 // Recomputing the CRCs is likely to alter them, which could be bad
982 // if the intent is to save a potentially bad GPT for later analysis;
983 // but if we don't do this, we get bogus errors when we load the
984 // backup. I'm favoring misses over false alarms....
985 RecomputeCRCs();
986
srs5694546a9c72010-01-26 16:00:26 -0500987 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400988
srs5694cb76c672010-02-11 22:22:22 -0500989 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500990 // MBR write closed disk, so re-open and seek to end....
991 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500992 allOK = SaveHeader(&mainHeader, backupFile, 1);
993 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400994
srs5694e7b4ff92009-08-18 13:16:10 -0400995 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -0500996 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -0400997
srs5694cb76c672010-02-11 22:22:22 -0500998 if (allOK)
999 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001000
1001 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001002 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001003 } else {
srs5694fed16d02010-01-27 23:03:40 -05001004 cerr << "Warning! An error was reported when writing the backup file.\n"
1005 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001006 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001007 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001008 } else {
srs5694fed16d02010-01-27 23:03:40 -05001009 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001010 allOK = 0;
1011 } // if/else
1012 return allOK;
1013} // GPTData::SaveGPTBackup()
1014
srs5694cb76c672010-02-11 22:22:22 -05001015// Write a GPT header (main or backup) to the specified sector. Used by both
1016// the SaveGPTData() and SaveGPTBackup() functions.
1017// Should be passed an architecture-appropriate header (DO NOT call
1018// ReverseHeaderBytes() on the header before calling this function)
1019// Returns 1 on success, 0 on failure
1020int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1021 int littleEndian, allOK = 1;
1022
1023 littleEndian = IsLittleEndian();
1024 if (!littleEndian)
1025 ReverseHeaderBytes(header);
1026 if (disk.Seek(sector)) {
1027 if (disk.Write(header, 512) == -1)
1028 allOK = 0;
1029 } else allOK = 0; // if (disk.Seek()...)
1030 if (!littleEndian)
1031 ReverseHeaderBytes(header);
1032 return allOK;
1033} // GPTData::SaveHeader()
1034
1035// Save the partitions to the specified sector. Used by both the SaveGPTData()
1036// and SaveGPTBackup() functions.
1037// Should be passed an architecture-appropriate header (DO NOT call
1038// ReverseHeaderBytes() on the header before calling this function)
1039// Returns 1 on success, 0 on failure
1040int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1041 int littleEndian, allOK = 1;
1042
1043 littleEndian = IsLittleEndian();
1044 if (disk.Seek(sector)) {
1045 if (!littleEndian)
1046 ReversePartitionBytes();
1047 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1048 allOK = 0;
1049 if (!littleEndian)
1050 ReversePartitionBytes();
1051 } else allOK = 0; // if (myDisk.Seek()...)
1052 return allOK;
1053} // GPTData::SavePartitionTable()
1054
srs5694e7b4ff92009-08-18 13:16:10 -04001055// Load GPT data from a backup file created by SaveGPTBackup(). This function
1056// does minimal error checking. It returns 1 if it completed successfully,
1057// 0 if there was a problem. In the latter case, it creates a new empty
1058// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001059int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001060 int allOK = 1, val, err;
1061 uint32_t numParts, sizeOfEntries;
1062 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001063 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001064
srs5694546a9c72010-01-26 16:00:26 -05001065 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001066 if (IsLittleEndian() == 0)
1067 littleEndian = 0;
1068
srs5694e7b4ff92009-08-18 13:16:10 -04001069 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001070 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001071
srs5694cb76c672010-02-11 22:22:22 -05001072 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001073
srs5694cb76c672010-02-11 22:22:22 -05001074 // Check backup file size and rebuild second header if file is right
1075 // size to be direct dd copy of MBR, main header, and main partition
1076 // table; if other size, treat it like a GPT fdisk-generated backup
1077 // file
1078 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1079 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1080 if (shortBackup) {
1081 RebuildSecondHeader();
1082 secondCrcOk = mainCrcOk;
1083 } else {
1084 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1085 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001086
srs5694e7b4ff92009-08-18 13:16:10 -04001087 // Return valid headers code: 0 = both headers bad; 1 = main header
1088 // good, backup bad; 2 = backup header good, main header bad;
1089 // 3 = both headers good. Note these codes refer to valid GPT
1090 // signatures and version numbers; more subtle problems will elude
1091 // this check!
1092 if ((val = CheckHeaderValidity()) > 0) {
1093 if (val == 2) { // only backup header seems to be good
1094 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001095 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001096 } else { // main header is OK
1097 numParts = mainHeader.numParts;
1098 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1099 } // if/else
1100
1101 SetGPTSize(numParts);
1102
srs5694e7b4ff92009-08-18 13:16:10 -04001103 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001104 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1105 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001106 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001107 } // if
1108
srs5694cb76c672010-02-11 22:22:22 -05001109 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1110 cerr << "Warning! Read error " << errno
1111 << " loading partition table; strange behavior now likely!\n";
srs56942a9f5da2009-08-26 00:48:01 -04001112
srs5694e7b4ff92009-08-18 13:16:10 -04001113 } else {
1114 allOK = 0;
1115 } // if/else
1116 } else {
1117 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001118 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001119 } // if/else
1120
1121 // Something went badly wrong, so blank out partitions
1122 if (allOK == 0) {
1123 ClearGPTData();
1124 protectiveMBR.MakeProtectiveMBR();
1125 } // if
1126 return allOK;
1127} // GPTData::LoadGPTBackup()
1128
srs569408bb0da2010-02-19 17:19:55 -05001129int GPTData::SaveMBR(void) {
1130 return protectiveMBR.WriteMBRData();
1131} // GPTData::SaveMBR()
1132
1133// This function destroys the on-disk GPT structures, but NOT the on-disk
1134// MBR.
1135// Returns 1 if the operation succeeds, 0 if not.
1136int GPTData::DestroyGPT(void) {
1137 int i, sum, tableSize, allOK = 1;
1138 uint8_t blankSector[512];
1139 uint8_t* emptyTable;
1140
1141 for (i = 0; i < 512; i++) {
1142 blankSector[i] = 0;
1143 } // for
1144
1145 if (myDisk.OpenForWrite()) {
1146 if (!myDisk.Seek(mainHeader.currentLBA))
1147 allOK = 0;
1148 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1149 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1150 allOK = 0;
1151 } // if
1152 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1153 allOK = 0;
1154 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
1155 emptyTable = new uint8_t[tableSize];
1156 for (i = 0; i < tableSize; i++)
1157 emptyTable[i] = 0;
1158 if (allOK) {
1159 sum = myDisk.Write(emptyTable, tableSize);
1160 if (sum != tableSize) {
1161 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1162 allOK = 0;
1163 } // if write failed
1164 } // if
1165 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1166 allOK = 0;
1167 if (allOK) {
1168 sum = myDisk.Write(emptyTable, tableSize);
1169 if (sum != tableSize) {
1170 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1171 << errno << "\n";
1172 allOK = 0;
1173 } // if wrong size written
1174 } // if
1175 if (!myDisk.Seek(secondHeader.currentLBA))
1176 allOK = 0;
1177 if (allOK) {
1178 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1179 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1180 allOK = 0;
1181 } // if
1182 } // if
1183 myDisk.DiskSync();
1184 myDisk.Close();
1185 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1186 << "other utilities.\n";
1187 delete[] emptyTable;
1188 } else {
1189 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1190 } // if/else (fd != -1)
1191 return (allOK);
1192} // GPTDataTextUI::DestroyGPT()
1193
1194// Wipe MBR data from the disk (zero it out completely)
1195// Returns 1 on success, 0 on failure.
1196int GPTData::DestroyMBR(void) {
1197 int allOK = 1, i;
1198 uint8_t blankSector[512];
1199
1200 for (i = 0; i < 512; i++)
1201 blankSector[i] = 0;
1202
1203 if (myDisk.OpenForWrite()) {
1204 if (myDisk.Seek(0)) {
1205 if (myDisk.Write(blankSector, 512) != 512)
1206 allOK = 0;
1207 } else allOK = 0;
1208 } else allOK = 0;
1209 if (!allOK)
1210 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1211 return allOK;
1212} // GPTData::DestroyMBR(void)
1213
srs5694e4ac11e2009-08-31 10:13:04 -04001214// Tell user whether Apple Partition Map (APM) was discovered....
1215void GPTData::ShowAPMState(void) {
1216 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001217 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001218 else
srs5694fed16d02010-01-27 23:03:40 -05001219 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001220} // GPTData::ShowAPMState()
1221
1222// Tell user about the state of the GPT data....
1223void GPTData::ShowGPTState(void) {
1224 switch (state) {
1225 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001227 break;
1228 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001229 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001230 break;
1231 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001232 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001233 break;
1234 default:
srs5694fed16d02010-01-27 23:03:40 -05001235 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001236 break;
1237 } // switch
1238} // GPTData::ShowGPTState()
1239
1240// Display the basic GPT data
1241void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001242 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001243 uint64_t temp, totalFree;
1244
srs5694fed16d02010-01-27 23:03:40 -05001245 cout << "Disk " << device << ": " << diskSize << " sectors, "
1246 << BytesToSI(diskSize * blockSize) << "\n";
1247 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001248 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1250 cout << "First usable sector is " << mainHeader.firstUsableLBA
1251 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001252 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001253 cout << "Total free space is " << totalFree << " sectors ("
1254 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1255 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001256 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001257 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001258 } // for
1259} // GPTData::DisplayGPTData()
1260
srs5694e4ac11e2009-08-31 10:13:04 -04001261// Show detailed information on the specified partition
1262void GPTData::ShowPartDetails(uint32_t partNum) {
1263 if (partitions[partNum].GetFirstLBA() != 0) {
1264 partitions[partNum].ShowDetails(blockSize);
1265 } else {
srs5694fed16d02010-01-27 23:03:40 -05001266 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001267 } // if
1268} // GPTData::ShowPartDetails()
1269
srs5694e4ac11e2009-08-31 10:13:04 -04001270/**************************************************************************
1271 * *
1272 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1273 * (some of these functions may require user interaction) *
1274 * *
1275 **************************************************************************/
1276
srs569408bb0da2010-02-19 17:19:55 -05001277// Examines the MBR & GPT data to determine which set of data to use: the
1278// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1279// a new set of partitions (use_new). A return value of use_abort indicates
1280// that this function couldn't determine what to do. Overriding functions
1281// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001282WhichToUse GPTData::UseWhichPartitions(void) {
1283 WhichToUse which = use_new;
1284 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001285
1286 mbrState = protectiveMBR.GetValidity();
1287
1288 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001289 cout << "\n***************************************************************\n"
1290 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001291 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001292 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1293 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001294 } // if
srs5694fed16d02010-01-27 23:03:40 -05001295 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001296 which = use_mbr;
1297 } // if
1298
1299 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001300 cout << "\n**********************************************************************\n"
1301 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1302 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001303 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001304 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1305 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1306 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001307 } // if
srs5694fed16d02010-01-27 23:03:40 -05001308 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001309 which = use_bsd;
1310 } // if
1311
1312 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001313 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001314 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001315 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001316 } // if
1317 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001318 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001319 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001320 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001321 } // if
1322 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001323 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001324 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001325 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001326 } // if
1327 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001328 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001329 } // if
1330
srs5694e4ac11e2009-08-31 10:13:04 -04001331 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001332 if (mbrState == gpt) {
1333 cout << "\a\a****************************************************************************\n"
1334 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1335 << "verification and recovery are STRONGLY recommended.\n"
1336 << "****************************************************************************\n";
1337 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001338 } else {
srs569408bb0da2010-02-19 17:19:55 -05001339 which = use_abort;
1340 } // if/else MBR says disk is GPT
1341 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001342
1343 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001344 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001345
1346 return which;
1347} // UseWhichPartitions()
1348
srs569408bb0da2010-02-19 17:19:55 -05001349// Convert MBR partition table into GPT form.
1350void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001351 int i, numToConvert;
1352 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001353
1354 // Clear out old data & prepare basics....
1355 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001356 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001357
1358 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001359 if (mainHeader.numParts > (MAX_MBR_PARTS))
1360 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001361 else
1362 numToConvert = mainHeader.numParts;
1363
1364 for (i = 0; i < numToConvert; i++) {
1365 origType = protectiveMBR.GetType(i);
1366 // don't waste CPU time trying to convert extended, hybrid protective, or
1367 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001368 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001369 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001370 partitions[i] = protectiveMBR.AsGPT(i);
1371 } // for
1372
1373 // Convert MBR into protective MBR
1374 protectiveMBR.MakeProtectiveMBR();
1375
1376 // Record that all original CRCs were OK so as not to raise flags
1377 // when doing a disk verification
1378 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001379} // GPTData::XFormPartitions()
1380
1381// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001382// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001383// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001384int GPTData::XFormDisklabel(uint32_t partNum) {
1385 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001386 int goOn = 1, numDone = 0;
1387 BSDData disklabel;
1388
srs569408bb0da2010-02-19 17:19:55 -05001389 if (GetPartRange(&low, &high) == 0) {
1390 goOn = 0;
1391 cout << "No partitions!\n";
1392 } // if
1393 if (partNum > high) {
1394 goOn = 0;
1395 cout << "Specified partition is invalid!\n";
1396 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001397
srs569408bb0da2010-02-19 17:19:55 -05001398 // If all is OK, read the disklabel and convert it.
1399 if (goOn) {
1400 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1401 partitions[partNum].GetLastLBA());
1402 if ((goOn) && (disklabel.IsDisklabel())) {
1403 numDone = XFormDisklabel(&disklabel);
1404 if (numDone == 1)
1405 cout << "Converted 1 BSD partition.\n";
1406 else
1407 cout << "Converted " << numDone << " BSD partitions.\n";
1408 } else {
1409 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1410 } // if/else
1411 } // if
1412 if (numDone > 0) { // converted partitions; delete carrier
1413 partitions[partNum].BlankPartition();
1414 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001415 return numDone;
1416} // GPTData::XFormDisklable(int i)
1417
1418// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001419int GPTData::XFormDisklabel(BSDData* disklabel) {
1420 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001421
srs569408bb0da2010-02-19 17:19:55 -05001422 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001423 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001424 partNum = FindFirstFreePart();
1425 if (partNum >= 0) {
1426 partitions[partNum] = disklabel->AsGPT(i);
1427 if (partitions[partNum].IsUsed())
1428 numDone++;
1429 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001430 } // for
srs569408bb0da2010-02-19 17:19:55 -05001431 if (partNum == -1)
1432 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001433 } // if
1434
1435 // Record that all original CRCs were OK so as not to raise flags
1436 // when doing a disk verification
1437 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1438
1439 return numDone;
1440} // GPTData::XFormDisklabel(BSDData* disklabel)
1441
srs569408bb0da2010-02-19 17:19:55 -05001442// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1443// partition has the active/bootable flag UNset and uses the GPT fdisk
1444// type code divided by 0x0100 as the MBR type code.
1445// Returns 1 if operation was 100% successful, 0 if there were ANY
1446// problems.
srs5694978041c2009-09-21 20:51:47 -04001447int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001448 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001449
srs5694978041c2009-09-21 20:51:47 -04001450 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001451 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001452 allOK = 0;
1453 } // if
1454 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001455 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001456 allOK = 0;
1457 } // if
1458 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001459 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001460 allOK = 0;
1461 } // if
1462 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1463 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1464 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001465 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1466 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001467 } // if
srs5694978041c2009-09-21 20:51:47 -04001468 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001469 (uint32_t) partitions[gptPart].GetLengthLBA(),
1470 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001471 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001472 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1473 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1474 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001475 allOK = 0;
1476 } // if/else
1477 return allOK;
1478} // GPTData::OnePartToMBR()
1479
srs569408bb0da2010-02-19 17:19:55 -05001480// Convert up to four partitions to MBR form and return the number done.
1481// Partitions are specified in an array of GPT partition numbers,
1482// with an associated array of partition type codes. Both must be
1483// at least four elements in size (longer is OK, but will be ignored).
1484// A partition number of MBR_EFI_GPT means to place an EFI GPT
1485// protective partition in that location in the table (the associated
1486// mbrType[] should be 0xEE), and MBR_EMPTY means not to create a
1487// partition in that table position. If the mbrType[] entry for a
1488// partition is 0, a default entry is used, based on the GPT
1489// partition type code.
1490// Returns the number of partitions converted, NOT counting EFI GPT
1491// protective partitions.
1492int GPTData::PartsToMBR(const int *gptParts, const int *mbrTypes) {
1493 int i, numConverted = 0;
srs5694978041c2009-09-21 20:51:47 -04001494
srs569408bb0da2010-02-19 17:19:55 -05001495 if ((gptParts != NULL) && (mbrTypes != NULL)) {
1496 protectiveMBR.EmptyMBR();
srs5694e4ac11e2009-08-31 10:13:04 -04001497 protectiveMBR.SetDiskSize(diskSize);
srs569408bb0da2010-02-19 17:19:55 -05001498 // Do two passes, one to get "real" partitions and
1499 // the next to create EFI GPT protective partition(s)
srs5694e4ac11e2009-08-31 10:13:04 -04001500 for (i = 0; i < 4; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001501 if (gptParts[i] >= 0) {
1502 numConverted += OnePartToMBR((uint32_t) gptParts[i], i);
1503 if (mbrTypes[i] != 0)
1504 protectiveMBR.SetPartType(i, mbrTypes[i]);
1505 } // if
1506 } // for (regular partition pass)
1507 for (i = 0; i < 4; i++) {
1508 if (gptParts[i] == MBR_EFI_GPT) {
1509 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1510 protectiveMBR.MakePart(i, 1, protectiveMBR.FindLastInFree(1), mbrTypes[i]);
1511 protectiveMBR.SetHybrid();
1512 } else {
1513 protectiveMBR.MakeBiggestPart(i, mbrTypes[i]);
1514 } // if/else
1515 } // if EFI GPT partition specified
1516 } // for (0xEE pass)
1517 } // if arrays were passed
1518 return numConverted;
1519} // GPTData::PartsToMBR()
1520
srs5694e4ac11e2009-08-31 10:13:04 -04001521
1522/**********************************************************************
1523 * *
1524 * Functions that adjust GPT data structures WITHOUT user interaction *
1525 * (they may display information for the user's benefit, though) *
1526 * *
1527 **********************************************************************/
1528
1529// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001530// necessary, copies data if it already exists. Returns 1 if all goes
1531// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001532int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001533 GPTPart* newParts;
1534 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001535 uint32_t i, high, copyNum;
1536 int allOK = 1;
1537
1538 // First, adjust numEntries upward, if necessary, to get a number
1539 // that fills the allocated sectors
1540 i = blockSize / GPT_SIZE;
1541 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001542 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001543 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001544 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001545 } // if
1546
srs5694247657a2009-11-26 18:36:12 -05001547 // Do the work only if the # of partitions is changing. Along with being
1548 // efficient, this prevents mucking the with location of the secondary
1549 // partition table, which causes problems when loading data from a RAID
1550 // array that's been expanded because this function is called when loading
1551 // data.
srs5694546a9c72010-01-26 16:00:26 -05001552 if ((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1553 || (partitions == NULL)) {
srs5694cb76c672010-02-11 22:22:22 -05001554 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001555 if (newParts != NULL) {
1556 if (partitions != NULL) { // existing partitions; copy them over
1557 GetPartRange(&i, &high);
1558 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001559 cout << "The highest-numbered partition is " << high + 1
1560 << ", which is greater than the requested\n"
1561 << "partition table size of " << numEntries
1562 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001563 allOK = 0;
1564 } else { // go ahead with copy
1565 if (numEntries < mainHeader.numParts)
1566 copyNum = numEntries;
1567 else
1568 copyNum = mainHeader.numParts;
1569 for (i = 0; i < copyNum; i++) {
1570 newParts[i] = partitions[i];
1571 } // for
1572 trash = partitions;
1573 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001574 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001575 } // if
1576 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001577 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001578 } // if/else existing partitions
1579 mainHeader.numParts = numEntries;
1580 secondHeader.numParts = numEntries;
1581 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1582 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1583 MoveSecondHeaderToEnd();
1584 if (diskSize > 0)
1585 CheckGPTSize();
1586 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001587 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001588 allOK = 0;
1589 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001590 } // if/else
1591 return (allOK);
1592} // GPTData::SetGPTSize()
1593
1594// Blank the partition array
1595void GPTData::BlankPartitions(void) {
1596 uint32_t i;
1597
1598 for (i = 0; i < mainHeader.numParts; i++) {
1599 partitions[i].BlankPartition();
1600 } // for
1601} // GPTData::BlankPartitions()
1602
srs5694ba00fed2010-01-12 18:18:36 -05001603// Delete a partition by number. Returns 1 if successful,
1604// 0 if there was a problem. Returns 1 if partition was in
1605// range, 0 if it was out of range.
1606int GPTData::DeletePartition(uint32_t partNum) {
1607 uint64_t startSector, length;
1608 uint32_t low, high, numParts, retval = 1;;
1609
1610 numParts = GetPartRange(&low, &high);
1611 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1612 // In case there's a protective MBR, look for & delete matching
1613 // MBR partition....
1614 startSector = partitions[partNum].GetFirstLBA();
1615 length = partitions[partNum].GetLengthLBA();
1616 protectiveMBR.DeleteByLocation(startSector, length);
1617
1618 // Now delete the GPT partition
1619 partitions[partNum].BlankPartition();
1620 } else {
srs5694fed16d02010-01-27 23:03:40 -05001621 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001622 retval = 0;
1623 } // if/else
1624 return retval;
1625} // GPTData::DeletePartition(uint32_t partNum)
1626
srs569408bb0da2010-02-19 17:19:55 -05001627// Non-interactively create a partition.
1628// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001629uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001630 int retval = 1; // assume there'll be no problems
1631
1632 if (IsFreePartNum(partNum)) {
1633 Align(&startSector); // Align sector to correct multiple
1634 if (IsFree(startSector) && (startSector <= endSector)) {
1635 if (FindLastInFree(startSector) >= endSector) {
1636 partitions[partNum].SetFirstLBA(startSector);
1637 partitions[partNum].SetLastLBA(endSector);
1638 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001639 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001640 } else retval = 0; // if free space until endSector
1641 } else retval = 0; // if startSector is free
1642 } else retval = 0; // if legal partition number
1643 return retval;
1644} // GPTData::CreatePartition(partNum, startSector, endSector)
1645
srs5694e4ac11e2009-08-31 10:13:04 -04001646// Sort the GPT entries, eliminating gaps and making for a logical
1647// ordering. Relies on QuickSortGPT() for the bulk of the work
1648void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001649 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001650
1651 // First, find the last partition with data, so as not to
1652 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001653 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001654
1655 // Now swap empties with the last partitions, to simplify the logic
1656 // in the Quicksort function....
1657 i = 0;
1658 while (i < lastPart) {
1659 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001660 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001661 do {
1662 lastPart--;
1663 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001664 } // if
1665 i++;
1666 } // while
1667
srs5694546a9c72010-01-26 16:00:26 -05001668 // If there are more empties than partitions in the range from 0 to lastPart,
1669 // the above leaves lastPart set too high, so we've got to adjust it to
1670 // prevent empties from migrating to the top of the list....
1671 GetPartRange(&firstPart, &lastPart);
1672
srs5694e4ac11e2009-08-31 10:13:04 -04001673 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001674 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001675} // GPTData::SortGPT()
1676
srs569408bb0da2010-02-19 17:19:55 -05001677// Recursive quick sort algorithm for GPT partitions. Note that if there
1678// are any empties in the specified range, they'll be sorted to the
1679// start, resulting in a sorted set of partitions that begins with
1680// partition 2, 3, or higher.
1681void GPTData::QuickSortGPT(int start, int finish) {
1682 uint64_t starterValue; // starting location of median partition
1683 int left, right;
1684
1685 left = start;
1686 right = finish;
1687 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1688 do {
1689 while (partitions[left].GetFirstLBA() < starterValue)
1690 left++;
1691 while (partitions[right].GetFirstLBA() > starterValue)
1692 right--;
1693 if (left <= right)
1694 SwapPartitions(left++, right--);
1695 } while (left <= right);
1696 if (start < right) QuickSortGPT(start, right);
1697 if (finish > left) QuickSortGPT(left, finish);
1698} // GPTData::QuickSortGPT()
1699
1700// Swap the contents of two partitions.
1701// Returns 1 if successful, 0 if either partition is out of range
1702// (that is, not a legal number; either or both can be empty).
1703// Note that if partNum1 = partNum2 and this number is in range,
1704// it will be considered successful.
1705int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1706 GPTPart temp;
1707 int allOK = 1;
1708
1709 if ((partNum1 < mainHeader.numParts) && (partNum2 < mainHeader.numParts)) {
1710 if (partNum1 != partNum2) {
1711 temp = partitions[partNum1];
1712 partitions[partNum1] = partitions[partNum2];
1713 partitions[partNum2] = temp;
1714 } // if
1715 } else allOK = 0; // partition numbers are valid
1716 return allOK;
1717} // GPTData::SwapPartitions()
1718
srs5694e4ac11e2009-08-31 10:13:04 -04001719// Set up data structures for entirely new set of partitions on the
1720// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001721// Note that this function does NOT clear the protectiveMBR data
1722// structure, since it may hold the original MBR partitions if the
1723// program was launched on an MBR disk, and those may need to be
1724// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001725int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001726 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001727
1728 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001729 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001730 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001731 partitions = NULL;
1732 SetGPTSize(NUM_GPT_ENTRIES);
1733
1734 // Now initialize a bunch of stuff that's static....
1735 mainHeader.signature = GPT_SIGNATURE;
1736 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001737 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001738 mainHeader.reserved = 0;
1739 mainHeader.currentLBA = UINT64_C(1);
1740 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1741 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1742 for (i = 0; i < GPT_RESERVED; i++) {
1743 mainHeader.reserved2[i] = '\0';
1744 } // for
1745
1746 // Now some semi-static items (computed based on end of disk)
1747 mainHeader.backupLBA = diskSize - UINT64_C(1);
1748 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1749
1750 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001751 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001752
1753 // Copy main header to backup header
1754 RebuildSecondHeader();
1755
1756 // Blank out the partitions array....
1757 BlankPartitions();
1758
1759 // Flag all CRCs as being OK....
1760 mainCrcOk = 1;
1761 secondCrcOk = 1;
1762 mainPartsCrcOk = 1;
1763 secondPartsCrcOk = 1;
1764
1765 return (goOn);
1766} // GPTData::ClearGPTData()
1767
srs5694247657a2009-11-26 18:36:12 -05001768// Set the location of the second GPT header data to the end of the disk.
1769// Used internally and called by the 'e' option on the recovery &
1770// transformation menu, to help users of RAID arrays who add disk space
1771// to their arrays.
1772void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001773 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1774 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1775 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1776} // GPTData::FixSecondHeaderLocation()
1777
srs56940a697312010-01-28 21:10:52 -05001778int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001779 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001780
1781 if (!IsFreePartNum(partNum)) {
1782 partitions[partNum].SetName(theName);
1783 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001784
1785 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001786} // GPTData::SetName
1787
1788// Set the disk GUID to the specified value. Note that the header CRCs must
1789// be recomputed after calling this function.
1790void GPTData::SetDiskGUID(GUIDData newGUID) {
1791 mainHeader.diskGUID = newGUID;
1792 secondHeader.diskGUID = newGUID;
1793} // SetDiskGUID()
1794
1795// Set the unique GUID of the specified partition. Returns 1 on
1796// successful completion, 0 if there were problems (invalid
1797// partition number).
1798int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1799 int retval = 0;
1800
1801 if (pn < mainHeader.numParts) {
1802 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1803 partitions[pn].SetUniqueGUID(theGUID);
1804 retval = 1;
1805 } // if
1806 } // if
1807 return retval;
1808} // GPTData::SetPartitionGUID()
1809
srs5694ba00fed2010-01-12 18:18:36 -05001810// Change partition type code non-interactively. Returns 1 if
1811// successful, 0 if not....
1812int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1813 int retval = 1;
1814
1815 if (!IsFreePartNum(partNum)) {
1816 partitions[partNum].SetType(hexCode);
1817 } else retval = 0;
1818 return retval;
1819} // GPTData::ChangePartType()
1820
srs56941d1448a2009-12-31 21:20:19 -05001821// Adjust sector number so that it falls on a sector boundary that's a
1822// multiple of sectorAlignment. This is done to improve the performance
1823// of Western Digital Advanced Format disks and disks with similar
1824// technology from other companies, which use 4096-byte sectors
1825// internally although they translate to 512-byte sectors for the
1826// benefit of the OS. If partitions aren't properly aligned on these
1827// disks, some filesystem data structures can span multiple physical
1828// sectors, degrading performance. This function should be called
1829// only on the FIRST sector of the partition, not the last!
1830// This function returns 1 if the alignment was altered, 0 if it
1831// was unchanged.
1832int GPTData::Align(uint64_t* sector) {
1833 int retval = 0, sectorOK = 0;
1834 uint64_t earlier, later, testSector, original;
1835
1836 if ((*sector % sectorAlignment) != 0) {
1837 original = *sector;
1838 retval = 1;
1839 earlier = (*sector / sectorAlignment) * sectorAlignment;
1840 later = earlier + (uint64_t) sectorAlignment;
1841
1842 // Check to see that every sector between the earlier one and the
1843 // requested one is clear, and that it's not too early....
1844 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001845 sectorOK = 1;
1846 testSector = earlier;
1847 do {
1848 sectorOK = IsFree(testSector++);
1849 } while ((sectorOK == 1) && (testSector < *sector));
1850 if (sectorOK == 1) {
1851 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001852 } // if
1853 } // if firstUsableLBA check
1854
1855 // If couldn't move the sector earlier, try to move it later instead....
1856 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1857 sectorOK = 1;
1858 testSector = later;
1859 do {
1860 sectorOK = IsFree(testSector--);
1861 } while ((sectorOK == 1) && (testSector > *sector));
1862 if (sectorOK == 1) {
1863 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001864 } // if
1865 } // if
1866
1867 // If sector was changed successfully, inform the user of this fact.
1868 // Otherwise, notify the user that it couldn't be done....
1869 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001870 cout << "Information: Moved requested sector from " << original << " to "
1871 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001872 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001873 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001874 } else {
srs5694fed16d02010-01-27 23:03:40 -05001875 cout << "Information: Sector not aligned on " << sectorAlignment
1876 << "-sector boundary and could not be moved.\n"
1877 << "If you're using a Western Digital Advanced Format or similar disk with\n"
1878 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001879 retval = 0;
1880 } // if/else
1881 } // if
1882 return retval;
1883} // GPTData::Align()
1884
srs5694e4ac11e2009-08-31 10:13:04 -04001885/********************************************************
1886 * *
1887 * Functions that return data about GPT data structures *
1888 * (most of these are inline in gpt.h) *
1889 * *
1890 ********************************************************/
1891
1892// Find the low and high used partition numbers (numbered from 0).
1893// Return value is the number of partitions found. Note that the
1894// *low and *high values are both set to 0 when no partitions
1895// are found, as well as when a single partition in the first
1896// position exists. Thus, the return value is the only way to
1897// tell when no partitions exist.
1898int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1899 uint32_t i;
1900 int numFound = 0;
1901
1902 *low = mainHeader.numParts + 1; // code for "not found"
1903 *high = 0;
1904 if (mainHeader.numParts > 0) { // only try if partition table exists...
1905 for (i = 0; i < mainHeader.numParts; i++) {
1906 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1907 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001908 // Set the low value only if it's not yet found...
srs5694e4ac11e2009-08-31 10:13:04 -04001909 if (*low == (mainHeader.numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001910 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001911 } // if
1912 } // for
1913 } // if
1914
1915 // Above will leave *low pointing to its "not found" value if no partitions
1916 // are defined, so reset to 0 if this is the case....
1917 if (*low == (mainHeader.numParts + 1))
1918 *low = 0;
1919 return numFound;
1920} // GPTData::GetPartRange()
1921
srs569408bb0da2010-02-19 17:19:55 -05001922// Returns the value of the first free partition, or -1 if none is
1923// unused.
1924int GPTData::FindFirstFreePart(void) {
1925 int i = 0;
1926
1927 if (partitions != NULL) {
1928 while ((partitions[i].IsUsed()) && (i < (int) mainHeader.numParts))
1929 i++;
1930 if (i >= (int) mainHeader.numParts)
1931 i = -1;
1932 } else i = -1;
1933 return i;
1934} // GPTData::FindFirstFreePart()
1935
srs5694978041c2009-09-21 20:51:47 -04001936// Returns the number of defined partitions.
1937uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001938 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001939
1940 for (i = 0; i < mainHeader.numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001941 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001942 counted++;
1943 } // for
1944 return counted;
1945} // GPTData::CountParts()
1946
srs5694e4ac11e2009-08-31 10:13:04 -04001947/****************************************************
1948 * *
1949 * Functions that return data about disk free space *
1950 * *
1951 ****************************************************/
1952
1953// Find the first available block after the starting point; returns 0 if
1954// there are no available blocks left
1955uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1956 uint64_t first;
1957 uint32_t i;
1958 int firstMoved = 0;
1959
1960 // Begin from the specified starting point or from the first usable
1961 // LBA, whichever is greater...
1962 if (start < mainHeader.firstUsableLBA)
1963 first = mainHeader.firstUsableLBA;
1964 else
1965 first = start;
1966
1967 // ...now search through all partitions; if first is within an
1968 // existing partition, move it to the next sector after that
1969 // partition and repeat. If first was moved, set firstMoved
1970 // flag; repeat until firstMoved is not set, so as to catch
1971 // cases where partitions are out of sequential order....
1972 do {
1973 firstMoved = 0;
1974 for (i = 0; i < mainHeader.numParts; i++) {
1975 if ((first >= partitions[i].GetFirstLBA()) &&
1976 (first <= partitions[i].GetLastLBA())) { // in existing part.
1977 first = partitions[i].GetLastLBA() + 1;
1978 firstMoved = 1;
1979 } // if
1980 } // for
1981 } while (firstMoved == 1);
1982 if (first > mainHeader.lastUsableLBA)
1983 first = 0;
1984 return (first);
1985} // GPTData::FindFirstAvailable()
1986
1987// Finds the first available sector in the largest block of unallocated
1988// space on the disk. Returns 0 if there are no available blocks left
1989uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001990 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001991
1992 start = 0;
1993 do {
1994 firstBlock = FindFirstAvailable(start);
1995 if (firstBlock != UINT32_C(0)) { // something's free...
1996 lastBlock = FindLastInFree(firstBlock);
1997 segmentSize = lastBlock - firstBlock + UINT32_C(1);
1998 if (segmentSize > selectedSize) {
1999 selectedSize = segmentSize;
2000 selectedSegment = firstBlock;
2001 } // if
2002 start = lastBlock + 1;
2003 } // if
2004 } while (firstBlock != 0);
2005 return selectedSegment;
2006} // GPTData::FindFirstInLargest()
2007
srs5694cb76c672010-02-11 22:22:22 -05002008// Find the last available block on the disk.
2009// Returns 0 if there are no available partitions
2010uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002011 uint64_t last;
2012 uint32_t i;
2013 int lastMoved = 0;
2014
2015 // Start by assuming the last usable LBA is available....
2016 last = mainHeader.lastUsableLBA;
2017
2018 // ...now, similar to algorithm in FindFirstAvailable(), search
2019 // through all partitions, moving last when it's in an existing
2020 // partition. Set the lastMoved flag so we repeat to catch cases
2021 // where partitions are out of logical order.
2022 do {
2023 lastMoved = 0;
2024 for (i = 0; i < mainHeader.numParts; i++) {
2025 if ((last >= partitions[i].GetFirstLBA()) &&
2026 (last <= partitions[i].GetLastLBA())) { // in existing part.
2027 last = partitions[i].GetFirstLBA() - 1;
2028 lastMoved = 1;
2029 } // if
2030 } // for
2031 } while (lastMoved == 1);
2032 if (last < mainHeader.firstUsableLBA)
2033 last = 0;
2034 return (last);
2035} // GPTData::FindLastAvailable()
2036
2037// Find the last available block in the free space pointed to by start.
2038uint64_t GPTData::FindLastInFree(uint64_t start) {
2039 uint64_t nearestStart;
2040 uint32_t i;
2041
2042 nearestStart = mainHeader.lastUsableLBA;
2043 for (i = 0; i < mainHeader.numParts; i++) {
2044 if ((nearestStart > partitions[i].GetFirstLBA()) &&
2045 (partitions[i].GetFirstLBA() > start)) {
2046 nearestStart = partitions[i].GetFirstLBA() - 1;
2047 } // if
2048 } // for
2049 return (nearestStart);
2050} // GPTData::FindLastInFree()
2051
2052// Finds the total number of free blocks, the number of segments in which
2053// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002054uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002055 uint64_t start = UINT64_C(0); // starting point for each search
2056 uint64_t totalFound = UINT64_C(0); // running total
2057 uint64_t firstBlock; // first block in a segment
2058 uint64_t lastBlock; // last block in a segment
2059 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002060 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002061
2062 *largestSegment = UINT64_C(0);
2063 do {
2064 firstBlock = FindFirstAvailable(start);
2065 if (firstBlock != UINT64_C(0)) { // something's free...
2066 lastBlock = FindLastInFree(firstBlock);
2067 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2068 if (segmentSize > *largestSegment) {
2069 *largestSegment = segmentSize;
2070 } // if
2071 totalFound += segmentSize;
2072 num++;
2073 start = lastBlock + 1;
2074 } // if
2075 } while (firstBlock != 0);
2076 *numSegments = num;
2077 return totalFound;
2078} // GPTData::FindFreeBlocks()
2079
2080// Returns 1 if sector is unallocated, 0 if it's allocated to a partition
2081int GPTData::IsFree(uint64_t sector) {
2082 int isFree = 1;
2083 uint32_t i;
2084
2085 for (i = 0; i < mainHeader.numParts; i++) {
2086 if ((sector >= partitions[i].GetFirstLBA()) &&
2087 (sector <= partitions[i].GetLastLBA())) {
2088 isFree = 0;
srs569408bb0da2010-02-19 17:19:55 -05002089 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002090 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002091 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002092 (sector > mainHeader.lastUsableLBA)) {
2093 isFree = 0;
srs569408bb0da2010-02-19 17:19:55 -05002094 } // if
2095 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002096} // GPTData::IsFree()
2097
srs5694ba00fed2010-01-12 18:18:36 -05002098// Returns 1 if partNum is unused.
2099int GPTData::IsFreePartNum(uint32_t partNum) {
2100 int retval = 1;
2101
srs569408bb0da2010-02-19 17:19:55 -05002102 if ((partNum < mainHeader.numParts) && (partitions != NULL)) {
2103 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002104 retval = 0;
2105 } // if partition is in use
2106 } else retval = 0;
2107
2108 return retval;
2109} // GPTData::IsFreePartNum()
2110
srs5694e4ac11e2009-08-31 10:13:04 -04002111/********************************
2112 * *
2113 * Endianness support functions *
2114 * *
2115 ********************************/
2116
srs56942a9f5da2009-08-26 00:48:01 -04002117void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002118 ReverseBytes(&header->signature, 8);
2119 ReverseBytes(&header->revision, 4);
2120 ReverseBytes(&header->headerSize, 4);
2121 ReverseBytes(&header->headerCRC, 4);
2122 ReverseBytes(&header->reserved, 4);
2123 ReverseBytes(&header->currentLBA, 8);
2124 ReverseBytes(&header->backupLBA, 8);
2125 ReverseBytes(&header->firstUsableLBA, 8);
2126 ReverseBytes(&header->lastUsableLBA, 8);
2127 ReverseBytes(&header->partitionEntriesLBA, 8);
2128 ReverseBytes(&header->numParts, 4);
2129 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2130 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002131 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002132} // GPTData::ReverseHeaderBytes()
2133
2134// IMPORTANT NOTE: This function requires non-reversed mainHeader
2135// structure!
2136void GPTData::ReversePartitionBytes() {
2137 uint32_t i;
2138
2139 // Check GPT signature on big-endian systems; this will mismatch
2140 // if the function is called out of order. Unfortunately, it'll also
2141 // mismatch if there's data corruption.
2142 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002143 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2144 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002145 } // if signature mismatch....
2146 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002147 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002148 } // for
2149} // GPTData::ReversePartitionBytes()
2150
2151/******************************************
2152 * *
2153 * Additional non-class support functions *
2154 * *
2155 ******************************************/
2156
srs5694e7b4ff92009-08-18 13:16:10 -04002157// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2158// never fail these tests, but the struct types may fail depending on compile options.
2159// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2160// sizes.
2161int SizesOK(void) {
2162 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002163
2164 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002165 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002166 allOK = 0;
2167 } // if
2168 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002169 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002170 allOK = 0;
2171 } // if
2172 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002173 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002174 allOK = 0;
2175 } // if
2176 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002177 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002178 allOK = 0;
2179 } // if
2180 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002181 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002182 allOK = 0;
2183 } // if
srs5694978041c2009-09-21 20:51:47 -04002184 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002185 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002186 allOK = 0;
2187 } // if
2188 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002189 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002190 allOK = 0;
2191 } // if
srs5694221e0872009-08-29 15:00:31 -04002192 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002193 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002194 allOK = 0;
2195 } // if
srs56946699b012010-02-04 00:55:30 -05002196 if (sizeof(GUIDData) != 16) {
2197 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2198 allOK = 0;
2199 } // if
2200 if (sizeof(PartType) != 16) {
2201 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2202 allOK = 0;
2203 } // if
srs5694fed16d02010-01-27 23:03:40 -05002204 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002205 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002206 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2207 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002208 } // if
2209 return (allOK);
2210} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002211