blob: ac429955c71af75d3cf566b1d790f2a363cf63ca [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"
srs569455d92612010-03-07 22:16:07 -050028#include "partnotes.h"
srs5694e7b4ff92009-08-18 13:16:10 -040029
30using namespace std;
31
32/****************************************
33 * *
34 * GPTData class and related structures *
35 * *
36 ****************************************/
37
srs5694e4ac11e2009-08-31 10:13:04 -040038// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040039GPTData::GPTData(void) {
40 blockSize = SECTOR_SIZE; // set a default
41 diskSize = 0;
42 partitions = NULL;
43 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050044 device = "";
srs56945d58fe02010-01-03 20:57:08 -050045 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040046 mainCrcOk = 0;
47 secondCrcOk = 0;
48 mainPartsCrcOk = 0;
49 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040050 apmFound = 0;
51 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050052 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050053 beQuiet = 0;
54 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040055 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050056 mainHeader.numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040057 SetGPTSize(NUM_GPT_ENTRIES);
58} // GPTData default constructor
59
60// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050061GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040062 blockSize = SECTOR_SIZE; // set a default
63 diskSize = 0;
64 partitions = NULL;
65 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050066 device = "";
srs56945d58fe02010-01-03 20:57:08 -050067 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040068 mainCrcOk = 0;
69 secondCrcOk = 0;
70 mainPartsCrcOk = 0;
71 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040072 apmFound = 0;
73 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050074 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050075 beQuiet = 0;
76 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040077 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050078 mainHeader.numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050079 if (!LoadPartitions(filename))
80 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050081} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040082
srs5694e4ac11e2009-08-31 10:13:04 -040083// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040084GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050085 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040086} // GPTData destructor
87
srs5694e4ac11e2009-08-31 10:13:04 -040088/*********************************************************************
89 * *
90 * Begin functions that verify data, or that adjust the verification *
91 * information (compute CRCs, rebuild headers) *
92 * *
93 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040094
srs5694e4ac11e2009-08-31 10:13:04 -040095// Perform detailed verification, reporting on any problems found, but
96// do *NOT* recover from these problems. Returns the total number of
97// problems identified.
98int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -050099 int problems = 0;
100 uint32_t i, numSegments;
101 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400102
103 // First, check for CRC errors in the GPT data....
104 if (!mainCrcOk) {
105 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500106 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
107 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
108 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
109 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400110 } // if
111 if (!mainPartsCrcOk) {
112 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500113 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
114 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
115 << "transformation menu). This report may be a false alarm if you've already\n"
116 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400117 } // if
118 if (!secondCrcOk) {
119 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500120 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
121 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
122 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
123 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400124 } // if
125 if (!secondPartsCrcOk) {
126 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500127 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
128 << "be corrupt. This program will automatically create a new backup partition\n"
129 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400130 } // if
131
srs5694978041c2009-09-21 20:51:47 -0400132 // Now check that the main and backup headers both point to themselves....
133 if (mainHeader.currentLBA != 1) {
134 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500135 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
136 << "is being automatically corrected, but it may be a symptom of more serious\n"
137 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400138 mainHeader.currentLBA = 1;
139 } // if
140 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
141 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500142 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
143 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
144 << "option on the experts' menu to adjust the secondary header's and partition\n"
145 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400146 } // if
147
148 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400149 if (mainHeader.currentLBA != secondHeader.backupLBA) {
150 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500151 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
152 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
153 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400154 } // if
155 if (mainHeader.backupLBA != secondHeader.currentLBA) {
156 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500157 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
158 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
159 << secondHeader.currentLBA << ").\n"
160 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400161 } // if
162 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
163 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500164 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
165 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
166 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400167 } // if
168 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
169 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500170 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
171 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
172 << secondHeader.lastUsableLBA << ")\n"
173 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400174 } // if
srs56946699b012010-02-04 00:55:30 -0500175 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400176 problems++;
srs56946699b012010-02-04 00:55:30 -0500177 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500178 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500179 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500180 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
181 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400182 } // if
183 if (mainHeader.numParts != secondHeader.numParts) {
184 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500185 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
186 << ") doesn't\nmatch the backup GPT header's number of partitions ("
187 << secondHeader.numParts << ")\n"
188 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400189 } // if
190 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
191 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500192 cout << "\nProblem: main GPT header's size of partition entries ("
193 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
194 << "match the backup GPT header's size of partition entries ("
195 << secondHeader.sizeOfPartitionEntries << ")\n"
196 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
197 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400198 } // if
199
200 // Now check for a few other miscellaneous problems...
201 // Check that the disk size will hold the data...
202 if (mainHeader.backupLBA > diskSize) {
203 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500204 cout << "\nProblem: Disk is too small to hold all the data!\n"
205 << "(Disk size is " << diskSize << " sectors, needs to be "
206 << mainHeader.backupLBA << " sectors.)\n"
207 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400208 } // if
209
210 // Check for overlapping partitions....
211 problems += FindOverlaps();
212
srs569455d92612010-03-07 22:16:07 -0500213 // Check for insane partitions (start after end, hugely big, etc.)
214 problems += FindInsanePartitions();
215
srs5694e4ac11e2009-08-31 10:13:04 -0400216 // Check for mismatched MBR and GPT partitions...
217 problems += FindHybridMismatches();
218
219 // Verify that partitions don't run into GPT data areas....
220 problems += CheckGPTSize();
221
srs56941d1448a2009-12-31 21:20:19 -0500222 // Check that partitions are aligned on proper boundaries (for WD Advanced
223 // Format and similar disks)....
224 for (i = 0; i < mainHeader.numParts; i++) {
225 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500226 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
227 << sectorAlignment << "-sector boundary. This may\nresult "
228 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500229 } // if
230 } // for
231
srs5694e4ac11e2009-08-31 10:13:04 -0400232 // Now compute available space, but only if no problems found, since
233 // problems could affect the results
234 if (problems == 0) {
235 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500236 cout << "No problems found. " << totalFree << " free sectors ("
237 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
238 << numSegments << "\nsegments, the largest of which is "
239 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
240 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } else {
srs56940a697312010-01-28 21:10:52 -0500242 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400243 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400244
245 return (problems);
246} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400247
248// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400249// do, issues a warning but takes no action. Returns number of problems
250// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400251int GPTData::CheckGPTSize(void) {
252 uint64_t overlap, firstUsedBlock, lastUsedBlock;
253 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400254 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400255
256 // first, locate the first & last used blocks
257 firstUsedBlock = UINT64_MAX;
258 lastUsedBlock = 0;
259 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400260 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400261 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400262 firstUsedBlock = partitions[i].GetFirstLBA();
263 if (partitions[i].GetLastLBA() > lastUsedBlock)
264 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400265 } // for
266
267 // If the disk size is 0 (the default), then it means that various
268 // variables aren't yet set, so the below tests will be useless;
269 // therefore we should skip everything
270 if (diskSize != 0) {
271 if (mainHeader.firstUsableLBA > firstUsedBlock) {
272 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500273 cout << "Warning! Main partition table overlaps the first partition by "
274 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400275 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "Try reducing the partition table size by " << overlap * 4
277 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400278 } else {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400280 } // if/else
281 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400282 } // Problem at start of disk
283 if (mainHeader.lastUsableLBA < lastUsedBlock) {
284 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500285 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500286 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400287 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500288 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400289 } else {
srs5694fed16d02010-01-27 23:03:40 -0500290 cout << "Try reducing the partition table size by " << overlap * 4
291 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400292 } // if/else
293 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400294 } // Problem at end of disk
295 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400296 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400297} // GPTData::CheckGPTSize()
298
srs5694e7b4ff92009-08-18 13:16:10 -0400299// Check the validity of the GPT header. Returns 1 if the main header
300// is valid, 2 if the backup header is valid, 3 if both are valid, and
301// 0 if neither is valid. Note that this function just checks the GPT
302// signature and revision numbers, not CRCs or other data.
303int GPTData::CheckHeaderValidity(void) {
304 int valid = 3;
305
srs5694fed16d02010-01-27 23:03:40 -0500306 cout.setf(ios::uppercase);
307 cout.fill('0');
308
309 // Note: failed GPT signature checks produce no error message because
310 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400311 if (mainHeader.signature != GPT_SIGNATURE) {
312 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400313 } else if ((mainHeader.revision != 0x00010000) && valid) {
314 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500315 cout << "Unsupported GPT version in main header; read 0x";
316 cout.width(8);
317 cout << hex << mainHeader.revision << ", should be\n0x";
318 cout.width(8);
319 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400320 } // if/else/if
321
322 if (secondHeader.signature != GPT_SIGNATURE) {
323 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } else if ((secondHeader.revision != 0x00010000) && valid) {
325 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500326 cout << "Unsupported GPT version in backup header; read 0x";
327 cout.width(8);
328 cout << hex << secondHeader.revision << ", should be\n0x";
329 cout.width(8);
330 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400331 } // if/else/if
332
srs56942a9f5da2009-08-26 00:48:01 -0400333 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400334 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400335 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400336 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400337 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500338 } // if
srs5694fed16d02010-01-27 23:03:40 -0500339 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400340
srs5694fed16d02010-01-27 23:03:40 -0500341 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400342} // GPTData::CheckHeaderValidity()
343
344// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500345// Note: Must be called with header in LITTLE-ENDIAN
346// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400347int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400348 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400349
srs56942a9f5da2009-08-26 00:48:01 -0400350 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400351 // computation to be valid
352 oldCRC = header->headerCRC;
353 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400354 hSize = header->headerSize;
355
356 // If big-endian system, reverse byte order
357 if (IsLittleEndian() == 0) {
358 ReverseBytes(&oldCRC, 4);
359 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400360
361 // Initialize CRC functions...
362 chksum_crc32gentab();
363
364 // Compute CRC, restore original, and return result of comparison
365 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400366 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400367 return (oldCRC == newCRC);
368} // GPTData::CheckHeaderCRC()
369
srs56946699b012010-02-04 00:55:30 -0500370// Recompute all the CRCs. Must be called before saving if any changes have
371// been made. Must be called on platform-ordered data (this function reverses
372// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400373void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400374 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400375 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400376
377 // Initialize CRC functions...
378 chksum_crc32gentab();
379
srs56946699b012010-02-04 00:55:30 -0500380 // Save some key data from header before reversing byte order....
381 trueNumParts = mainHeader.numParts;
srs5694978041c2009-09-21 20:51:47 -0400382 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500383
384 if ((littleEndian = IsLittleEndian()) == 0) {
385 ReversePartitionBytes();
386 ReverseHeaderBytes(&mainHeader);
387 ReverseHeaderBytes(&secondHeader);
388 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400389
srs5694e7b4ff92009-08-18 13:16:10 -0400390 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400391 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400392 mainHeader.partitionEntriesCRC = crc;
393 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400394 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400395 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
396 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400397 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400398
399 // Zero out GPT tables' own CRCs (required for correct computation)
400 mainHeader.headerCRC = 0;
401 secondHeader.headerCRC = 0;
402
403 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400404 crc = chksum_crc32((unsigned char*) &mainHeader, 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 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400408 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400409 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400410 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400411 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500412
413 if ((littleEndian = IsLittleEndian()) == 0) {
414 ReverseHeaderBytes(&mainHeader);
415 ReverseHeaderBytes(&secondHeader);
416 ReversePartitionBytes();
417 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400418} // GPTData::RecomputeCRCs()
419
srs5694e7b4ff92009-08-18 13:16:10 -0400420// Rebuild the main GPT header, using the secondary header as a model.
421// Typically called when the main header has been found to be corrupt.
422void GPTData::RebuildMainHeader(void) {
423 int i;
424
425 mainHeader.signature = GPT_SIGNATURE;
426 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400427 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400428 mainHeader.headerCRC = UINT32_C(0);
429 mainHeader.reserved = secondHeader.reserved;
430 mainHeader.currentLBA = secondHeader.backupLBA;
431 mainHeader.backupLBA = secondHeader.currentLBA;
432 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
433 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500434 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400435 mainHeader.partitionEntriesLBA = UINT64_C(2);
436 mainHeader.numParts = secondHeader.numParts;
437 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
438 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
439 for (i = 0 ; i < GPT_RESERVED; i++)
440 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500441 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400442} // GPTData::RebuildMainHeader()
443
444// Rebuild the secondary GPT header, using the main header as a model.
445void GPTData::RebuildSecondHeader(void) {
446 int i;
447
448 secondHeader.signature = GPT_SIGNATURE;
449 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400450 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400451 secondHeader.headerCRC = UINT32_C(0);
452 secondHeader.reserved = mainHeader.reserved;
453 secondHeader.currentLBA = mainHeader.backupLBA;
454 secondHeader.backupLBA = mainHeader.currentLBA;
455 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
456 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500457 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400458 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
459 secondHeader.numParts = mainHeader.numParts;
460 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
461 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
462 for (i = 0 ; i < GPT_RESERVED; i++)
463 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500464 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400465} // GPTData::RebuildSecondHeader()
466
467// Search for hybrid MBR entries that have no corresponding GPT partition.
468// Returns number of such mismatches found
469int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500470 int i, found, numFound = 0;
471 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400472 uint64_t mbrFirst, mbrLast;
473
474 for (i = 0; i < 4; i++) {
475 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
476 j = 0;
477 found = 0;
478 do {
479 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
480 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
481 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
482 (partitions[j].GetLastLBA() == mbrLast))
483 found = 1;
484 j++;
485 } while ((!found) && (j < mainHeader.numParts));
486 if (!found) {
487 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500488 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
489 << i + 1 << ", of type 0x";
490 cout.fill('0');
491 cout.setf(ios::uppercase);
492 cout.width(2);
493 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
494 << "has no corresponding GPT partition! You may continue, but this condition\n"
495 << "might cause data loss in the future!\a\n" << dec;
496 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400497 } // if
498 } // if
499 } // for
500 return numFound;
501} // GPTData::FindHybridMismatches
502
503// Find overlapping partitions and warn user about them. Returns number of
504// overlapping partitions.
505int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500506 int problems = 0;
507 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400508
509 for (i = 1; i < mainHeader.numParts; i++) {
510 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500511 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400512 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500513 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
514 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
515 << " to " << partitions[i].GetLastLBA() << "\n";
516 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
517 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400518 } // if
519 } // for j...
520 } // for i...
521 return problems;
522} // GPTData::FindOverlaps()
523
srs569455d92612010-03-07 22:16:07 -0500524// Find partitions that are insane -- they start after they end or are too
525// big for the disk. (The latter should duplicate detection of overlaps
526// with GPT backup data structures, but better to err on the side of
527// redundant tests than to miss something....)
528int GPTData::FindInsanePartitions(void) {
529 uint32_t i;
530 int problems = 0;
531
532 for (i = 0; i < mainHeader.numParts; i++) {
533 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
534 problems++;
535 cout << "\nProblem: partition " << i << " ends before it begins.\n";
536 } // if
537 if (partitions[i].GetLastLBA() >= diskSize) {
538 problems++;
539 cout << "\nProblem: partition " << i << " is too big for the disk.\n";
540 } // if
541 } // for
542 return problems;
543} // GPTData::FindInsanePartitions(void)
544
545
srs5694e4ac11e2009-08-31 10:13:04 -0400546/******************************************************************
547 * *
548 * Begin functions that load data from disk or save data to disk. *
549 * *
550 ******************************************************************/
551
552// Scan for partition data. This function loads the MBR data (regular MBR or
553// protective MBR) and loads BSD disklabel data (which is probably invalid).
554// It also looks for APM data, forces a load of GPT data, and summarizes
555// the results.
srs5694546a9c72010-01-26 16:00:26 -0500556void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400557 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400558
559 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500560 protectiveMBR.ReadMBRData(&myDisk);
561 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400562
563 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500564 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500565
566 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500567 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500568 protectiveMBR.ShowState();
569 bsdDisklabel.ShowState();
570 ShowAPMState(); // Show whether there's an Apple Partition Map present
571 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500572 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500573 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400574
575 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500576 cout << "\n*******************************************************************\n"
577 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500578 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500579 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500580 } // if
srs5694fed16d02010-01-27 23:03:40 -0500581 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400582 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400583} // GPTData::PartitionScan()
584
585// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500586int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500587 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500588 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500589 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400590
srs5694546a9c72010-01-26 16:00:26 -0500591 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500592 err = myDisk.OpenForWrite(deviceFilename);
593 if ((err == 0) && (!justLooking)) {
594 cout << "\aNOTE: Write test failed with error number " << errno
595 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
596#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
597 cout << "You may be able to enable writes by exiting this program, typing\n"
598 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
599 << "program.\n";
600#endif
601 cout << "\n";
602 } // if
603 myDisk.Close(); // Close and re-open read-only in case of bugs
604 } else allOK = 0; // if
605
606 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400607 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500608 diskSize = myDisk.DiskSize(&err);
609 blockSize = (uint32_t) myDisk.GetBlockSize();
610 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500611 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500612 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400613
srs5694ba00fed2010-01-12 18:18:36 -0500614 whichWasUsed = UseWhichPartitions();
615 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400616 case use_mbr:
617 XFormPartitions();
618 break;
619 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500620 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400621// bsdDisklabel.DisplayBSDData();
622 ClearGPTData();
623 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500624 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400625 break;
626 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500627 mbrState = protectiveMBR.GetValidity();
628 if ((mbrState == invalid) || (mbrState == mbr))
629 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400630 break;
631 case use_new:
632 ClearGPTData();
633 protectiveMBR.MakeProtectiveMBR();
634 break;
srs56943c0af382010-01-15 19:19:18 -0500635 case use_abort:
636 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500637 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500638 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400639 } // switch
640
srs569455d92612010-03-07 22:16:07 -0500641 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500642 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500643 myDisk.Close();
srs5694e4ac11e2009-08-31 10:13:04 -0400644 } else {
645 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400646 } // if/else
647 return (allOK);
648} // GPTData::LoadPartitions()
649
650// Loads the GPT, as much as possible. Returns 1 if this seems to have
651// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500652int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500653 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400654
srs5694cb76c672010-02-11 22:22:22 -0500655 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400656
srs5694cb76c672010-02-11 22:22:22 -0500657 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
658 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
659 } else {
srs569408bb0da2010-02-19 17:19:55 -0500660 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
661 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500662 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
663 << "secondary header from the last sector of the disk! You should use 'v' to\n"
664 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
665 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500666 } // if/else
667 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400668 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400669
670 // Return valid headers code: 0 = both headers bad; 1 = main header
671 // good, backup bad; 2 = backup header good, main header bad;
672 // 3 = both headers good. Note these codes refer to valid GPT
673 // signatures and version numbers; more subtle problems will elude
674 // this check!
675 validHeaders = CheckHeaderValidity();
676
677 // Read partitions (from primary array)
678 if (validHeaders > 0) { // if at least one header is OK....
679 // GPT appears to be valid....
680 state = gpt_valid;
681
682 // We're calling the GPT valid, but there's a possibility that one
683 // of the two headers is corrupt. If so, use the one that seems to
684 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500685 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500686 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
687 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400688 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500689 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400690 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500691 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500692 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
693 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500694 RebuildMainHeader();
695 state = gpt_corrupt;
696 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400697 } // if/else/if
698
srs5694546a9c72010-01-26 16:00:26 -0500699 // Figure out which partition table to load....
700 // Load the main partition table, since either its header's CRC is OK or the
701 // backup header's CRC is not OK....
702 if (mainCrcOk || !secondCrcOk) {
703 if (LoadMainTable() == 0)
704 allOK = 0;
705 } else { // bad main header CRC and backup header CRC is OK
706 state = gpt_corrupt;
707 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500708 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500709 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500710 } else { // backup table bad, bad main header CRC, but try main table in desperation....
711 if (LoadMainTable() == 0) {
712 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500713 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500714 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500715 } // if
716 } // if/else (LoadSecondTableAsMain())
717 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400718
srs5694cb76c672010-02-11 22:22:22 -0500719 if (loadedTable == 1)
720 secondPartsCrcOk = CheckTable(&secondHeader);
721 else if (loadedTable == 2)
722 mainPartsCrcOk = CheckTable(&mainHeader);
723 else
724 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400725
srs5694546a9c72010-01-26 16:00:26 -0500726 // Problem with main partition table; if backup is OK, use it instead....
727 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
728 state = gpt_corrupt;
729 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500730 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500731 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
732 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500733 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500734
srs5694e4ac11e2009-08-31 10:13:04 -0400735 // Check for valid CRCs and warn if there are problems
736 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
737 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500738 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400739 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500740 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400741 } else {
742 state = gpt_invalid;
743 } // if/else
744 return allOK;
745} // GPTData::ForceLoadGPTData()
746
srs5694247657a2009-11-26 18:36:12 -0500747// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400748// main GPT header in memory MUST be valid for this call to do anything
749// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500750// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400751int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500752 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400753} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400754
755// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500756// table. Used in repair functions, and when starting up if the main
757// partition table is damaged.
758// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
759int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500760 return LoadPartitionTable(secondHeader, myDisk);
761} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400762
srs5694cb76c672010-02-11 22:22:22 -0500763// Load a single GPT header (main or backup) from the specified disk device and
764// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
765// value appropriately.
766// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
767// failure.
768int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
769 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500770 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500771
772 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500773 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500774 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
775 allOK = 0;
776 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500777 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500778
srs56941c6f8b02010-02-21 11:09:20 -0500779 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500780 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500781 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500782 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500783
srs569455d92612010-03-07 22:16:07 -0500784 if (allOK && (mainHeader.numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500785 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500786 }
srs56941c6f8b02010-02-21 11:09:20 -0500787
788 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500789 return allOK;
790} // GPTData::LoadHeader
791
792// Load a partition table (either main or secondary) from the specified disk,
793// using header as a reference for what to load. If sector != 0 (the default
794// is 0), loads from the specified sector; otherwise loads from the sector
795// indicated in header.
796// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
797int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
798 uint32_t sizeOfParts, newCRC;
799 int retval;
800
801 if (disk.OpenForRead()) {
802 if (sector == 0) {
803 retval = disk.Seek(header.partitionEntriesLBA);
804 } else {
805 retval = disk.Seek(sector);
806 } // if/else
srs569455d92612010-03-07 22:16:07 -0500807 if (retval == 1)
808 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500809 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500810 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
811 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500812 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500813 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500814 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400815 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500816 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400817 if (IsLittleEndian() == 0)
818 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500819 if (!mainPartsCrcOk) {
820 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400821 } // if
822 } else {
srs5694cb76c672010-02-11 22:22:22 -0500823 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400824 } // if/else
825 } else {
srs5694fed16d02010-01-27 23:03:40 -0500826 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500827 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500828 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400829 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500830 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500831} // GPTData::LoadPartitionsTable()
832
833// Check the partition table pointed to by header, but don't keep it
834// around.
835// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
836int GPTData::CheckTable(struct GPTHeader *header) {
837 uint32_t sizeOfParts, newCRC;
838 uint8_t *storage;
839 int newCrcOk = 0;
840
841 // Load backup partition table into temporary storage to check
842 // its CRC and store the results, then discard this temporary
843 // storage, since we don't use it in any but recovery operations
844 if (myDisk.Seek(header->partitionEntriesLBA)) {
845 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
846 storage = new uint8_t[sizeOfParts];
847 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
848 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
849 } else {
850 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
851 newCrcOk = (newCRC == header->partitionEntriesCRC);
852 } // if/else
853 delete[] storage;
854 } // if
855 return newCrcOk;
856} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400857
srs5694e7b4ff92009-08-18 13:16:10 -0400858// Writes GPT (and protective MBR) to disk. Returns 1 on successful
859// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500860int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500861 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500862 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400863
srs56946699b012010-02-04 00:55:30 -0500864 littleEndian = IsLittleEndian();
865
srs5694fed16d02010-01-27 23:03:40 -0500866 if (device == "") {
867 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400868 } // if
869
870 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500871
872 // This test should only fail on read-only disks....
873 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500874 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500875 allOK = 0;
876 } // if
877
srs5694e7b4ff92009-08-18 13:16:10 -0400878 // Is there enough space to hold the GPT headers and partition tables,
879 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400880 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400881 allOK = 0;
882 } // if
883
884 // Check that disk is really big enough to handle this...
885 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500886 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
887 << "problem (or it might not). Aborting!\n(Disk size is "
888 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400889 allOK = 0;
890 } // if
srs5694247657a2009-11-26 18:36:12 -0500891 // Check that second header is properly placed. Warn and ask if this should
892 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500893 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500894 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
895 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500896 if (GetYN() == 'Y') {
897 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500898 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500899 } else {
srs5694fed16d02010-01-27 23:03:40 -0500900 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500901 } // if correction requested
902 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400903
srs569455d92612010-03-07 22:16:07 -0500904 // Check for overlapping or insane partitions....
905 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400906 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500907 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400908 } // if
909
910 // Check for mismatched MBR and GPT data, but let it pass if found
911 // (function displays warning message)
912 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400913
914 RecomputeCRCs();
915
srs5694ba00fed2010-01-12 18:18:36 -0500916 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500917 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
918 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500919 answer = GetYN();
920 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500921 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400922 } else {
923 allOK = 0;
924 } // if/else
925 } // if
926
927 // Do it!
928 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500929 // First, write the protective MBR...
930 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400931
srs5694546a9c72010-01-26 16:00:26 -0500932 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400933 // Now write the main GPT header...
srs5694cb76c672010-02-11 22:22:22 -0500934 allOK = SaveHeader(&mainHeader, myDisk, 1);
srs5694e7b4ff92009-08-18 13:16:10 -0400935
936 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400937 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500938 allOK = SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
srs56941e093722010-01-05 00:14:19 -0500939 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400940
941 // Now seek to near the end to write the secondary GPT....
srs5694cb76c672010-02-11 22:22:22 -0500942 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
943 if (!allOK)
944 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
945 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400946
947 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500948 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500949 allOK = SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
srs56946699b012010-02-04 00:55:30 -0500950 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400951
952 // re-read the partition table
953 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500954 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400955 } // if
956
957 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500958 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400959 } else {
srs5694fed16d02010-01-27 23:03:40 -0500960 cerr << "Warning! An error was reported when writing the partition table! This error\n"
961 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
962 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400963 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500964 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } else {
srs5694fed16d02010-01-27 23:03:40 -0500966 cerr << "Unable to open device " << device << " for writing! Errno is "
967 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400968 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400969 } // if/else
970 } else {
srs5694fed16d02010-01-27 23:03:40 -0500971 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400972 } // if
973
974 return (allOK);
975} // GPTData::SaveGPTData()
976
977// Save GPT data to a backup file. This function does much less error
978// checking than SaveGPTData(). It can therefore preserve many types of
979// corruption for later analysis; however, it preserves only the MBR,
980// the main GPT header, the backup GPT header, and the main partition
981// table; it discards the backup partition table, since it should be
982// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500983int GPTData::SaveGPTBackup(const string & filename) {
984 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500985 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400986
srs5694546a9c72010-01-26 16:00:26 -0500987 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500988 // Recomputing the CRCs is likely to alter them, which could be bad
989 // if the intent is to save a potentially bad GPT for later analysis;
990 // but if we don't do this, we get bogus errors when we load the
991 // backup. I'm favoring misses over false alarms....
992 RecomputeCRCs();
993
srs5694546a9c72010-01-26 16:00:26 -0500994 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400995
srs5694cb76c672010-02-11 22:22:22 -0500996 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500997 // MBR write closed disk, so re-open and seek to end....
998 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500999 allOK = SaveHeader(&mainHeader, backupFile, 1);
1000 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001001
srs5694e7b4ff92009-08-18 13:16:10 -04001002 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001003 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001004
srs5694cb76c672010-02-11 22:22:22 -05001005 if (allOK)
1006 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001007
1008 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001009 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001010 } else {
srs5694fed16d02010-01-27 23:03:40 -05001011 cerr << "Warning! An error was reported when writing the backup file.\n"
1012 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001013 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001014 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001015 } else {
srs5694fed16d02010-01-27 23:03:40 -05001016 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001017 allOK = 0;
1018 } // if/else
1019 return allOK;
1020} // GPTData::SaveGPTBackup()
1021
srs5694cb76c672010-02-11 22:22:22 -05001022// Write a GPT header (main or backup) to the specified sector. Used by both
1023// the SaveGPTData() and SaveGPTBackup() functions.
1024// Should be passed an architecture-appropriate header (DO NOT call
1025// ReverseHeaderBytes() on the header before calling this function)
1026// Returns 1 on success, 0 on failure
1027int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1028 int littleEndian, allOK = 1;
1029
1030 littleEndian = IsLittleEndian();
1031 if (!littleEndian)
1032 ReverseHeaderBytes(header);
1033 if (disk.Seek(sector)) {
1034 if (disk.Write(header, 512) == -1)
1035 allOK = 0;
1036 } else allOK = 0; // if (disk.Seek()...)
1037 if (!littleEndian)
1038 ReverseHeaderBytes(header);
1039 return allOK;
1040} // GPTData::SaveHeader()
1041
1042// Save the partitions to the specified sector. Used by both the SaveGPTData()
1043// and SaveGPTBackup() functions.
1044// Should be passed an architecture-appropriate header (DO NOT call
1045// ReverseHeaderBytes() on the header before calling this function)
1046// Returns 1 on success, 0 on failure
1047int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1048 int littleEndian, allOK = 1;
1049
1050 littleEndian = IsLittleEndian();
1051 if (disk.Seek(sector)) {
1052 if (!littleEndian)
1053 ReversePartitionBytes();
1054 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1055 allOK = 0;
1056 if (!littleEndian)
1057 ReversePartitionBytes();
1058 } else allOK = 0; // if (myDisk.Seek()...)
1059 return allOK;
1060} // GPTData::SavePartitionTable()
1061
srs5694e7b4ff92009-08-18 13:16:10 -04001062// Load GPT data from a backup file created by SaveGPTBackup(). This function
1063// does minimal error checking. It returns 1 if it completed successfully,
1064// 0 if there was a problem. In the latter case, it creates a new empty
1065// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001066int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001067 int allOK = 1, val, err;
1068 uint32_t numParts, sizeOfEntries;
1069 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001070 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001071
srs5694546a9c72010-01-26 16:00:26 -05001072 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001073 if (IsLittleEndian() == 0)
1074 littleEndian = 0;
1075
srs5694e7b4ff92009-08-18 13:16:10 -04001076 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001077 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001078
srs5694cb76c672010-02-11 22:22:22 -05001079 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001080
srs5694cb76c672010-02-11 22:22:22 -05001081 // Check backup file size and rebuild second header if file is right
1082 // size to be direct dd copy of MBR, main header, and main partition
1083 // table; if other size, treat it like a GPT fdisk-generated backup
1084 // file
1085 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1086 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1087 if (shortBackup) {
1088 RebuildSecondHeader();
1089 secondCrcOk = mainCrcOk;
1090 } else {
1091 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1092 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001093
srs5694e7b4ff92009-08-18 13:16:10 -04001094 // Return valid headers code: 0 = both headers bad; 1 = main header
1095 // good, backup bad; 2 = backup header good, main header bad;
1096 // 3 = both headers good. Note these codes refer to valid GPT
1097 // signatures and version numbers; more subtle problems will elude
1098 // this check!
1099 if ((val = CheckHeaderValidity()) > 0) {
1100 if (val == 2) { // only backup header seems to be good
1101 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001102 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001103 } else { // main header is OK
1104 numParts = mainHeader.numParts;
1105 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1106 } // if/else
1107
1108 SetGPTSize(numParts);
1109
srs5694e7b4ff92009-08-18 13:16:10 -04001110 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001111 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1112 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001113 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001114 } // if
1115
srs5694cb76c672010-02-11 22:22:22 -05001116 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1117 cerr << "Warning! Read error " << errno
1118 << " loading partition table; strange behavior now likely!\n";
srs56942a9f5da2009-08-26 00:48:01 -04001119
srs5694e7b4ff92009-08-18 13:16:10 -04001120 } else {
1121 allOK = 0;
1122 } // if/else
1123 } else {
1124 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001125 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001126 } // if/else
1127
1128 // Something went badly wrong, so blank out partitions
1129 if (allOK == 0) {
1130 ClearGPTData();
1131 protectiveMBR.MakeProtectiveMBR();
1132 } // if
1133 return allOK;
1134} // GPTData::LoadGPTBackup()
1135
srs569408bb0da2010-02-19 17:19:55 -05001136int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001137 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001138} // GPTData::SaveMBR()
1139
1140// This function destroys the on-disk GPT structures, but NOT the on-disk
1141// MBR.
1142// Returns 1 if the operation succeeds, 0 if not.
1143int GPTData::DestroyGPT(void) {
1144 int i, sum, tableSize, allOK = 1;
1145 uint8_t blankSector[512];
1146 uint8_t* emptyTable;
1147
1148 for (i = 0; i < 512; i++) {
1149 blankSector[i] = 0;
1150 } // for
1151
1152 if (myDisk.OpenForWrite()) {
1153 if (!myDisk.Seek(mainHeader.currentLBA))
1154 allOK = 0;
1155 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1156 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1157 allOK = 0;
1158 } // if
1159 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1160 allOK = 0;
1161 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
1162 emptyTable = new uint8_t[tableSize];
1163 for (i = 0; i < tableSize; i++)
1164 emptyTable[i] = 0;
1165 if (allOK) {
1166 sum = myDisk.Write(emptyTable, tableSize);
1167 if (sum != tableSize) {
1168 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1169 allOK = 0;
1170 } // if write failed
1171 } // if
1172 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1173 allOK = 0;
1174 if (allOK) {
1175 sum = myDisk.Write(emptyTable, tableSize);
1176 if (sum != tableSize) {
1177 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1178 << errno << "\n";
1179 allOK = 0;
1180 } // if wrong size written
1181 } // if
1182 if (!myDisk.Seek(secondHeader.currentLBA))
1183 allOK = 0;
1184 if (allOK) {
1185 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1186 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1187 allOK = 0;
1188 } // if
1189 } // if
1190 myDisk.DiskSync();
1191 myDisk.Close();
1192 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1193 << "other utilities.\n";
1194 delete[] emptyTable;
1195 } else {
1196 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1197 } // if/else (fd != -1)
1198 return (allOK);
1199} // GPTDataTextUI::DestroyGPT()
1200
1201// Wipe MBR data from the disk (zero it out completely)
1202// Returns 1 on success, 0 on failure.
1203int GPTData::DestroyMBR(void) {
1204 int allOK = 1, i;
1205 uint8_t blankSector[512];
1206
1207 for (i = 0; i < 512; i++)
1208 blankSector[i] = 0;
1209
1210 if (myDisk.OpenForWrite()) {
1211 if (myDisk.Seek(0)) {
1212 if (myDisk.Write(blankSector, 512) != 512)
1213 allOK = 0;
1214 } else allOK = 0;
1215 } else allOK = 0;
1216 if (!allOK)
1217 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1218 return allOK;
1219} // GPTData::DestroyMBR(void)
1220
srs5694e4ac11e2009-08-31 10:13:04 -04001221// Tell user whether Apple Partition Map (APM) was discovered....
1222void GPTData::ShowAPMState(void) {
1223 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001224 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001225 else
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001227} // GPTData::ShowAPMState()
1228
1229// Tell user about the state of the GPT data....
1230void GPTData::ShowGPTState(void) {
1231 switch (state) {
1232 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001233 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001234 break;
1235 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001236 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001237 break;
1238 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001239 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001240 break;
1241 default:
srs5694fed16d02010-01-27 23:03:40 -05001242 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001243 break;
1244 } // switch
1245} // GPTData::ShowGPTState()
1246
1247// Display the basic GPT data
1248void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001249 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001250 uint64_t temp, totalFree;
1251
srs5694fed16d02010-01-27 23:03:40 -05001252 cout << "Disk " << device << ": " << diskSize << " sectors, "
1253 << BytesToSI(diskSize * blockSize) << "\n";
1254 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001255 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001256 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1257 cout << "First usable sector is " << mainHeader.firstUsableLBA
1258 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001259 totalFree = FindFreeBlocks(&i, &temp);
srs5694fed16d02010-01-27 23:03:40 -05001260 cout << "Total free space is " << totalFree << " sectors ("
1261 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1262 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001263 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001264 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001265 } // for
1266} // GPTData::DisplayGPTData()
1267
srs5694e4ac11e2009-08-31 10:13:04 -04001268// Show detailed information on the specified partition
1269void GPTData::ShowPartDetails(uint32_t partNum) {
1270 if (partitions[partNum].GetFirstLBA() != 0) {
1271 partitions[partNum].ShowDetails(blockSize);
1272 } else {
srs5694fed16d02010-01-27 23:03:40 -05001273 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001274 } // if
1275} // GPTData::ShowPartDetails()
1276
srs5694e4ac11e2009-08-31 10:13:04 -04001277/**************************************************************************
1278 * *
1279 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1280 * (some of these functions may require user interaction) *
1281 * *
1282 **************************************************************************/
1283
srs569408bb0da2010-02-19 17:19:55 -05001284// Examines the MBR & GPT data to determine which set of data to use: the
1285// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1286// a new set of partitions (use_new). A return value of use_abort indicates
1287// that this function couldn't determine what to do. Overriding functions
1288// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001289WhichToUse GPTData::UseWhichPartitions(void) {
1290 WhichToUse which = use_new;
1291 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001292
1293 mbrState = protectiveMBR.GetValidity();
1294
1295 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001296 cout << "\n***************************************************************\n"
1297 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001298 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001299 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1300 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001301 } // if
srs5694fed16d02010-01-27 23:03:40 -05001302 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001303 which = use_mbr;
1304 } // if
1305
1306 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001307 cout << "\n**********************************************************************\n"
1308 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1309 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001310 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001311 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1312 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1313 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001314 } // if
srs5694fed16d02010-01-27 23:03:40 -05001315 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001316 which = use_bsd;
1317 } // if
1318
1319 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001320 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001321 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001322 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001323 } // if
1324 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001325 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001326 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001327 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001328 } // if
1329 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001330 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001331 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001332 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001333 } // if
1334 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001335 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001336 } // if
1337
srs5694e4ac11e2009-08-31 10:13:04 -04001338 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001339 if (mbrState == gpt) {
1340 cout << "\a\a****************************************************************************\n"
1341 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1342 << "verification and recovery are STRONGLY recommended.\n"
1343 << "****************************************************************************\n";
1344 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001345 } else {
srs569408bb0da2010-02-19 17:19:55 -05001346 which = use_abort;
1347 } // if/else MBR says disk is GPT
1348 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001349
1350 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001351 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001352
1353 return which;
1354} // UseWhichPartitions()
1355
srs569408bb0da2010-02-19 17:19:55 -05001356// Convert MBR partition table into GPT form.
1357void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001358 int i, numToConvert;
1359 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001360
1361 // Clear out old data & prepare basics....
1362 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001363 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001364
1365 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001366 if (mainHeader.numParts > (MAX_MBR_PARTS))
1367 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001368 else
1369 numToConvert = mainHeader.numParts;
1370
1371 for (i = 0; i < numToConvert; i++) {
1372 origType = protectiveMBR.GetType(i);
1373 // don't waste CPU time trying to convert extended, hybrid protective, or
1374 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001375 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001376 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001377 partitions[i] = protectiveMBR.AsGPT(i);
1378 } // for
1379
1380 // Convert MBR into protective MBR
1381 protectiveMBR.MakeProtectiveMBR();
1382
1383 // Record that all original CRCs were OK so as not to raise flags
1384 // when doing a disk verification
1385 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001386} // GPTData::XFormPartitions()
1387
1388// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001389// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001390// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001391int GPTData::XFormDisklabel(uint32_t partNum) {
1392 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001393 int goOn = 1, numDone = 0;
1394 BSDData disklabel;
1395
srs569408bb0da2010-02-19 17:19:55 -05001396 if (GetPartRange(&low, &high) == 0) {
1397 goOn = 0;
1398 cout << "No partitions!\n";
1399 } // if
1400 if (partNum > high) {
1401 goOn = 0;
1402 cout << "Specified partition is invalid!\n";
1403 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001404
srs569408bb0da2010-02-19 17:19:55 -05001405 // If all is OK, read the disklabel and convert it.
1406 if (goOn) {
1407 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1408 partitions[partNum].GetLastLBA());
1409 if ((goOn) && (disklabel.IsDisklabel())) {
1410 numDone = XFormDisklabel(&disklabel);
1411 if (numDone == 1)
1412 cout << "Converted 1 BSD partition.\n";
1413 else
1414 cout << "Converted " << numDone << " BSD partitions.\n";
1415 } else {
1416 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1417 } // if/else
1418 } // if
1419 if (numDone > 0) { // converted partitions; delete carrier
1420 partitions[partNum].BlankPartition();
1421 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001422 return numDone;
srs569455d92612010-03-07 22:16:07 -05001423} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001424
1425// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001426int GPTData::XFormDisklabel(BSDData* disklabel) {
1427 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001428
srs569408bb0da2010-02-19 17:19:55 -05001429 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001430 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001431 partNum = FindFirstFreePart();
1432 if (partNum >= 0) {
1433 partitions[partNum] = disklabel->AsGPT(i);
1434 if (partitions[partNum].IsUsed())
1435 numDone++;
1436 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001437 } // for
srs569408bb0da2010-02-19 17:19:55 -05001438 if (partNum == -1)
1439 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001440 } // if
1441
1442 // Record that all original CRCs were OK so as not to raise flags
1443 // when doing a disk verification
1444 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1445
1446 return numDone;
1447} // GPTData::XFormDisklabel(BSDData* disklabel)
1448
srs569408bb0da2010-02-19 17:19:55 -05001449// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1450// partition has the active/bootable flag UNset and uses the GPT fdisk
1451// type code divided by 0x0100 as the MBR type code.
1452// Returns 1 if operation was 100% successful, 0 if there were ANY
1453// problems.
srs5694978041c2009-09-21 20:51:47 -04001454int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001455 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001456
srs5694978041c2009-09-21 20:51:47 -04001457 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001458 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001459 allOK = 0;
1460 } // if
1461 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001462 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001463 allOK = 0;
1464 } // if
1465 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001466 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001467 allOK = 0;
1468 } // if
1469 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1470 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1471 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001472 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1473 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001474 } // if
srs5694978041c2009-09-21 20:51:47 -04001475 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001476 (uint32_t) partitions[gptPart].GetLengthLBA(),
1477 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001478 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001479 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1480 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1481 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001482 allOK = 0;
1483 } // if/else
1484 return allOK;
1485} // GPTData::OnePartToMBR()
1486
srs569455d92612010-03-07 22:16:07 -05001487// Convert partitions to MBR form (primary and logical) and return
1488// the number done. Partitions are specified in a PartNotes variable,
1489// which includes pointers to GPT partition numbers. A partition number
1490// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1491// location in the table, and MBR_EMPTY means not to create a partition
1492// in that table position. If the partition type entry for a partition
1493// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001494// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001495// protective partitions or extended partitions.
1496int GPTData::PartsToMBR(PartNotes & notes) {
1497 int mbrNum = 0, numConverted = 0;
1498 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001499
srs569455d92612010-03-07 22:16:07 -05001500 protectiveMBR.EmptyMBR();
1501 protectiveMBR.SetDiskSize(diskSize);
1502 notes.Rewind();
1503 while (notes.GetNextInfo(&convInfo) >= 0) {
1504 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1505 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1506 if (convInfo.hexCode != 0)
1507 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1508 if (convInfo.active)
1509 protectiveMBR.SetPartBootable(mbrNum);
1510 mbrNum++;
1511 } // if
1512 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1513 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1514 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1515 protectiveMBR.SetHybrid();
1516 } else {
1517 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1518 } // if/else
1519 mbrNum++;
1520 } // if EFI GPT partition specified
1521 } // for
1522 // Now do logical partition(s)...
1523 protectiveMBR.SetDisk(&myDisk);
1524 numConverted += protectiveMBR.CreateLogicals(notes);
1525// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001526 return numConverted;
1527} // GPTData::PartsToMBR()
1528
srs5694e4ac11e2009-08-31 10:13:04 -04001529
1530/**********************************************************************
1531 * *
1532 * Functions that adjust GPT data structures WITHOUT user interaction *
1533 * (they may display information for the user's benefit, though) *
1534 * *
1535 **********************************************************************/
1536
1537// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001538// necessary, copies data if it already exists. Returns 1 if all goes
1539// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001540int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001541 GPTPart* newParts;
1542 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001543 uint32_t i, high, copyNum;
1544 int allOK = 1;
1545
1546 // First, adjust numEntries upward, if necessary, to get a number
1547 // that fills the allocated sectors
1548 i = blockSize / GPT_SIZE;
1549 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001550 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001551 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001552 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001553 } // if
1554
srs5694247657a2009-11-26 18:36:12 -05001555 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001556 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001557 // partition table, which causes problems when loading data from a RAID
1558 // array that's been expanded because this function is called when loading
1559 // data.
srs569455d92612010-03-07 22:16:07 -05001560 if (((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1561 || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001562 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001563 if (newParts != NULL) {
1564 if (partitions != NULL) { // existing partitions; copy them over
1565 GetPartRange(&i, &high);
1566 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001567 cout << "The highest-numbered partition is " << high + 1
1568 << ", which is greater than the requested\n"
1569 << "partition table size of " << numEntries
1570 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001571 allOK = 0;
1572 } else { // go ahead with copy
1573 if (numEntries < mainHeader.numParts)
1574 copyNum = numEntries;
1575 else
1576 copyNum = mainHeader.numParts;
1577 for (i = 0; i < copyNum; i++) {
1578 newParts[i] = partitions[i];
1579 } // for
1580 trash = partitions;
1581 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001582 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001583 } // if
1584 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001585 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001586 } // if/else existing partitions
1587 mainHeader.numParts = numEntries;
1588 secondHeader.numParts = numEntries;
1589 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1590 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1591 MoveSecondHeaderToEnd();
1592 if (diskSize > 0)
1593 CheckGPTSize();
1594 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001595 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001596 allOK = 0;
1597 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001598 } // if/else
1599 return (allOK);
1600} // GPTData::SetGPTSize()
1601
1602// Blank the partition array
1603void GPTData::BlankPartitions(void) {
1604 uint32_t i;
1605
1606 for (i = 0; i < mainHeader.numParts; i++) {
1607 partitions[i].BlankPartition();
1608 } // for
1609} // GPTData::BlankPartitions()
1610
srs5694ba00fed2010-01-12 18:18:36 -05001611// Delete a partition by number. Returns 1 if successful,
1612// 0 if there was a problem. Returns 1 if partition was in
1613// range, 0 if it was out of range.
1614int GPTData::DeletePartition(uint32_t partNum) {
1615 uint64_t startSector, length;
1616 uint32_t low, high, numParts, retval = 1;;
1617
1618 numParts = GetPartRange(&low, &high);
1619 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1620 // In case there's a protective MBR, look for & delete matching
1621 // MBR partition....
1622 startSector = partitions[partNum].GetFirstLBA();
1623 length = partitions[partNum].GetLengthLBA();
1624 protectiveMBR.DeleteByLocation(startSector, length);
1625
1626 // Now delete the GPT partition
1627 partitions[partNum].BlankPartition();
1628 } else {
srs5694fed16d02010-01-27 23:03:40 -05001629 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001630 retval = 0;
1631 } // if/else
1632 return retval;
1633} // GPTData::DeletePartition(uint32_t partNum)
1634
srs569408bb0da2010-02-19 17:19:55 -05001635// Non-interactively create a partition.
1636// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001637uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001638 int retval = 1; // assume there'll be no problems
1639
1640 if (IsFreePartNum(partNum)) {
1641 Align(&startSector); // Align sector to correct multiple
1642 if (IsFree(startSector) && (startSector <= endSector)) {
1643 if (FindLastInFree(startSector) >= endSector) {
1644 partitions[partNum].SetFirstLBA(startSector);
1645 partitions[partNum].SetLastLBA(endSector);
1646 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001647 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001648 } else retval = 0; // if free space until endSector
1649 } else retval = 0; // if startSector is free
1650 } else retval = 0; // if legal partition number
1651 return retval;
1652} // GPTData::CreatePartition(partNum, startSector, endSector)
1653
srs5694e4ac11e2009-08-31 10:13:04 -04001654// Sort the GPT entries, eliminating gaps and making for a logical
1655// ordering. Relies on QuickSortGPT() for the bulk of the work
1656void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001657 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001658
1659 // First, find the last partition with data, so as not to
1660 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001661 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001662
1663 // Now swap empties with the last partitions, to simplify the logic
1664 // in the Quicksort function....
1665 i = 0;
1666 while (i < lastPart) {
1667 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001668 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001669 do {
1670 lastPart--;
1671 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001672 } // if
1673 i++;
1674 } // while
1675
srs5694546a9c72010-01-26 16:00:26 -05001676 // If there are more empties than partitions in the range from 0 to lastPart,
1677 // the above leaves lastPart set too high, so we've got to adjust it to
1678 // prevent empties from migrating to the top of the list....
1679 GetPartRange(&firstPart, &lastPart);
1680
srs5694e4ac11e2009-08-31 10:13:04 -04001681 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001682 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001683} // GPTData::SortGPT()
1684
srs569408bb0da2010-02-19 17:19:55 -05001685// Recursive quick sort algorithm for GPT partitions. Note that if there
1686// are any empties in the specified range, they'll be sorted to the
1687// start, resulting in a sorted set of partitions that begins with
1688// partition 2, 3, or higher.
1689void GPTData::QuickSortGPT(int start, int finish) {
1690 uint64_t starterValue; // starting location of median partition
1691 int left, right;
1692
1693 left = start;
1694 right = finish;
1695 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1696 do {
1697 while (partitions[left].GetFirstLBA() < starterValue)
1698 left++;
1699 while (partitions[right].GetFirstLBA() > starterValue)
1700 right--;
1701 if (left <= right)
1702 SwapPartitions(left++, right--);
1703 } while (left <= right);
1704 if (start < right) QuickSortGPT(start, right);
1705 if (finish > left) QuickSortGPT(left, finish);
1706} // GPTData::QuickSortGPT()
1707
1708// Swap the contents of two partitions.
1709// Returns 1 if successful, 0 if either partition is out of range
1710// (that is, not a legal number; either or both can be empty).
1711// Note that if partNum1 = partNum2 and this number is in range,
1712// it will be considered successful.
1713int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1714 GPTPart temp;
1715 int allOK = 1;
1716
1717 if ((partNum1 < mainHeader.numParts) && (partNum2 < mainHeader.numParts)) {
1718 if (partNum1 != partNum2) {
1719 temp = partitions[partNum1];
1720 partitions[partNum1] = partitions[partNum2];
1721 partitions[partNum2] = temp;
1722 } // if
1723 } else allOK = 0; // partition numbers are valid
1724 return allOK;
1725} // GPTData::SwapPartitions()
1726
srs5694e4ac11e2009-08-31 10:13:04 -04001727// Set up data structures for entirely new set of partitions on the
1728// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001729// Note that this function does NOT clear the protectiveMBR data
1730// structure, since it may hold the original MBR partitions if the
1731// program was launched on an MBR disk, and those may need to be
1732// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001733int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001734 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001735
1736 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001737 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001738 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001739 partitions = NULL;
1740 SetGPTSize(NUM_GPT_ENTRIES);
1741
1742 // Now initialize a bunch of stuff that's static....
1743 mainHeader.signature = GPT_SIGNATURE;
1744 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001745 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001746 mainHeader.reserved = 0;
1747 mainHeader.currentLBA = UINT64_C(1);
1748 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1749 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1750 for (i = 0; i < GPT_RESERVED; i++) {
1751 mainHeader.reserved2[i] = '\0';
1752 } // for
1753
1754 // Now some semi-static items (computed based on end of disk)
1755 mainHeader.backupLBA = diskSize - UINT64_C(1);
1756 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1757
1758 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001759 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001760
1761 // Copy main header to backup header
1762 RebuildSecondHeader();
1763
1764 // Blank out the partitions array....
1765 BlankPartitions();
1766
1767 // Flag all CRCs as being OK....
1768 mainCrcOk = 1;
1769 secondCrcOk = 1;
1770 mainPartsCrcOk = 1;
1771 secondPartsCrcOk = 1;
1772
1773 return (goOn);
1774} // GPTData::ClearGPTData()
1775
srs5694247657a2009-11-26 18:36:12 -05001776// Set the location of the second GPT header data to the end of the disk.
1777// Used internally and called by the 'e' option on the recovery &
1778// transformation menu, to help users of RAID arrays who add disk space
1779// to their arrays.
1780void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001781 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1782 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1783 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1784} // GPTData::FixSecondHeaderLocation()
1785
srs56940a697312010-01-28 21:10:52 -05001786int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001787 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001788
1789 if (!IsFreePartNum(partNum)) {
1790 partitions[partNum].SetName(theName);
1791 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001792
1793 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001794} // GPTData::SetName
1795
1796// Set the disk GUID to the specified value. Note that the header CRCs must
1797// be recomputed after calling this function.
1798void GPTData::SetDiskGUID(GUIDData newGUID) {
1799 mainHeader.diskGUID = newGUID;
1800 secondHeader.diskGUID = newGUID;
1801} // SetDiskGUID()
1802
1803// Set the unique GUID of the specified partition. Returns 1 on
1804// successful completion, 0 if there were problems (invalid
1805// partition number).
1806int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1807 int retval = 0;
1808
1809 if (pn < mainHeader.numParts) {
1810 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1811 partitions[pn].SetUniqueGUID(theGUID);
1812 retval = 1;
1813 } // if
1814 } // if
1815 return retval;
1816} // GPTData::SetPartitionGUID()
1817
srs5694ba00fed2010-01-12 18:18:36 -05001818// Change partition type code non-interactively. Returns 1 if
1819// successful, 0 if not....
1820int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1821 int retval = 1;
1822
1823 if (!IsFreePartNum(partNum)) {
1824 partitions[partNum].SetType(hexCode);
1825 } else retval = 0;
1826 return retval;
1827} // GPTData::ChangePartType()
1828
srs56941d1448a2009-12-31 21:20:19 -05001829// Adjust sector number so that it falls on a sector boundary that's a
1830// multiple of sectorAlignment. This is done to improve the performance
1831// of Western Digital Advanced Format disks and disks with similar
1832// technology from other companies, which use 4096-byte sectors
1833// internally although they translate to 512-byte sectors for the
1834// benefit of the OS. If partitions aren't properly aligned on these
1835// disks, some filesystem data structures can span multiple physical
1836// sectors, degrading performance. This function should be called
1837// only on the FIRST sector of the partition, not the last!
1838// This function returns 1 if the alignment was altered, 0 if it
1839// was unchanged.
1840int GPTData::Align(uint64_t* sector) {
1841 int retval = 0, sectorOK = 0;
1842 uint64_t earlier, later, testSector, original;
1843
1844 if ((*sector % sectorAlignment) != 0) {
1845 original = *sector;
1846 retval = 1;
1847 earlier = (*sector / sectorAlignment) * sectorAlignment;
1848 later = earlier + (uint64_t) sectorAlignment;
1849
1850 // Check to see that every sector between the earlier one and the
1851 // requested one is clear, and that it's not too early....
1852 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001853 sectorOK = 1;
1854 testSector = earlier;
1855 do {
1856 sectorOK = IsFree(testSector++);
1857 } while ((sectorOK == 1) && (testSector < *sector));
1858 if (sectorOK == 1) {
1859 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001860 } // if
1861 } // if firstUsableLBA check
1862
1863 // If couldn't move the sector earlier, try to move it later instead....
1864 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1865 sectorOK = 1;
1866 testSector = later;
1867 do {
1868 sectorOK = IsFree(testSector--);
1869 } while ((sectorOK == 1) && (testSector > *sector));
1870 if (sectorOK == 1) {
1871 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001872 } // if
1873 } // if
1874
1875 // If sector was changed successfully, inform the user of this fact.
1876 // Otherwise, notify the user that it couldn't be done....
1877 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001878 cout << "Information: Moved requested sector from " << original << " to "
1879 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001880 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001881 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001882 } else {
srs5694fed16d02010-01-27 23:03:40 -05001883 cout << "Information: Sector not aligned on " << sectorAlignment
1884 << "-sector boundary and could not be moved.\n"
1885 << "If you're using a Western Digital Advanced Format or similar disk with\n"
1886 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001887 retval = 0;
1888 } // if/else
1889 } // if
1890 return retval;
1891} // GPTData::Align()
1892
srs5694e4ac11e2009-08-31 10:13:04 -04001893/********************************************************
1894 * *
1895 * Functions that return data about GPT data structures *
1896 * (most of these are inline in gpt.h) *
1897 * *
1898 ********************************************************/
1899
1900// Find the low and high used partition numbers (numbered from 0).
1901// Return value is the number of partitions found. Note that the
1902// *low and *high values are both set to 0 when no partitions
1903// are found, as well as when a single partition in the first
1904// position exists. Thus, the return value is the only way to
1905// tell when no partitions exist.
1906int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1907 uint32_t i;
1908 int numFound = 0;
1909
1910 *low = mainHeader.numParts + 1; // code for "not found"
1911 *high = 0;
1912 if (mainHeader.numParts > 0) { // only try if partition table exists...
1913 for (i = 0; i < mainHeader.numParts; i++) {
1914 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1915 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001916 // Set the low value only if it's not yet found...
srs5694e4ac11e2009-08-31 10:13:04 -04001917 if (*low == (mainHeader.numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001918 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001919 } // if
1920 } // for
1921 } // if
1922
1923 // Above will leave *low pointing to its "not found" value if no partitions
1924 // are defined, so reset to 0 if this is the case....
1925 if (*low == (mainHeader.numParts + 1))
1926 *low = 0;
1927 return numFound;
1928} // GPTData::GetPartRange()
1929
srs569408bb0da2010-02-19 17:19:55 -05001930// Returns the value of the first free partition, or -1 if none is
1931// unused.
1932int GPTData::FindFirstFreePart(void) {
1933 int i = 0;
1934
1935 if (partitions != NULL) {
1936 while ((partitions[i].IsUsed()) && (i < (int) mainHeader.numParts))
1937 i++;
1938 if (i >= (int) mainHeader.numParts)
1939 i = -1;
1940 } else i = -1;
1941 return i;
1942} // GPTData::FindFirstFreePart()
1943
srs5694978041c2009-09-21 20:51:47 -04001944// Returns the number of defined partitions.
1945uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001946 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001947
1948 for (i = 0; i < mainHeader.numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001949 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001950 counted++;
1951 } // for
1952 return counted;
1953} // GPTData::CountParts()
1954
srs5694e4ac11e2009-08-31 10:13:04 -04001955/****************************************************
1956 * *
1957 * Functions that return data about disk free space *
1958 * *
1959 ****************************************************/
1960
1961// Find the first available block after the starting point; returns 0 if
1962// there are no available blocks left
1963uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1964 uint64_t first;
1965 uint32_t i;
1966 int firstMoved = 0;
1967
1968 // Begin from the specified starting point or from the first usable
1969 // LBA, whichever is greater...
1970 if (start < mainHeader.firstUsableLBA)
1971 first = mainHeader.firstUsableLBA;
1972 else
1973 first = start;
1974
1975 // ...now search through all partitions; if first is within an
1976 // existing partition, move it to the next sector after that
1977 // partition and repeat. If first was moved, set firstMoved
1978 // flag; repeat until firstMoved is not set, so as to catch
1979 // cases where partitions are out of sequential order....
1980 do {
1981 firstMoved = 0;
1982 for (i = 0; i < mainHeader.numParts; i++) {
1983 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001984 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001985 first = partitions[i].GetLastLBA() + 1;
1986 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001987 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001988 } // for
1989 } while (firstMoved == 1);
1990 if (first > mainHeader.lastUsableLBA)
1991 first = 0;
1992 return (first);
1993} // GPTData::FindFirstAvailable()
1994
1995// Finds the first available sector in the largest block of unallocated
1996// space on the disk. Returns 0 if there are no available blocks left
1997uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001998 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001999
2000 start = 0;
2001 do {
2002 firstBlock = FindFirstAvailable(start);
2003 if (firstBlock != UINT32_C(0)) { // something's free...
2004 lastBlock = FindLastInFree(firstBlock);
2005 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2006 if (segmentSize > selectedSize) {
2007 selectedSize = segmentSize;
2008 selectedSegment = firstBlock;
2009 } // if
2010 start = lastBlock + 1;
2011 } // if
2012 } while (firstBlock != 0);
2013 return selectedSegment;
2014} // GPTData::FindFirstInLargest()
2015
srs5694cb76c672010-02-11 22:22:22 -05002016// Find the last available block on the disk.
2017// Returns 0 if there are no available partitions
2018uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002019 uint64_t last;
2020 uint32_t i;
2021 int lastMoved = 0;
2022
2023 // Start by assuming the last usable LBA is available....
2024 last = mainHeader.lastUsableLBA;
2025
2026 // ...now, similar to algorithm in FindFirstAvailable(), search
2027 // through all partitions, moving last when it's in an existing
2028 // partition. Set the lastMoved flag so we repeat to catch cases
2029 // where partitions are out of logical order.
2030 do {
2031 lastMoved = 0;
2032 for (i = 0; i < mainHeader.numParts; i++) {
2033 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002034 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002035 last = partitions[i].GetFirstLBA() - 1;
2036 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002037 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002038 } // for
2039 } while (lastMoved == 1);
2040 if (last < mainHeader.firstUsableLBA)
2041 last = 0;
2042 return (last);
2043} // GPTData::FindLastAvailable()
2044
2045// Find the last available block in the free space pointed to by start.
2046uint64_t GPTData::FindLastInFree(uint64_t start) {
2047 uint64_t nearestStart;
2048 uint32_t i;
2049
2050 nearestStart = mainHeader.lastUsableLBA;
2051 for (i = 0; i < mainHeader.numParts; i++) {
2052 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002053 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002054 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002055 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002056 } // for
2057 return (nearestStart);
2058} // GPTData::FindLastInFree()
2059
2060// Finds the total number of free blocks, the number of segments in which
2061// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002062uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002063 uint64_t start = UINT64_C(0); // starting point for each search
2064 uint64_t totalFound = UINT64_C(0); // running total
2065 uint64_t firstBlock; // first block in a segment
2066 uint64_t lastBlock; // last block in a segment
2067 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002068 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002069
2070 *largestSegment = UINT64_C(0);
2071 do {
2072 firstBlock = FindFirstAvailable(start);
2073 if (firstBlock != UINT64_C(0)) { // something's free...
2074 lastBlock = FindLastInFree(firstBlock);
2075 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2076 if (segmentSize > *largestSegment) {
2077 *largestSegment = segmentSize;
2078 } // if
2079 totalFound += segmentSize;
2080 num++;
2081 start = lastBlock + 1;
2082 } // if
2083 } while (firstBlock != 0);
2084 *numSegments = num;
2085 return totalFound;
2086} // GPTData::FindFreeBlocks()
2087
srs569455d92612010-03-07 22:16:07 -05002088// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2089// If it's allocated, return the partition number to which it's allocated
2090// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2091// returned in partNum if the sector is in use by basic GPT data structures.)
2092int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002093 int isFree = 1;
2094 uint32_t i;
2095
2096 for (i = 0; i < mainHeader.numParts; i++) {
2097 if ((sector >= partitions[i].GetFirstLBA()) &&
2098 (sector <= partitions[i].GetLastLBA())) {
2099 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002100 if (partNum != NULL)
2101 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002102 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002103 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002104 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002105 (sector > mainHeader.lastUsableLBA)) {
2106 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002107 if (partNum != NULL)
2108 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002109 } // if
2110 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002111} // GPTData::IsFree()
2112
srs5694ba00fed2010-01-12 18:18:36 -05002113// Returns 1 if partNum is unused.
2114int GPTData::IsFreePartNum(uint32_t partNum) {
2115 int retval = 1;
2116
srs569408bb0da2010-02-19 17:19:55 -05002117 if ((partNum < mainHeader.numParts) && (partitions != NULL)) {
2118 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002119 retval = 0;
2120 } // if partition is in use
2121 } else retval = 0;
2122
2123 return retval;
2124} // GPTData::IsFreePartNum()
2125
srs5694e4ac11e2009-08-31 10:13:04 -04002126/********************************
2127 * *
2128 * Endianness support functions *
2129 * *
2130 ********************************/
2131
srs56942a9f5da2009-08-26 00:48:01 -04002132void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002133 ReverseBytes(&header->signature, 8);
2134 ReverseBytes(&header->revision, 4);
2135 ReverseBytes(&header->headerSize, 4);
2136 ReverseBytes(&header->headerCRC, 4);
2137 ReverseBytes(&header->reserved, 4);
2138 ReverseBytes(&header->currentLBA, 8);
2139 ReverseBytes(&header->backupLBA, 8);
2140 ReverseBytes(&header->firstUsableLBA, 8);
2141 ReverseBytes(&header->lastUsableLBA, 8);
2142 ReverseBytes(&header->partitionEntriesLBA, 8);
2143 ReverseBytes(&header->numParts, 4);
2144 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2145 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002146 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002147} // GPTData::ReverseHeaderBytes()
2148
2149// IMPORTANT NOTE: This function requires non-reversed mainHeader
2150// structure!
2151void GPTData::ReversePartitionBytes() {
2152 uint32_t i;
2153
2154 // Check GPT signature on big-endian systems; this will mismatch
2155 // if the function is called out of order. Unfortunately, it'll also
2156 // mismatch if there's data corruption.
2157 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002158 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2159 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002160 } // if signature mismatch....
2161 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002162 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002163 } // for
2164} // GPTData::ReversePartitionBytes()
2165
2166/******************************************
2167 * *
2168 * Additional non-class support functions *
2169 * *
2170 ******************************************/
2171
srs5694e7b4ff92009-08-18 13:16:10 -04002172// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2173// never fail these tests, but the struct types may fail depending on compile options.
2174// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2175// sizes.
2176int SizesOK(void) {
2177 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002178
2179 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002180 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002181 allOK = 0;
2182 } // if
2183 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002184 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002185 allOK = 0;
2186 } // if
2187 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002188 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002189 allOK = 0;
2190 } // if
2191 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002192 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002193 allOK = 0;
2194 } // if
2195 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002196 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002197 allOK = 0;
2198 } // if
srs5694978041c2009-09-21 20:51:47 -04002199 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002200 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002201 allOK = 0;
2202 } // if
2203 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002204 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002205 allOK = 0;
2206 } // if
srs5694221e0872009-08-29 15:00:31 -04002207 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002208 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002209 allOK = 0;
2210 } // if
srs56946699b012010-02-04 00:55:30 -05002211 if (sizeof(GUIDData) != 16) {
2212 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2213 allOK = 0;
2214 } // if
2215 if (sizeof(PartType) != 16) {
2216 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2217 allOK = 0;
2218 } // if
srs5694fed16d02010-01-27 23:03:40 -05002219 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002220 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002221 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2222 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002223 } // if
2224 return (allOK);
2225} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002226