blob: 2c5e1388766900e311c767ffdd15b9129835a7b5 [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
srs569464cbd172011-03-01 22:03:54 -05006/* This program is copyright (c) 2009-2011 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040022#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "crc32.h"
24#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040025#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040026#include "support.h"
27#include "parttypes.h"
28#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050029#include "diskio.h"
srs5694bf8950c2011-03-12 01:23:12 -050030//#include "partnotes.h"
srs5694e7b4ff92009-08-18 13:16:10 -040031
32using namespace std;
33
srs56948f1b2d62010-05-23 13:07:19 -040034#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040035#define log2(x) (log(x) / M_LN2)
36#endif // __FreeBSD__
37
srs56948f1b2d62010-05-23 13:07:19 -040038#ifdef _MSC_VER
39#define log2(x) (log((double) x) / log(2.0))
40#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040041
srs5694e7b4ff92009-08-18 13:16:10 -040042/****************************************
43 * *
44 * GPTData class and related structures *
45 * *
46 ****************************************/
47
srs5694e4ac11e2009-08-31 10:13:04 -040048// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040049GPTData::GPTData(void) {
50 blockSize = SECTOR_SIZE; // set a default
51 diskSize = 0;
52 partitions = NULL;
53 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050054 device = "";
srs56945d58fe02010-01-03 20:57:08 -050055 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040056 mainCrcOk = 0;
57 secondCrcOk = 0;
58 mainPartsCrcOk = 0;
59 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040060 apmFound = 0;
61 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040062 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050063 beQuiet = 0;
64 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050065 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040066 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040067 SetGPTSize(NUM_GPT_ENTRIES);
68} // GPTData default constructor
69
70// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050071GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040072 blockSize = SECTOR_SIZE; // set a default
73 diskSize = 0;
74 partitions = NULL;
75 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050076 device = "";
srs56945d58fe02010-01-03 20:57:08 -050077 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040078 mainCrcOk = 0;
79 secondCrcOk = 0;
80 mainPartsCrcOk = 0;
81 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040082 apmFound = 0;
83 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040084 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050085 beQuiet = 0;
86 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050087 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040088 numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050089 if (!LoadPartitions(filename))
90 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050091} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040092
srs5694e4ac11e2009-08-31 10:13:04 -040093// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040094GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050095 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040096} // GPTData destructor
97
srs569464cbd172011-03-01 22:03:54 -050098// Assignment operator
99GPTData & GPTData::operator=(const GPTData & orig) {
100 uint32_t i;
101
102 mainHeader = orig.mainHeader;
103 numParts = orig.numParts;
104 secondHeader = orig.secondHeader;
105 protectiveMBR = orig.protectiveMBR;
106 device = orig.device;
107 blockSize = orig.blockSize;
108 diskSize = orig.diskSize;
109 state = orig.state;
110 justLooking = orig.justLooking;
111 mainCrcOk = orig.mainCrcOk;
112 secondCrcOk = orig.secondCrcOk;
113 mainPartsCrcOk = orig.mainPartsCrcOk;
114 secondPartsCrcOk = orig.secondPartsCrcOk;
115 apmFound = orig.apmFound;
116 bsdFound = orig.bsdFound;
117 sectorAlignment = orig.sectorAlignment;
118 beQuiet = orig.beQuiet;
119 whichWasUsed = orig.whichWasUsed;
120
121 myDisk.OpenForRead(orig.myDisk.GetName());
122
123 delete[] partitions;
srs569401f7f082011-03-15 23:53:31 -0400124 partitions = new GPTPart [numParts];
srs569464cbd172011-03-01 22:03:54 -0500125 if (partitions != NULL) {
126 for (i = 0; i < numParts; i++) {
127 partitions[i] = orig.partitions[i];
128 }
129 } else {
130 numParts = 0;
131 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
132 << "Continuing, but strange problems may occur!\n";
133 } // if/else
134 return *this;
135} // GPTData::operator=()
136
srs5694e4ac11e2009-08-31 10:13:04 -0400137/*********************************************************************
138 * *
139 * Begin functions that verify data, or that adjust the verification *
140 * information (compute CRCs, rebuild headers) *
141 * *
142 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400143
srs5694e4ac11e2009-08-31 10:13:04 -0400144// Perform detailed verification, reporting on any problems found, but
145// do *NOT* recover from these problems. Returns the total number of
146// problems identified.
147int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500148 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500149 uint32_t i, numSegments;
150 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400151
152 // First, check for CRC errors in the GPT data....
153 if (!mainCrcOk) {
154 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500155 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
156 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
157 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
158 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400159 } // if
160 if (!mainPartsCrcOk) {
161 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500162 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
163 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
164 << "transformation menu). This report may be a false alarm if you've already\n"
165 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400166 } // if
167 if (!secondCrcOk) {
168 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500169 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
170 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
171 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
172 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400173 } // if
174 if (!secondPartsCrcOk) {
175 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500176 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
177 << "be corrupt. This program will automatically create a new backup partition\n"
178 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400179 } // if
180
srs5694978041c2009-09-21 20:51:47 -0400181 // Now check that the main and backup headers both point to themselves....
182 if (mainHeader.currentLBA != 1) {
183 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500184 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
185 << "is being automatically corrected, but it may be a symptom of more serious\n"
186 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400187 mainHeader.currentLBA = 1;
188 } // if
189 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
190 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500191 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
192 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
193 << "option on the experts' menu to adjust the secondary header's and partition\n"
194 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400195 } // if
196
197 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400198 if (mainHeader.currentLBA != secondHeader.backupLBA) {
199 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500200 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
201 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
202 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400203 } // if
204 if (mainHeader.backupLBA != secondHeader.currentLBA) {
205 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500206 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
207 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
208 << secondHeader.currentLBA << ").\n"
209 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400210 } // if
211 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
212 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500213 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
214 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
215 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400216 } // if
217 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
218 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500219 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
220 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
221 << secondHeader.lastUsableLBA << ")\n"
222 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400223 } // if
srs56946699b012010-02-04 00:55:30 -0500224 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400225 problems++;
srs56945a081752010-09-24 20:39:41 -0400226 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500227 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400228 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500229 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
230 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400231 } // if
232 if (mainHeader.numParts != secondHeader.numParts) {
233 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500234 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
235 << ") doesn't\nmatch the backup GPT header's number of partitions ("
236 << secondHeader.numParts << ")\n"
237 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400238 } // if
239 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
240 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500241 cout << "\nProblem: main GPT header's size of partition entries ("
242 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
243 << "match the backup GPT header's size of partition entries ("
244 << secondHeader.sizeOfPartitionEntries << ")\n"
245 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
246 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400247 } // if
248
249 // Now check for a few other miscellaneous problems...
250 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500251 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400252 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500253 cout << "\nProblem: Disk is too small to hold all the data!\n"
254 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500255 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500256 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400257 } // if
258
259 // Check for overlapping partitions....
260 problems += FindOverlaps();
261
srs569455d92612010-03-07 22:16:07 -0500262 // Check for insane partitions (start after end, hugely big, etc.)
263 problems += FindInsanePartitions();
264
srs5694e4ac11e2009-08-31 10:13:04 -0400265 // Check for mismatched MBR and GPT partitions...
266 problems += FindHybridMismatches();
267
srs5694327129e2010-09-22 01:07:31 -0400268 // Check for MBR-specific problems....
269 problems += VerifyMBR();
270
srs5694e4ac11e2009-08-31 10:13:04 -0400271 // Verify that partitions don't run into GPT data areas....
272 problems += CheckGPTSize();
273
srs56941d1448a2009-12-31 21:20:19 -0500274 // Check that partitions are aligned on proper boundaries (for WD Advanced
275 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400276 for (i = 0; i < numParts; i++) {
srs56941d1448a2009-12-31 21:20:19 -0500277 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500278 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
279 << sectorAlignment << "-sector boundary. This may\nresult "
280 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500281 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500282 } // if
283 } // for
srs569464cbd172011-03-01 22:03:54 -0500284 if (alignProbs > 0)
285 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
286 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500287
srs5694e4ac11e2009-08-31 10:13:04 -0400288 // Now compute available space, but only if no problems found, since
289 // problems could affect the results
290 if (problems == 0) {
291 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500292 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400293 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500294 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400295 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400296 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400297 } else {
srs56940a697312010-01-28 21:10:52 -0500298 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400299 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400300
301 return (problems);
302} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400303
304// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400305// do, issues a warning but takes no action. Returns number of problems
306// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400307int GPTData::CheckGPTSize(void) {
308 uint64_t overlap, firstUsedBlock, lastUsedBlock;
309 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400310 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400311
312 // first, locate the first & last used blocks
313 firstUsedBlock = UINT64_MAX;
314 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400315 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400316 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400317 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400318 firstUsedBlock = partitions[i].GetFirstLBA();
319 if (partitions[i].GetLastLBA() > lastUsedBlock)
320 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400321 } // for
322
323 // If the disk size is 0 (the default), then it means that various
324 // variables aren't yet set, so the below tests will be useless;
325 // therefore we should skip everything
326 if (diskSize != 0) {
327 if (mainHeader.firstUsableLBA > firstUsedBlock) {
328 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500329 cout << "Warning! Main partition table overlaps the first partition by "
330 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400331 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500332 cout << "Try reducing the partition table size by " << overlap * 4
333 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400334 } else {
srs5694fed16d02010-01-27 23:03:40 -0500335 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400336 } // if/else
337 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400338 } // Problem at start of disk
339 if (mainHeader.lastUsableLBA < lastUsedBlock) {
340 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500341 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500342 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400343 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500344 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400345 } else {
srs5694fed16d02010-01-27 23:03:40 -0500346 cout << "Try reducing the partition table size by " << overlap * 4
347 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400348 } // if/else
349 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400350 } // Problem at end of disk
351 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400352 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400353} // GPTData::CheckGPTSize()
354
srs5694e7b4ff92009-08-18 13:16:10 -0400355// Check the validity of the GPT header. Returns 1 if the main header
356// is valid, 2 if the backup header is valid, 3 if both are valid, and
357// 0 if neither is valid. Note that this function just checks the GPT
358// signature and revision numbers, not CRCs or other data.
359int GPTData::CheckHeaderValidity(void) {
360 int valid = 3;
361
srs5694fed16d02010-01-27 23:03:40 -0500362 cout.setf(ios::uppercase);
363 cout.fill('0');
364
365 // Note: failed GPT signature checks produce no error message because
366 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400367 if (mainHeader.signature != GPT_SIGNATURE) {
368 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400369 } else if ((mainHeader.revision != 0x00010000) && valid) {
370 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500371 cout << "Unsupported GPT version in main header; read 0x";
372 cout.width(8);
373 cout << hex << mainHeader.revision << ", should be\n0x";
374 cout.width(8);
375 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400376 } // if/else/if
377
378 if (secondHeader.signature != GPT_SIGNATURE) {
379 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400380 } else if ((secondHeader.revision != 0x00010000) && valid) {
381 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500382 cout << "Unsupported GPT version in backup header; read 0x";
383 cout.width(8);
384 cout << hex << secondHeader.revision << ", should be\n0x";
385 cout.width(8);
386 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400387 } // if/else/if
388
srs5694df9d3632011-01-08 18:33:24 -0500389 // Check for an Apple disk signature
390 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
391 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400392 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500393 } // if
srs5694fed16d02010-01-27 23:03:40 -0500394 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400395
srs5694fed16d02010-01-27 23:03:40 -0500396 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400397} // GPTData::CheckHeaderValidity()
398
399// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500400// Note: Must be called with header in LITTLE-ENDIAN
401// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400402int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400403 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400404
srs56942a9f5da2009-08-26 00:48:01 -0400405 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400406 // computation to be valid
407 oldCRC = header->headerCRC;
408 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400409 hSize = header->headerSize;
410
411 // If big-endian system, reverse byte order
412 if (IsLittleEndian() == 0) {
413 ReverseBytes(&oldCRC, 4);
414 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400415
416 // Initialize CRC functions...
417 chksum_crc32gentab();
418
419 // Compute CRC, restore original, and return result of comparison
420 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400421 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400422 return (oldCRC == newCRC);
423} // GPTData::CheckHeaderCRC()
424
srs56946699b012010-02-04 00:55:30 -0500425// Recompute all the CRCs. Must be called before saving if any changes have
426// been made. Must be called on platform-ordered data (this function reverses
427// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400428void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400429 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400430 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400431
432 // Initialize CRC functions...
433 chksum_crc32gentab();
434
srs56946699b012010-02-04 00:55:30 -0500435 // Save some key data from header before reversing byte order....
srs5694978041c2009-09-21 20:51:47 -0400436 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500437
438 if ((littleEndian = IsLittleEndian()) == 0) {
439 ReversePartitionBytes();
440 ReverseHeaderBytes(&mainHeader);
441 ReverseHeaderBytes(&secondHeader);
442 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400443
srs5694e7b4ff92009-08-18 13:16:10 -0400444 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400445 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400446 mainHeader.partitionEntriesCRC = crc;
447 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400448 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400449 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
450 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400451 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400452
453 // Zero out GPT tables' own CRCs (required for correct computation)
454 mainHeader.headerCRC = 0;
455 secondHeader.headerCRC = 0;
456
457 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400458 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400459 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400460 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400461 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400462 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400463 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400464 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400465 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500466
467 if ((littleEndian = IsLittleEndian()) == 0) {
468 ReverseHeaderBytes(&mainHeader);
469 ReverseHeaderBytes(&secondHeader);
470 ReversePartitionBytes();
471 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400472} // GPTData::RecomputeCRCs()
473
srs5694e7b4ff92009-08-18 13:16:10 -0400474// Rebuild the main GPT header, using the secondary header as a model.
475// Typically called when the main header has been found to be corrupt.
476void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400477 mainHeader.signature = GPT_SIGNATURE;
478 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400479 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400480 mainHeader.headerCRC = UINT32_C(0);
481 mainHeader.reserved = secondHeader.reserved;
482 mainHeader.currentLBA = secondHeader.backupLBA;
483 mainHeader.backupLBA = secondHeader.currentLBA;
484 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
485 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500486 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400487 mainHeader.partitionEntriesLBA = UINT64_C(2);
488 mainHeader.numParts = secondHeader.numParts;
489 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
490 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400491 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500492 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400493 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400494} // GPTData::RebuildMainHeader()
495
496// Rebuild the secondary GPT header, using the main header as a model.
497void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400498 secondHeader.signature = GPT_SIGNATURE;
499 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400500 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400501 secondHeader.headerCRC = UINT32_C(0);
502 secondHeader.reserved = mainHeader.reserved;
503 secondHeader.currentLBA = mainHeader.backupLBA;
504 secondHeader.backupLBA = mainHeader.currentLBA;
505 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
506 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500507 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400508 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
509 secondHeader.numParts = mainHeader.numParts;
510 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
511 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400512 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500513 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400514 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400515} // GPTData::RebuildSecondHeader()
516
517// Search for hybrid MBR entries that have no corresponding GPT partition.
518// Returns number of such mismatches found
519int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500520 int i, found, numFound = 0;
521 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400522 uint64_t mbrFirst, mbrLast;
523
524 for (i = 0; i < 4; i++) {
525 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
526 j = 0;
527 found = 0;
528 do {
529 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
530 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
531 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
532 (partitions[j].GetLastLBA() == mbrLast))
533 found = 1;
534 j++;
srs56940283dae2010-04-28 16:44:34 -0400535 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400536 if (!found) {
537 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500538 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
539 << i + 1 << ", of type 0x";
540 cout.fill('0');
541 cout.setf(ios::uppercase);
542 cout.width(2);
543 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
544 << "has no corresponding GPT partition! You may continue, but this condition\n"
545 << "might cause data loss in the future!\a\n" << dec;
546 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400547 } // if
548 } // if
549 } // for
550 return numFound;
551} // GPTData::FindHybridMismatches
552
553// Find overlapping partitions and warn user about them. Returns number of
554// overlapping partitions.
555int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500556 int problems = 0;
557 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400558
srs56940283dae2010-04-28 16:44:34 -0400559 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400560 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500561 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400562 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500563 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
564 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
565 << " to " << partitions[i].GetLastLBA() << "\n";
566 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
567 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400568 } // if
569 } // for j...
570 } // for i...
571 return problems;
572} // GPTData::FindOverlaps()
573
srs569455d92612010-03-07 22:16:07 -0500574// Find partitions that are insane -- they start after they end or are too
575// big for the disk. (The latter should duplicate detection of overlaps
576// with GPT backup data structures, but better to err on the side of
577// redundant tests than to miss something....)
578int GPTData::FindInsanePartitions(void) {
579 uint32_t i;
580 int problems = 0;
581
srs56940283dae2010-04-28 16:44:34 -0400582 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500583 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
584 problems++;
srs56940283dae2010-04-28 16:44:34 -0400585 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500586 } // if
587 if (partitions[i].GetLastLBA() >= diskSize) {
588 problems++;
srs56940873e9d2010-10-07 13:00:45 -0400589 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500590 } // if
591 } // for
592 return problems;
593} // GPTData::FindInsanePartitions(void)
594
595
srs5694e4ac11e2009-08-31 10:13:04 -0400596/******************************************************************
597 * *
598 * Begin functions that load data from disk or save data to disk. *
599 * *
600 ******************************************************************/
601
srs569464cbd172011-03-01 22:03:54 -0500602// Change the filename associated with the GPT. Used for duplicating
603// the partition table to a new disk and saving backups.
604// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500605int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500606 int err, allOK = 1;
607
608 device = deviceFilename;
609 if (allOK && myDisk.OpenForRead(deviceFilename)) {
610 // store disk information....
611 diskSize = myDisk.DiskSize(&err);
612 blockSize = (uint32_t) myDisk.GetBlockSize();
613 } // if
614 protectiveMBR.SetDisk(&myDisk);
615 protectiveMBR.SetDiskSize(diskSize);
616 protectiveMBR.SetBlockSize(blockSize);
617 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500618} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500619
srs5694e4ac11e2009-08-31 10:13:04 -0400620// Scan for partition data. This function loads the MBR data (regular MBR or
621// protective MBR) and loads BSD disklabel data (which is probably invalid).
622// It also looks for APM data, forces a load of GPT data, and summarizes
623// the results.
srs5694546a9c72010-01-26 16:00:26 -0500624void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400625 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400626
627 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500628 protectiveMBR.ReadMBRData(&myDisk);
629 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400630
631 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500632 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500633
634 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500635 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500636 protectiveMBR.ShowState();
637 bsdDisklabel.ShowState();
638 ShowAPMState(); // Show whether there's an Apple Partition Map present
639 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500640 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500641 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400642
643 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500644 cout << "\n*******************************************************************\n"
645 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500646 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500647 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500648 } // if
srs5694fed16d02010-01-27 23:03:40 -0500649 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400650 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400651} // GPTData::PartitionScan()
652
653// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500654int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500655 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500656 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500657 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400658
srs5694546a9c72010-01-26 16:00:26 -0500659 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500660 err = myDisk.OpenForWrite(deviceFilename);
661 if ((err == 0) && (!justLooking)) {
662 cout << "\aNOTE: Write test failed with error number " << errno
663 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
664#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
665 cout << "You may be able to enable writes by exiting this program, typing\n"
666 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
667 << "program.\n";
668#endif
669 cout << "\n";
670 } // if
671 myDisk.Close(); // Close and re-open read-only in case of bugs
672 } else allOK = 0; // if
673
674 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400675 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500676 diskSize = myDisk.DiskSize(&err);
677 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500678 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500679 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400680
srs5694ba00fed2010-01-12 18:18:36 -0500681 whichWasUsed = UseWhichPartitions();
682 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400683 case use_mbr:
684 XFormPartitions();
685 break;
686 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500687 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400688// bsdDisklabel.DisplayBSDData();
689 ClearGPTData();
690 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500691 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400692 break;
693 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500694 mbrState = protectiveMBR.GetValidity();
695 if ((mbrState == invalid) || (mbrState == mbr))
696 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400697 break;
698 case use_new:
699 ClearGPTData();
700 protectiveMBR.MakeProtectiveMBR();
701 break;
srs56943c0af382010-01-15 19:19:18 -0500702 case use_abort:
703 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400704 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500705 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400706 } // switch
707
srs569455d92612010-03-07 22:16:07 -0500708 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500709 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500710 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400711 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400712 } else {
713 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400714 } // if/else
715 return (allOK);
716} // GPTData::LoadPartitions()
717
718// Loads the GPT, as much as possible. Returns 1 if this seems to have
719// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500720int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500721 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400722
srs5694cb76c672010-02-11 22:22:22 -0500723 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400724
srs5694cb76c672010-02-11 22:22:22 -0500725 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
726 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
727 } else {
srs569408bb0da2010-02-19 17:19:55 -0500728 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
729 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500730 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
731 << "secondary header from the last sector of the disk! You should use 'v' to\n"
732 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
733 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500734 } // if/else
735 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400736 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400737
738 // Return valid headers code: 0 = both headers bad; 1 = main header
739 // good, backup bad; 2 = backup header good, main header bad;
740 // 3 = both headers good. Note these codes refer to valid GPT
741 // signatures and version numbers; more subtle problems will elude
742 // this check!
743 validHeaders = CheckHeaderValidity();
744
745 // Read partitions (from primary array)
746 if (validHeaders > 0) { // if at least one header is OK....
747 // GPT appears to be valid....
748 state = gpt_valid;
749
750 // We're calling the GPT valid, but there's a possibility that one
751 // of the two headers is corrupt. If so, use the one that seems to
752 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500753 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500754 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
755 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400756 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500757 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400758 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500759 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500760 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
761 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500762 RebuildMainHeader();
763 state = gpt_corrupt;
764 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400765 } // if/else/if
766
srs5694546a9c72010-01-26 16:00:26 -0500767 // Figure out which partition table to load....
768 // Load the main partition table, since either its header's CRC is OK or the
769 // backup header's CRC is not OK....
770 if (mainCrcOk || !secondCrcOk) {
771 if (LoadMainTable() == 0)
772 allOK = 0;
773 } else { // bad main header CRC and backup header CRC is OK
774 state = gpt_corrupt;
775 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500776 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500777 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500778 } else { // backup table bad, bad main header CRC, but try main table in desperation....
779 if (LoadMainTable() == 0) {
780 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500781 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500782 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500783 } // if
784 } // if/else (LoadSecondTableAsMain())
785 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400786
srs5694cb76c672010-02-11 22:22:22 -0500787 if (loadedTable == 1)
788 secondPartsCrcOk = CheckTable(&secondHeader);
789 else if (loadedTable == 2)
790 mainPartsCrcOk = CheckTable(&mainHeader);
791 else
792 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400793
srs5694546a9c72010-01-26 16:00:26 -0500794 // Problem with main partition table; if backup is OK, use it instead....
795 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
796 state = gpt_corrupt;
797 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500798 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500799 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
800 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500801 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500802
srs5694e4ac11e2009-08-31 10:13:04 -0400803 // Check for valid CRCs and warn if there are problems
804 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
805 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500806 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400807 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500808 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400809 } else {
810 state = gpt_invalid;
811 } // if/else
812 return allOK;
813} // GPTData::ForceLoadGPTData()
814
srs5694247657a2009-11-26 18:36:12 -0500815// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400816// main GPT header in memory MUST be valid for this call to do anything
817// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500818// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400819int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500820 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400821} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400822
823// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500824// table. Used in repair functions, and when starting up if the main
825// partition table is damaged.
826// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
827int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500828 return LoadPartitionTable(secondHeader, myDisk);
829} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400830
srs5694cb76c672010-02-11 22:22:22 -0500831// Load a single GPT header (main or backup) from the specified disk device and
832// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
833// value appropriately.
834// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
835// failure.
836int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
837 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500838 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500839
840 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500841 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500842 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
843 allOK = 0;
844 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500845 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500846
srs56941c6f8b02010-02-21 11:09:20 -0500847 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500848 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500849 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500850 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500851
srs56940283dae2010-04-28 16:44:34 -0400852 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500853 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500854 }
srs56941c6f8b02010-02-21 11:09:20 -0500855
856 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500857 return allOK;
858} // GPTData::LoadHeader
859
860// Load a partition table (either main or secondary) from the specified disk,
861// using header as a reference for what to load. If sector != 0 (the default
862// is 0), loads from the specified sector; otherwise loads from the sector
863// indicated in header.
864// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
865int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
866 uint32_t sizeOfParts, newCRC;
867 int retval;
868
869 if (disk.OpenForRead()) {
870 if (sector == 0) {
871 retval = disk.Seek(header.partitionEntriesLBA);
872 } else {
873 retval = disk.Seek(sector);
874 } // if/else
srs569455d92612010-03-07 22:16:07 -0500875 if (retval == 1)
876 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500877 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500878 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
879 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500880 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500881 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500882 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400883 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500884 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400885 if (IsLittleEndian() == 0)
886 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500887 if (!mainPartsCrcOk) {
888 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400889 } // if
890 } else {
srs5694cb76c672010-02-11 22:22:22 -0500891 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400892 } // if/else
893 } else {
srs5694fed16d02010-01-27 23:03:40 -0500894 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500895 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500896 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400897 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500898 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500899} // GPTData::LoadPartitionsTable()
900
901// Check the partition table pointed to by header, but don't keep it
902// around.
903// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
904int GPTData::CheckTable(struct GPTHeader *header) {
905 uint32_t sizeOfParts, newCRC;
906 uint8_t *storage;
907 int newCrcOk = 0;
908
srs56940283dae2010-04-28 16:44:34 -0400909 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500910 // its CRC and store the results, then discard this temporary
911 // storage, since we don't use it in any but recovery operations
912 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400913 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500914 storage = new uint8_t[sizeOfParts];
915 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400916 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500917 } else {
918 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
919 newCrcOk = (newCRC == header->partitionEntriesCRC);
920 } // if/else
921 delete[] storage;
922 } // if
923 return newCrcOk;
924} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400925
srs569464cbd172011-03-01 22:03:54 -0500926// Writes GPT (and protective MBR) to disk. If quiet==1,
927// Returns 1 on successful
srs5694e7b4ff92009-08-18 13:16:10 -0400928// write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500929int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500930 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500931 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400932
srs56946699b012010-02-04 00:55:30 -0500933 littleEndian = IsLittleEndian();
934
srs5694e7b4ff92009-08-18 13:16:10 -0400935 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500936
937 // This test should only fail on read-only disks....
938 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500939 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500940 allOK = 0;
941 } // if
942
srs569464cbd172011-03-01 22:03:54 -0500943 // Check that disk is really big enough to handle the second header...
944 if (mainHeader.backupLBA >= diskSize) {
945 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
946 << "header, but other problems may occur!\n";
947 MoveSecondHeaderToEnd();
948 } // if
949
srs5694e7b4ff92009-08-18 13:16:10 -0400950 // Is there enough space to hold the GPT headers and partition tables,
951 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400952 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400953 allOK = 0;
954 } // if
955
srs5694247657a2009-11-26 18:36:12 -0500956 // Check that second header is properly placed. Warn and ask if this should
957 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -0500958 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
959 if (quiet == 0) {
960 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
961 << "correct this problem? ";
962 if (GetYN() == 'Y') {
963 MoveSecondHeaderToEnd();
964 cout << "Have moved second header and partition table to correct location.\n";
965 } else {
966 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
967 } // if correction requested
968 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -0500969 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -0500970 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -0500971 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400972
srs569455d92612010-03-07 22:16:07 -0500973 // Check for overlapping or insane partitions....
974 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400975 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500976 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400977 } // if
978
979 // Check for mismatched MBR and GPT data, but let it pass if found
980 // (function displays warning message)
981 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400982
983 RecomputeCRCs();
984
srs5694ba00fed2010-01-12 18:18:36 -0500985 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500986 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -0500987 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -0500988 answer = GetYN();
989 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500990 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400991 } else {
992 allOK = 0;
993 } // if/else
994 } // if
995
996 // Do it!
997 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -0500998 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -0400999 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001000 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1001 if (!allOK)
1002 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1003 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001004
1005 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001006 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1007
1008 // Now write the main partition tables...
1009 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1010
1011 // Now write the main GPT header...
1012 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1013
1014 // To top it off, write the protective MBR...
1015 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001016
1017 // re-read the partition table
1018 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001019 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001020 } // if
1021
1022 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001023 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001024 } else {
srs5694fed16d02010-01-27 23:03:40 -05001025 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001026 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001027 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001028
srs5694546a9c72010-01-26 16:00:26 -05001029 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001030 } else {
srs569464cbd172011-03-01 22:03:54 -05001031 cerr << "Unable to open device " << myDisk.GetName() << " for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001032 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001033 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001034 } // if/else
1035 } else {
srs5694fed16d02010-01-27 23:03:40 -05001036 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001037 } // if
1038
1039 return (allOK);
1040} // GPTData::SaveGPTData()
1041
1042// Save GPT data to a backup file. This function does much less error
1043// checking than SaveGPTData(). It can therefore preserve many types of
1044// corruption for later analysis; however, it preserves only the MBR,
1045// the main GPT header, the backup GPT header, and the main partition
1046// table; it discards the backup partition table, since it should be
1047// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001048int GPTData::SaveGPTBackup(const string & filename) {
1049 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001050 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001051
srs5694546a9c72010-01-26 16:00:26 -05001052 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001053 // Recomputing the CRCs is likely to alter them, which could be bad
1054 // if the intent is to save a potentially bad GPT for later analysis;
1055 // but if we don't do this, we get bogus errors when we load the
1056 // backup. I'm favoring misses over false alarms....
1057 RecomputeCRCs();
1058
srs5694546a9c72010-01-26 16:00:26 -05001059 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001060
srs5694cb76c672010-02-11 22:22:22 -05001061 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001062 // MBR write closed disk, so re-open and seek to end....
1063 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001064 allOK = SaveHeader(&mainHeader, backupFile, 1);
1065 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001066
srs5694e7b4ff92009-08-18 13:16:10 -04001067 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001068 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001069
srs5694cb76c672010-02-11 22:22:22 -05001070 if (allOK)
1071 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001072
1073 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001074 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001075 } else {
srs5694fed16d02010-01-27 23:03:40 -05001076 cerr << "Warning! An error was reported when writing the backup file.\n"
1077 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001078 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001079 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001080 } else {
srs5694fed16d02010-01-27 23:03:40 -05001081 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001082 allOK = 0;
1083 } // if/else
1084 return allOK;
1085} // GPTData::SaveGPTBackup()
1086
srs5694cb76c672010-02-11 22:22:22 -05001087// Write a GPT header (main or backup) to the specified sector. Used by both
1088// the SaveGPTData() and SaveGPTBackup() functions.
1089// Should be passed an architecture-appropriate header (DO NOT call
1090// ReverseHeaderBytes() on the header before calling this function)
1091// Returns 1 on success, 0 on failure
1092int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1093 int littleEndian, allOK = 1;
1094
1095 littleEndian = IsLittleEndian();
1096 if (!littleEndian)
1097 ReverseHeaderBytes(header);
1098 if (disk.Seek(sector)) {
1099 if (disk.Write(header, 512) == -1)
1100 allOK = 0;
1101 } else allOK = 0; // if (disk.Seek()...)
1102 if (!littleEndian)
1103 ReverseHeaderBytes(header);
1104 return allOK;
1105} // GPTData::SaveHeader()
1106
1107// Save the partitions to the specified sector. Used by both the SaveGPTData()
1108// and SaveGPTBackup() functions.
1109// Should be passed an architecture-appropriate header (DO NOT call
1110// ReverseHeaderBytes() on the header before calling this function)
1111// Returns 1 on success, 0 on failure
1112int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1113 int littleEndian, allOK = 1;
1114
1115 littleEndian = IsLittleEndian();
1116 if (disk.Seek(sector)) {
1117 if (!littleEndian)
1118 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001119 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001120 allOK = 0;
1121 if (!littleEndian)
1122 ReversePartitionBytes();
1123 } else allOK = 0; // if (myDisk.Seek()...)
1124 return allOK;
1125} // GPTData::SavePartitionTable()
1126
srs5694e7b4ff92009-08-18 13:16:10 -04001127// Load GPT data from a backup file created by SaveGPTBackup(). This function
1128// does minimal error checking. It returns 1 if it completed successfully,
1129// 0 if there was a problem. In the latter case, it creates a new empty
1130// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001131int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001132 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001133 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001134 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001135 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001136
srs5694546a9c72010-01-26 16:00:26 -05001137 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001138 if (IsLittleEndian() == 0)
1139 littleEndian = 0;
1140
srs5694e7b4ff92009-08-18 13:16:10 -04001141 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001142 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001143
srs5694cb76c672010-02-11 22:22:22 -05001144 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001145
srs5694cb76c672010-02-11 22:22:22 -05001146 // Check backup file size and rebuild second header if file is right
1147 // size to be direct dd copy of MBR, main header, and main partition
1148 // table; if other size, treat it like a GPT fdisk-generated backup
1149 // file
1150 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1151 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1152 if (shortBackup) {
1153 RebuildSecondHeader();
1154 secondCrcOk = mainCrcOk;
1155 } else {
1156 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1157 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001158
srs5694e7b4ff92009-08-18 13:16:10 -04001159 // Return valid headers code: 0 = both headers bad; 1 = main header
1160 // good, backup bad; 2 = backup header good, main header bad;
1161 // 3 = both headers good. Note these codes refer to valid GPT
1162 // signatures and version numbers; more subtle problems will elude
1163 // this check!
1164 if ((val = CheckHeaderValidity()) > 0) {
1165 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001166 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001167 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001168 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001169 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001170 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1171 } // if/else
1172
srs5694e7b4ff92009-08-18 13:16:10 -04001173 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001174 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1175 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001176 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001177 } // if
1178
srs5694cb76c672010-02-11 22:22:22 -05001179 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1180 cerr << "Warning! Read error " << errno
1181 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001182 } else {
1183 allOK = 0;
1184 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001185 // Something went badly wrong, so blank out partitions
1186 if (allOK == 0) {
1187 cerr << "Improper backup file! Clearing all partition data!\n";
1188 ClearGPTData();
1189 protectiveMBR.MakeProtectiveMBR();
1190 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001191 } else {
1192 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001193 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001194 } // if/else
1195
srs5694e7b4ff92009-08-18 13:16:10 -04001196 return allOK;
1197} // GPTData::LoadGPTBackup()
1198
srs569408bb0da2010-02-19 17:19:55 -05001199int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001200 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001201} // GPTData::SaveMBR()
1202
1203// This function destroys the on-disk GPT structures, but NOT the on-disk
1204// MBR.
1205// Returns 1 if the operation succeeds, 0 if not.
1206int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001207 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001208 uint8_t blankSector[512];
1209 uint8_t* emptyTable;
1210
srs569401f7f082011-03-15 23:53:31 -04001211 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001212
1213 if (myDisk.OpenForWrite()) {
1214 if (!myDisk.Seek(mainHeader.currentLBA))
1215 allOK = 0;
1216 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1217 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1218 allOK = 0;
1219 } // if
1220 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1221 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001222 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001223 emptyTable = new uint8_t[tableSize];
srs569401f7f082011-03-15 23:53:31 -04001224 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001225 if (allOK) {
1226 sum = myDisk.Write(emptyTable, tableSize);
1227 if (sum != tableSize) {
1228 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1229 allOK = 0;
1230 } // if write failed
1231 } // if
1232 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1233 allOK = 0;
1234 if (allOK) {
1235 sum = myDisk.Write(emptyTable, tableSize);
1236 if (sum != tableSize) {
1237 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1238 << errno << "\n";
1239 allOK = 0;
1240 } // if wrong size written
1241 } // if
1242 if (!myDisk.Seek(secondHeader.currentLBA))
1243 allOK = 0;
1244 if (allOK) {
1245 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1246 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1247 allOK = 0;
1248 } // if
1249 } // if
1250 myDisk.DiskSync();
1251 myDisk.Close();
1252 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1253 << "other utilities.\n";
1254 delete[] emptyTable;
1255 } else {
1256 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1257 } // if/else (fd != -1)
1258 return (allOK);
1259} // GPTDataTextUI::DestroyGPT()
1260
1261// Wipe MBR data from the disk (zero it out completely)
1262// Returns 1 on success, 0 on failure.
1263int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001264 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001265 uint8_t blankSector[512];
1266
srs569401f7f082011-03-15 23:53:31 -04001267 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001268
srs569401f7f082011-03-15 23:53:31 -04001269 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1270
srs569408bb0da2010-02-19 17:19:55 -05001271 if (!allOK)
1272 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1273 return allOK;
1274} // GPTData::DestroyMBR(void)
1275
srs5694e4ac11e2009-08-31 10:13:04 -04001276// Tell user whether Apple Partition Map (APM) was discovered....
1277void GPTData::ShowAPMState(void) {
1278 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001279 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001280 else
srs5694fed16d02010-01-27 23:03:40 -05001281 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001282} // GPTData::ShowAPMState()
1283
1284// Tell user about the state of the GPT data....
1285void GPTData::ShowGPTState(void) {
1286 switch (state) {
1287 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001288 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001289 break;
1290 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001291 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001292 break;
1293 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001294 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001295 break;
1296 default:
srs5694fed16d02010-01-27 23:03:40 -05001297 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001298 break;
1299 } // switch
1300} // GPTData::ShowGPTState()
1301
1302// Display the basic GPT data
1303void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001304 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001305 uint64_t temp, totalFree;
1306
srs5694fed16d02010-01-27 23:03:40 -05001307 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001308 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001309 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001310 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001311 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001312 cout << "First usable sector is " << mainHeader.firstUsableLBA
1313 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001314 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001315 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001316 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001317 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001318 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001319 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001320 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001321 } // for
1322} // GPTData::DisplayGPTData()
1323
srs5694e4ac11e2009-08-31 10:13:04 -04001324// Show detailed information on the specified partition
1325void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001326 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001327 partitions[partNum].ShowDetails(blockSize);
1328 } else {
srs5694fed16d02010-01-27 23:03:40 -05001329 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001330 } // if
1331} // GPTData::ShowPartDetails()
1332
srs5694e4ac11e2009-08-31 10:13:04 -04001333/**************************************************************************
1334 * *
1335 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1336 * (some of these functions may require user interaction) *
1337 * *
1338 **************************************************************************/
1339
srs569408bb0da2010-02-19 17:19:55 -05001340// Examines the MBR & GPT data to determine which set of data to use: the
1341// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1342// a new set of partitions (use_new). A return value of use_abort indicates
1343// that this function couldn't determine what to do. Overriding functions
1344// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001345WhichToUse GPTData::UseWhichPartitions(void) {
1346 WhichToUse which = use_new;
1347 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001348
1349 mbrState = protectiveMBR.GetValidity();
1350
1351 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001352 cout << "\n***************************************************************\n"
1353 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001354 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001355 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001356 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001357 } // if
srs5694fed16d02010-01-27 23:03:40 -05001358 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001359 which = use_mbr;
1360 } // if
1361
1362 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001363 cout << "\n**********************************************************************\n"
1364 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1365 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001366 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001367 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001368 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1369 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001370 } // if
srs5694fed16d02010-01-27 23:03:40 -05001371 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001372 which = use_bsd;
1373 } // if
1374
1375 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001376 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001377 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001378 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001379 } // if
1380 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001381 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001382 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001383 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001384 } // if
1385 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001386 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001387 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001388 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001389 } // if
1390 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001391 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001392 } // if
1393
srs5694e4ac11e2009-08-31 10:13:04 -04001394 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001395 if (mbrState == gpt) {
1396 cout << "\a\a****************************************************************************\n"
1397 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1398 << "verification and recovery are STRONGLY recommended.\n"
1399 << "****************************************************************************\n";
1400 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001401 } else {
srs569408bb0da2010-02-19 17:19:55 -05001402 which = use_abort;
1403 } // if/else MBR says disk is GPT
1404 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001405
1406 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001407 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001408
1409 return which;
1410} // UseWhichPartitions()
1411
srs569408bb0da2010-02-19 17:19:55 -05001412// Convert MBR partition table into GPT form.
1413void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001414 int i, numToConvert;
1415 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001416
1417 // Clear out old data & prepare basics....
1418 ClearGPTData();
1419
1420 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001421 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001422 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001423 else
srs56940283dae2010-04-28 16:44:34 -04001424 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001425
1426 for (i = 0; i < numToConvert; i++) {
1427 origType = protectiveMBR.GetType(i);
1428 // don't waste CPU time trying to convert extended, hybrid protective, or
1429 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001430 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001431 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001432 partitions[i] = protectiveMBR.AsGPT(i);
1433 } // for
1434
1435 // Convert MBR into protective MBR
1436 protectiveMBR.MakeProtectiveMBR();
1437
1438 // Record that all original CRCs were OK so as not to raise flags
1439 // when doing a disk verification
1440 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001441} // GPTData::XFormPartitions()
1442
1443// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001444// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001445// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001446int GPTData::XFormDisklabel(uint32_t partNum) {
1447 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001448 int goOn = 1, numDone = 0;
1449 BSDData disklabel;
1450
srs569408bb0da2010-02-19 17:19:55 -05001451 if (GetPartRange(&low, &high) == 0) {
1452 goOn = 0;
1453 cout << "No partitions!\n";
1454 } // if
1455 if (partNum > high) {
1456 goOn = 0;
1457 cout << "Specified partition is invalid!\n";
1458 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001459
srs569408bb0da2010-02-19 17:19:55 -05001460 // If all is OK, read the disklabel and convert it.
1461 if (goOn) {
1462 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1463 partitions[partNum].GetLastLBA());
1464 if ((goOn) && (disklabel.IsDisklabel())) {
1465 numDone = XFormDisklabel(&disklabel);
1466 if (numDone == 1)
1467 cout << "Converted 1 BSD partition.\n";
1468 else
1469 cout << "Converted " << numDone << " BSD partitions.\n";
1470 } else {
1471 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1472 } // if/else
1473 } // if
1474 if (numDone > 0) { // converted partitions; delete carrier
1475 partitions[partNum].BlankPartition();
1476 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001477 return numDone;
srs569455d92612010-03-07 22:16:07 -05001478} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001479
1480// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001481int GPTData::XFormDisklabel(BSDData* disklabel) {
1482 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001483
srs569408bb0da2010-02-19 17:19:55 -05001484 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001485 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001486 partNum = FindFirstFreePart();
1487 if (partNum >= 0) {
1488 partitions[partNum] = disklabel->AsGPT(i);
1489 if (partitions[partNum].IsUsed())
1490 numDone++;
1491 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001492 } // for
srs569408bb0da2010-02-19 17:19:55 -05001493 if (partNum == -1)
1494 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001495 } // if
1496
1497 // Record that all original CRCs were OK so as not to raise flags
1498 // when doing a disk verification
1499 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1500
1501 return numDone;
1502} // GPTData::XFormDisklabel(BSDData* disklabel)
1503
srs569408bb0da2010-02-19 17:19:55 -05001504// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1505// partition has the active/bootable flag UNset and uses the GPT fdisk
1506// type code divided by 0x0100 as the MBR type code.
1507// Returns 1 if operation was 100% successful, 0 if there were ANY
1508// problems.
srs5694978041c2009-09-21 20:51:47 -04001509int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001510 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001511
srs5694978041c2009-09-21 20:51:47 -04001512 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001513 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001514 allOK = 0;
1515 } // if
srs56940283dae2010-04-28 16:44:34 -04001516 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001517 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001518 allOK = 0;
1519 } // if
1520 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001521 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001522 allOK = 0;
1523 } // if
1524 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1525 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1526 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001527 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1528 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001529 } // if
srs5694978041c2009-09-21 20:51:47 -04001530 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001531 (uint32_t) partitions[gptPart].GetLengthLBA(),
1532 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001533 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001534 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1535 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1536 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001537 allOK = 0;
1538 } // if/else
1539 return allOK;
1540} // GPTData::OnePartToMBR()
1541
srs5694e4ac11e2009-08-31 10:13:04 -04001542
1543/**********************************************************************
1544 * *
1545 * Functions that adjust GPT data structures WITHOUT user interaction *
1546 * (they may display information for the user's benefit, though) *
1547 * *
1548 **********************************************************************/
1549
1550// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001551// necessary, copies data if it already exists. Returns 1 if all goes
1552// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001553int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001554 GPTPart* newParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001555 uint32_t i, high, copyNum;
1556 int allOK = 1;
1557
1558 // First, adjust numEntries upward, if necessary, to get a number
1559 // that fills the allocated sectors
1560 i = blockSize / GPT_SIZE;
1561 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001562 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001563 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001564 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001565 } // if
1566
srs5694247657a2009-11-26 18:36:12 -05001567 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001568 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001569 // partition table, which causes problems when loading data from a RAID
1570 // array that's been expanded because this function is called when loading
1571 // data.
srs56940283dae2010-04-28 16:44:34 -04001572 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001573 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001574 if (newParts != NULL) {
1575 if (partitions != NULL) { // existing partitions; copy them over
1576 GetPartRange(&i, &high);
1577 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001578 cout << "The highest-numbered partition is " << high + 1
1579 << ", which is greater than the requested\n"
1580 << "partition table size of " << numEntries
1581 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001582 allOK = 0;
1583 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001584 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001585 copyNum = numEntries;
1586 else
srs56940283dae2010-04-28 16:44:34 -04001587 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001588 for (i = 0; i < copyNum; i++) {
1589 newParts[i] = partitions[i];
1590 } // for
srs569401f7f082011-03-15 23:53:31 -04001591 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001592 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001593 } // if
1594 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001595 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001596 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001597 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001598 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1599 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1600 MoveSecondHeaderToEnd();
1601 if (diskSize > 0)
1602 CheckGPTSize();
1603 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001604 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001605 allOK = 0;
1606 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001607 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001608 mainHeader.numParts = numParts;
1609 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001610 return (allOK);
1611} // GPTData::SetGPTSize()
1612
1613// Blank the partition array
1614void GPTData::BlankPartitions(void) {
1615 uint32_t i;
1616
srs56940283dae2010-04-28 16:44:34 -04001617 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001618 partitions[i].BlankPartition();
1619 } // for
1620} // GPTData::BlankPartitions()
1621
srs5694ba00fed2010-01-12 18:18:36 -05001622// Delete a partition by number. Returns 1 if successful,
1623// 0 if there was a problem. Returns 1 if partition was in
1624// range, 0 if it was out of range.
1625int GPTData::DeletePartition(uint32_t partNum) {
1626 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001627 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001628
srs56940283dae2010-04-28 16:44:34 -04001629 numUsedParts = GetPartRange(&low, &high);
1630 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001631 // In case there's a protective MBR, look for & delete matching
1632 // MBR partition....
1633 startSector = partitions[partNum].GetFirstLBA();
1634 length = partitions[partNum].GetLengthLBA();
1635 protectiveMBR.DeleteByLocation(startSector, length);
1636
1637 // Now delete the GPT partition
1638 partitions[partNum].BlankPartition();
1639 } else {
srs5694fed16d02010-01-27 23:03:40 -05001640 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001641 retval = 0;
1642 } // if/else
1643 return retval;
1644} // GPTData::DeletePartition(uint32_t partNum)
1645
srs569408bb0da2010-02-19 17:19:55 -05001646// Non-interactively create a partition.
1647// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001648uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001649 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001650 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001651
1652 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001653 if (Align(&startSector)) {
1654 cout << "Information: Moved requested sector from " << origSector << " to "
1655 << startSector << " in\norder to align on " << sectorAlignment
1656 << "-sector boundaries.\n";
1657 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001658 if (IsFree(startSector) && (startSector <= endSector)) {
1659 if (FindLastInFree(startSector) >= endSector) {
1660 partitions[partNum].SetFirstLBA(startSector);
1661 partitions[partNum].SetLastLBA(endSector);
1662 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001663 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001664 } else retval = 0; // if free space until endSector
1665 } else retval = 0; // if startSector is free
1666 } else retval = 0; // if legal partition number
1667 return retval;
1668} // GPTData::CreatePartition(partNum, startSector, endSector)
1669
srs5694e4ac11e2009-08-31 10:13:04 -04001670// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001671// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001672void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001673 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001674 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001675} // GPTData::SortGPT()
1676
srs569408bb0da2010-02-19 17:19:55 -05001677// Swap the contents of two partitions.
1678// Returns 1 if successful, 0 if either partition is out of range
1679// (that is, not a legal number; either or both can be empty).
1680// Note that if partNum1 = partNum2 and this number is in range,
1681// it will be considered successful.
1682int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1683 GPTPart temp;
1684 int allOK = 1;
1685
srs56940283dae2010-04-28 16:44:34 -04001686 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001687 if (partNum1 != partNum2) {
1688 temp = partitions[partNum1];
1689 partitions[partNum1] = partitions[partNum2];
1690 partitions[partNum2] = temp;
1691 } // if
1692 } else allOK = 0; // partition numbers are valid
1693 return allOK;
1694} // GPTData::SwapPartitions()
1695
srs5694e4ac11e2009-08-31 10:13:04 -04001696// Set up data structures for entirely new set of partitions on the
1697// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001698// Note that this function does NOT clear the protectiveMBR data
1699// structure, since it may hold the original MBR partitions if the
1700// program was launched on an MBR disk, and those may need to be
1701// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001702int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001703 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001704
1705 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001706 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001707 partitions = NULL;
1708 SetGPTSize(NUM_GPT_ENTRIES);
1709
1710 // Now initialize a bunch of stuff that's static....
1711 mainHeader.signature = GPT_SIGNATURE;
1712 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001713 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001714 mainHeader.reserved = 0;
1715 mainHeader.currentLBA = UINT64_C(1);
1716 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1717 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1718 for (i = 0; i < GPT_RESERVED; i++) {
1719 mainHeader.reserved2[i] = '\0';
1720 } // for
srs56940873e9d2010-10-07 13:00:45 -04001721 if (blockSize > 0)
1722 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1723 else
1724 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001725
1726 // Now some semi-static items (computed based on end of disk)
1727 mainHeader.backupLBA = diskSize - UINT64_C(1);
1728 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1729
1730 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001731 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001732
1733 // Copy main header to backup header
1734 RebuildSecondHeader();
1735
1736 // Blank out the partitions array....
1737 BlankPartitions();
1738
1739 // Flag all CRCs as being OK....
1740 mainCrcOk = 1;
1741 secondCrcOk = 1;
1742 mainPartsCrcOk = 1;
1743 secondPartsCrcOk = 1;
1744
1745 return (goOn);
1746} // GPTData::ClearGPTData()
1747
srs5694247657a2009-11-26 18:36:12 -05001748// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001749// If the disk size has actually changed, this also adjusts the protective
1750// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001751// Used internally and called by the 'e' option on the recovery &
1752// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001753// to their arrays or to adjust data structures in restore operations
1754// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001755void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001756 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001757 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1758 if (protectiveMBR.GetValidity() == hybrid) {
1759 protectiveMBR.OptimizeEESize();
1760 RecomputeCHS();
1761 } // if
1762 if (protectiveMBR.GetValidity() == gpt)
1763 MakeProtectiveMBR();
1764 } // if
srs56948bb78762009-11-24 15:43:49 -05001765 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1766 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1767} // GPTData::FixSecondHeaderLocation()
1768
srs56940a697312010-01-28 21:10:52 -05001769int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001770 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001771
1772 if (!IsFreePartNum(partNum)) {
1773 partitions[partNum].SetName(theName);
1774 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001775
1776 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001777} // GPTData::SetName
1778
1779// Set the disk GUID to the specified value. Note that the header CRCs must
1780// be recomputed after calling this function.
1781void GPTData::SetDiskGUID(GUIDData newGUID) {
1782 mainHeader.diskGUID = newGUID;
1783 secondHeader.diskGUID = newGUID;
1784} // SetDiskGUID()
1785
1786// Set the unique GUID of the specified partition. Returns 1 on
1787// successful completion, 0 if there were problems (invalid
1788// partition number).
1789int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1790 int retval = 0;
1791
srs56940283dae2010-04-28 16:44:34 -04001792 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001793 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1794 partitions[pn].SetUniqueGUID(theGUID);
1795 retval = 1;
1796 } // if
1797 } // if
1798 return retval;
1799} // GPTData::SetPartitionGUID()
1800
srs56949ba54212010-05-18 23:24:02 -04001801// Set new random GUIDs for the disk and all partitions. Intended to be used
1802// after disk cloning or similar operations that don't randomize the GUIDs.
1803void GPTData::RandomizeGUIDs(void) {
1804 uint32_t i;
1805
1806 mainHeader.diskGUID.Randomize();
1807 secondHeader.diskGUID = mainHeader.diskGUID;
1808 for (i = 0; i < numParts; i++)
1809 if (partitions[i].IsUsed())
1810 partitions[i].RandomizeUniqueGUID();
1811} // GPTData::RandomizeGUIDs()
1812
srs5694ba00fed2010-01-12 18:18:36 -05001813// Change partition type code non-interactively. Returns 1 if
1814// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001815int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1816 int retval = 1;
1817
1818 if (!IsFreePartNum(partNum)) {
1819 partitions[partNum].SetType(theGUID);
1820 } else retval = 0;
1821 return retval;
1822} // GPTData::ChangePartType()
1823
srs56949ba54212010-05-18 23:24:02 -04001824// Recompute the CHS values of all the MBR partitions. Used to reset
1825// CHS values that some BIOSes require, despite the fact that the
1826// resulting CHS values violate the GPT standard.
1827void GPTData::RecomputeCHS(void) {
1828 int i;
1829
1830 for (i = 0; i < 4; i++)
1831 protectiveMBR.RecomputeCHS(i);
1832} // GPTData::RecomputeCHS()
1833
srs56941d1448a2009-12-31 21:20:19 -05001834// Adjust sector number so that it falls on a sector boundary that's a
1835// multiple of sectorAlignment. This is done to improve the performance
1836// of Western Digital Advanced Format disks and disks with similar
1837// technology from other companies, which use 4096-byte sectors
1838// internally although they translate to 512-byte sectors for the
1839// benefit of the OS. If partitions aren't properly aligned on these
1840// disks, some filesystem data structures can span multiple physical
1841// sectors, degrading performance. This function should be called
1842// only on the FIRST sector of the partition, not the last!
1843// This function returns 1 if the alignment was altered, 0 if it
1844// was unchanged.
1845int GPTData::Align(uint64_t* sector) {
1846 int retval = 0, sectorOK = 0;
1847 uint64_t earlier, later, testSector, original;
1848
1849 if ((*sector % sectorAlignment) != 0) {
1850 original = *sector;
srs56941d1448a2009-12-31 21:20:19 -05001851 earlier = (*sector / sectorAlignment) * sectorAlignment;
1852 later = earlier + (uint64_t) sectorAlignment;
1853
1854 // Check to see that every sector between the earlier one and the
1855 // requested one is clear, and that it's not too early....
1856 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001857 sectorOK = 1;
1858 testSector = earlier;
1859 do {
1860 sectorOK = IsFree(testSector++);
1861 } while ((sectorOK == 1) && (testSector < *sector));
1862 if (sectorOK == 1) {
1863 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001864 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001865 } // if
1866 } // if firstUsableLBA check
1867
1868 // If couldn't move the sector earlier, try to move it later instead....
1869 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1870 sectorOK = 1;
1871 testSector = later;
1872 do {
1873 sectorOK = IsFree(testSector--);
1874 } while ((sectorOK == 1) && (testSector > *sector));
1875 if (sectorOK == 1) {
1876 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001877 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001878 } // if
1879 } // if
srs56941d1448a2009-12-31 21:20:19 -05001880 } // if
1881 return retval;
1882} // GPTData::Align()
1883
srs5694e4ac11e2009-08-31 10:13:04 -04001884/********************************************************
1885 * *
1886 * Functions that return data about GPT data structures *
1887 * (most of these are inline in gpt.h) *
1888 * *
1889 ********************************************************/
1890
1891// Find the low and high used partition numbers (numbered from 0).
1892// Return value is the number of partitions found. Note that the
1893// *low and *high values are both set to 0 when no partitions
1894// are found, as well as when a single partition in the first
1895// position exists. Thus, the return value is the only way to
1896// tell when no partitions exist.
1897int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1898 uint32_t i;
1899 int numFound = 0;
1900
srs56940283dae2010-04-28 16:44:34 -04001901 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001902 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001903 for (i = 0; i < numParts; i++) {
1904 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1905 *high = i; // since we're counting up, set the high value
1906 // Set the low value only if it's not yet found...
1907 if (*low == (numParts + 1)) *low = i;
1908 numFound++;
1909 } // if
1910 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04001911
1912 // Above will leave *low pointing to its "not found" value if no partitions
1913 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001914 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001915 *low = 0;
1916 return numFound;
1917} // GPTData::GetPartRange()
1918
srs569408bb0da2010-02-19 17:19:55 -05001919// Returns the value of the first free partition, or -1 if none is
1920// unused.
1921int GPTData::FindFirstFreePart(void) {
1922 int i = 0;
1923
1924 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04001925 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05001926 i++;
srs56940283dae2010-04-28 16:44:34 -04001927 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001928 i = -1;
1929 } else i = -1;
1930 return i;
1931} // GPTData::FindFirstFreePart()
1932
srs5694978041c2009-09-21 20:51:47 -04001933// Returns the number of defined partitions.
1934uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001935 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001936
srs56940283dae2010-04-28 16:44:34 -04001937 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001938 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001939 counted++;
1940 } // for
1941 return counted;
1942} // GPTData::CountParts()
1943
srs5694e4ac11e2009-08-31 10:13:04 -04001944/****************************************************
1945 * *
1946 * Functions that return data about disk free space *
1947 * *
1948 ****************************************************/
1949
1950// Find the first available block after the starting point; returns 0 if
1951// there are no available blocks left
1952uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1953 uint64_t first;
1954 uint32_t i;
1955 int firstMoved = 0;
1956
1957 // Begin from the specified starting point or from the first usable
1958 // LBA, whichever is greater...
1959 if (start < mainHeader.firstUsableLBA)
1960 first = mainHeader.firstUsableLBA;
1961 else
1962 first = start;
1963
1964 // ...now search through all partitions; if first is within an
1965 // existing partition, move it to the next sector after that
1966 // partition and repeat. If first was moved, set firstMoved
1967 // flag; repeat until firstMoved is not set, so as to catch
1968 // cases where partitions are out of sequential order....
1969 do {
1970 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04001971 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001972 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001973 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001974 first = partitions[i].GetLastLBA() + 1;
1975 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001976 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001977 } // for
1978 } while (firstMoved == 1);
1979 if (first > mainHeader.lastUsableLBA)
1980 first = 0;
1981 return (first);
1982} // GPTData::FindFirstAvailable()
1983
1984// Finds the first available sector in the largest block of unallocated
1985// space on the disk. Returns 0 if there are no available blocks left
1986uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001987 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001988
1989 start = 0;
1990 do {
1991 firstBlock = FindFirstAvailable(start);
1992 if (firstBlock != UINT32_C(0)) { // something's free...
1993 lastBlock = FindLastInFree(firstBlock);
1994 segmentSize = lastBlock - firstBlock + UINT32_C(1);
1995 if (segmentSize > selectedSize) {
1996 selectedSize = segmentSize;
1997 selectedSegment = firstBlock;
1998 } // if
1999 start = lastBlock + 1;
2000 } // if
2001 } while (firstBlock != 0);
2002 return selectedSegment;
2003} // GPTData::FindFirstInLargest()
2004
srs5694cb76c672010-02-11 22:22:22 -05002005// Find the last available block on the disk.
2006// Returns 0 if there are no available partitions
2007uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002008 uint64_t last;
2009 uint32_t i;
2010 int lastMoved = 0;
2011
2012 // Start by assuming the last usable LBA is available....
2013 last = mainHeader.lastUsableLBA;
2014
2015 // ...now, similar to algorithm in FindFirstAvailable(), search
2016 // through all partitions, moving last when it's in an existing
2017 // partition. Set the lastMoved flag so we repeat to catch cases
2018 // where partitions are out of logical order.
2019 do {
2020 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002021 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002022 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002023 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002024 last = partitions[i].GetFirstLBA() - 1;
2025 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002026 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002027 } // for
2028 } while (lastMoved == 1);
2029 if (last < mainHeader.firstUsableLBA)
2030 last = 0;
2031 return (last);
2032} // GPTData::FindLastAvailable()
2033
2034// Find the last available block in the free space pointed to by start.
2035uint64_t GPTData::FindLastInFree(uint64_t start) {
2036 uint64_t nearestStart;
2037 uint32_t i;
2038
2039 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002040 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002041 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002042 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002043 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002044 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002045 } // for
2046 return (nearestStart);
2047} // GPTData::FindLastInFree()
2048
2049// Finds the total number of free blocks, the number of segments in which
2050// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002051uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002052 uint64_t start = UINT64_C(0); // starting point for each search
2053 uint64_t totalFound = UINT64_C(0); // running total
2054 uint64_t firstBlock; // first block in a segment
2055 uint64_t lastBlock; // last block in a segment
2056 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002057 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002058
2059 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002060 if (diskSize > 0) {
2061 do {
2062 firstBlock = FindFirstAvailable(start);
2063 if (firstBlock != UINT64_C(0)) { // something's free...
2064 lastBlock = FindLastInFree(firstBlock);
2065 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2066 if (segmentSize > *largestSegment) {
2067 *largestSegment = segmentSize;
2068 } // if
2069 totalFound += segmentSize;
2070 num++;
2071 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002072 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002073 } while (firstBlock != 0);
2074 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002075 *numSegments = num;
2076 return totalFound;
2077} // GPTData::FindFreeBlocks()
2078
srs569455d92612010-03-07 22:16:07 -05002079// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2080// If it's allocated, return the partition number to which it's allocated
2081// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2082// returned in partNum if the sector is in use by basic GPT data structures.)
2083int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002084 int isFree = 1;
2085 uint32_t i;
2086
srs56940283dae2010-04-28 16:44:34 -04002087 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002088 if ((sector >= partitions[i].GetFirstLBA()) &&
2089 (sector <= partitions[i].GetLastLBA())) {
2090 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002091 if (partNum != NULL)
2092 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002093 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002094 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002095 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002096 (sector > mainHeader.lastUsableLBA)) {
2097 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002098 if (partNum != NULL)
2099 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002100 } // if
2101 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002102} // GPTData::IsFree()
2103
srs5694ba00fed2010-01-12 18:18:36 -05002104// Returns 1 if partNum is unused.
2105int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002106 return ((partNum < numParts) && (partitions != NULL) &&
2107 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002108} // GPTData::IsFreePartNum()
2109
srs5694a8582cf2010-03-19 14:21:59 -04002110
2111/***********************************************************
2112 * *
2113 * Change how functions work or return information on them *
2114 * *
2115 ***********************************************************/
2116
2117// Set partition alignment value; partitions will begin on multiples of
2118// the specified value
2119void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002120 if (n > 0)
2121 sectorAlignment = n;
2122 else
2123 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002124} // GPTData::SetAlignment()
2125
2126// Compute sector alignment based on the current partitions (if any). Each
2127// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002128// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2129// sector size), but not by the previously-located alignment value, then the
2130// alignment value is adjusted down. If the computed alignment is less than 8
2131// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2132// is a safety measure for WD Advanced Format and similar drives. If no partitions
2133// are defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2134// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002135// drives are aligned to 2048-sector multiples but the program won't complain
2136// about other alignments on existing disks unless a smaller-than-8 alignment
srs56940873e9d2010-10-07 13:00:45 -04002137// is used on big disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002138// Returns the computed alignment value.
2139uint32_t GPTData::ComputeAlignment(void) {
2140 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002141 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002142
srs56940873e9d2010-10-07 13:00:45 -04002143 if (blockSize > 0)
2144 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2145 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002146 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002147 if (partitions[i].IsUsed()) {
2148 found = 0;
2149 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002150 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002151 if ((partitions[i].GetFirstLBA() % align) == 0) {
2152 found = 1;
2153 } else {
2154 exponent--;
2155 } // if/else
2156 } // while
2157 } // if
2158 } // for
srs56940873e9d2010-10-07 13:00:45 -04002159 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2160 align = MIN_AF_ALIGNMENT;
2161 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002162 return align;
2163} // GPTData::ComputeAlignment()
2164
srs5694e4ac11e2009-08-31 10:13:04 -04002165/********************************
2166 * *
2167 * Endianness support functions *
2168 * *
2169 ********************************/
2170
srs56942a9f5da2009-08-26 00:48:01 -04002171void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002172 ReverseBytes(&header->signature, 8);
2173 ReverseBytes(&header->revision, 4);
2174 ReverseBytes(&header->headerSize, 4);
2175 ReverseBytes(&header->headerCRC, 4);
2176 ReverseBytes(&header->reserved, 4);
2177 ReverseBytes(&header->currentLBA, 8);
2178 ReverseBytes(&header->backupLBA, 8);
2179 ReverseBytes(&header->firstUsableLBA, 8);
2180 ReverseBytes(&header->lastUsableLBA, 8);
2181 ReverseBytes(&header->partitionEntriesLBA, 8);
2182 ReverseBytes(&header->numParts, 4);
2183 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2184 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002185 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002186} // GPTData::ReverseHeaderBytes()
2187
srs56940283dae2010-04-28 16:44:34 -04002188// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002189void GPTData::ReversePartitionBytes() {
2190 uint32_t i;
2191
srs56940283dae2010-04-28 16:44:34 -04002192 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002193 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002194 } // for
2195} // GPTData::ReversePartitionBytes()
2196
srs56949ddc14b2010-08-22 22:44:42 -04002197// Validate partition number
2198bool GPTData::ValidPartNum (const uint32_t partNum) {
2199 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002200 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002201 return false;
2202 } // if
2203 return true;
2204} // GPTData::ValidPartNum
2205
srs56945a081752010-09-24 20:39:41 -04002206// Return a single partition for inspection (not modification!) by other
2207// functions.
2208const GPTPart & GPTData::operator[](uint32_t partNum) const {
2209 if (partNum >= numParts) {
2210 cerr << "Partition number out of range: " << partNum << "\n";
2211 partNum = 0;
srs56949a46b042011-03-15 00:34:10 -04002212 if ((numParts == 0) || (partitions == NULL)) {
srs569401f7f082011-03-15 23:53:31 -04002213 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
srs56949a46b042011-03-15 00:34:10 -04002214 exit(1);
2215 } // if
srs56945a081752010-09-24 20:39:41 -04002216 } // if
2217 return partitions[partNum];
2218} // operator[]
2219
2220// Return (not for modification!) the disk's GUID value
2221const GUIDData & GPTData::GetDiskGUID(void) const {
2222 return mainHeader.diskGUID;
2223} // GPTData::GetDiskGUID()
2224
srs56949ddc14b2010-08-22 22:44:42 -04002225// Manage attributes for a partition, based on commands passed to this function.
2226// (Function is non-interactive.)
2227// Returns 1 if a modification command succeeded, 0 if the command should not have
2228// modified data, and -1 if a modification command failed.
2229int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2230 int retval = 0;
2231 Attributes theAttr;
2232
2233 if (command == "show") {
2234 ShowAttributes(partNum);
2235 } else if (command == "get") {
2236 GetAttribute(partNum, bits);
2237 } else {
2238 theAttr = partitions[partNum].GetAttributes();
2239 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2240 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2241 retval = 1;
2242 } else {
2243 retval = -1;
2244 } // if/else
2245 } // if/elseif/else
2246
2247 return retval;
2248} // GPTData::ManageAttributes()
2249
2250// Show all attributes for a specified partition....
2251void GPTData::ShowAttributes(const uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04002252 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002253} // GPTData::ShowAttributes
2254
2255// Show whether a single attribute bit is set (terse output)...
2256void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002257 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002258} // GPTData::GetAttribute
2259
2260
srs56942a9f5da2009-08-26 00:48:01 -04002261/******************************************
2262 * *
2263 * Additional non-class support functions *
2264 * *
2265 ******************************************/
2266
srs5694e7b4ff92009-08-18 13:16:10 -04002267// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2268// never fail these tests, but the struct types may fail depending on compile options.
2269// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2270// sizes.
2271int SizesOK(void) {
2272 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002273
2274 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002275 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002276 allOK = 0;
2277 } // if
2278 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002279 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002280 allOK = 0;
2281 } // if
2282 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002283 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002284 allOK = 0;
2285 } // if
2286 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002287 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002288 allOK = 0;
2289 } // if
2290 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002291 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002292 allOK = 0;
2293 } // if
srs5694978041c2009-09-21 20:51:47 -04002294 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002295 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002296 allOK = 0;
2297 } // if
2298 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002299 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002300 allOK = 0;
2301 } // if
srs5694221e0872009-08-29 15:00:31 -04002302 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002303 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002304 allOK = 0;
2305 } // if
srs56946699b012010-02-04 00:55:30 -05002306 if (sizeof(GUIDData) != 16) {
2307 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2308 allOK = 0;
2309 } // if
2310 if (sizeof(PartType) != 16) {
2311 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2312 allOK = 0;
2313 } // if
srs5694fed16d02010-01-27 23:03:40 -05002314 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56940873e9d2010-10-07 13:00:45 -04002315// if (IsLittleEndian() == 0) {
2316// cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2317// " tested!\n";
2318// } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002319 return (allOK);
2320} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002321