blob: 4f5683ad648688c10bfa7792f9bc0fd6b6a66173 [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;
124 partitions = new GPTPart [numParts * sizeof (GPTPart)];
125 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 ("
srs56940873e9d2010-10-07 13:00:45 -0400293 << BytesToSI(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500294 << numSegments << "\nsegments, the largest of which is "
srs56940873e9d2010-10-07 13:00:45 -0400295 << largestSegment << " (" << BytesToSI(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) {
477 int i;
478
479 mainHeader.signature = GPT_SIGNATURE;
480 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400481 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400482 mainHeader.headerCRC = UINT32_C(0);
483 mainHeader.reserved = secondHeader.reserved;
484 mainHeader.currentLBA = secondHeader.backupLBA;
485 mainHeader.backupLBA = secondHeader.currentLBA;
486 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
487 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500488 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400489 mainHeader.partitionEntriesLBA = UINT64_C(2);
490 mainHeader.numParts = secondHeader.numParts;
491 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
492 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
493 for (i = 0 ; i < GPT_RESERVED; i++)
494 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500495 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400496 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400497} // GPTData::RebuildMainHeader()
498
499// Rebuild the secondary GPT header, using the main header as a model.
500void GPTData::RebuildSecondHeader(void) {
501 int i;
502
503 secondHeader.signature = GPT_SIGNATURE;
504 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400505 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400506 secondHeader.headerCRC = UINT32_C(0);
507 secondHeader.reserved = mainHeader.reserved;
508 secondHeader.currentLBA = mainHeader.backupLBA;
509 secondHeader.backupLBA = mainHeader.currentLBA;
510 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
511 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500512 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400513 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
514 secondHeader.numParts = mainHeader.numParts;
515 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
516 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
517 for (i = 0 ; i < GPT_RESERVED; i++)
518 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500519 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400520 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400521} // GPTData::RebuildSecondHeader()
522
523// Search for hybrid MBR entries that have no corresponding GPT partition.
524// Returns number of such mismatches found
525int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500526 int i, found, numFound = 0;
527 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400528 uint64_t mbrFirst, mbrLast;
529
530 for (i = 0; i < 4; i++) {
531 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
532 j = 0;
533 found = 0;
534 do {
535 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
536 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
537 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
538 (partitions[j].GetLastLBA() == mbrLast))
539 found = 1;
540 j++;
srs56940283dae2010-04-28 16:44:34 -0400541 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400542 if (!found) {
543 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500544 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
545 << i + 1 << ", of type 0x";
546 cout.fill('0');
547 cout.setf(ios::uppercase);
548 cout.width(2);
549 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
550 << "has no corresponding GPT partition! You may continue, but this condition\n"
551 << "might cause data loss in the future!\a\n" << dec;
552 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400553 } // if
554 } // if
555 } // for
556 return numFound;
557} // GPTData::FindHybridMismatches
558
559// Find overlapping partitions and warn user about them. Returns number of
560// overlapping partitions.
561int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500562 int problems = 0;
563 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400564
srs56940283dae2010-04-28 16:44:34 -0400565 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400566 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500567 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400568 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500569 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
570 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
571 << " to " << partitions[i].GetLastLBA() << "\n";
572 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
573 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400574 } // if
575 } // for j...
576 } // for i...
577 return problems;
578} // GPTData::FindOverlaps()
579
srs569455d92612010-03-07 22:16:07 -0500580// Find partitions that are insane -- they start after they end or are too
581// big for the disk. (The latter should duplicate detection of overlaps
582// with GPT backup data structures, but better to err on the side of
583// redundant tests than to miss something....)
584int GPTData::FindInsanePartitions(void) {
585 uint32_t i;
586 int problems = 0;
587
srs56940283dae2010-04-28 16:44:34 -0400588 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500589 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
590 problems++;
srs56940283dae2010-04-28 16:44:34 -0400591 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500592 } // if
593 if (partitions[i].GetLastLBA() >= diskSize) {
594 problems++;
srs56940873e9d2010-10-07 13:00:45 -0400595 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500596 } // if
597 } // for
598 return problems;
599} // GPTData::FindInsanePartitions(void)
600
601
srs5694e4ac11e2009-08-31 10:13:04 -0400602/******************************************************************
603 * *
604 * Begin functions that load data from disk or save data to disk. *
605 * *
606 ******************************************************************/
607
srs569464cbd172011-03-01 22:03:54 -0500608// Change the filename associated with the GPT. Used for duplicating
609// the partition table to a new disk and saving backups.
610// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500611int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500612 int err, allOK = 1;
613
614 device = deviceFilename;
615 if (allOK && myDisk.OpenForRead(deviceFilename)) {
616 // store disk information....
617 diskSize = myDisk.DiskSize(&err);
618 blockSize = (uint32_t) myDisk.GetBlockSize();
619 } // if
620 protectiveMBR.SetDisk(&myDisk);
621 protectiveMBR.SetDiskSize(diskSize);
622 protectiveMBR.SetBlockSize(blockSize);
623 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500624} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500625
srs5694e4ac11e2009-08-31 10:13:04 -0400626// Scan for partition data. This function loads the MBR data (regular MBR or
627// protective MBR) and loads BSD disklabel data (which is probably invalid).
628// It also looks for APM data, forces a load of GPT data, and summarizes
629// the results.
srs5694546a9c72010-01-26 16:00:26 -0500630void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400631 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400632
633 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500634 protectiveMBR.ReadMBRData(&myDisk);
635 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400636
637 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500638 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500639
640 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500641 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500642 protectiveMBR.ShowState();
643 bsdDisklabel.ShowState();
644 ShowAPMState(); // Show whether there's an Apple Partition Map present
645 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500646 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500647 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400648
649 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500650 cout << "\n*******************************************************************\n"
651 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500652 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500653 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500654 } // if
srs5694fed16d02010-01-27 23:03:40 -0500655 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400656 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400657} // GPTData::PartitionScan()
658
659// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500660int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500661 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500662 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500663 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400664
srs5694546a9c72010-01-26 16:00:26 -0500665 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500666 err = myDisk.OpenForWrite(deviceFilename);
667 if ((err == 0) && (!justLooking)) {
668 cout << "\aNOTE: Write test failed with error number " << errno
669 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
670#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
671 cout << "You may be able to enable writes by exiting this program, typing\n"
672 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
673 << "program.\n";
674#endif
675 cout << "\n";
676 } // if
677 myDisk.Close(); // Close and re-open read-only in case of bugs
678 } else allOK = 0; // if
679
680 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400681 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500682 diskSize = myDisk.DiskSize(&err);
683 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500684 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500685 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400686
srs5694ba00fed2010-01-12 18:18:36 -0500687 whichWasUsed = UseWhichPartitions();
688 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400689 case use_mbr:
690 XFormPartitions();
691 break;
692 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500693 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400694// bsdDisklabel.DisplayBSDData();
695 ClearGPTData();
696 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500697 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400698 break;
699 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500700 mbrState = protectiveMBR.GetValidity();
701 if ((mbrState == invalid) || (mbrState == mbr))
702 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400703 break;
704 case use_new:
705 ClearGPTData();
706 protectiveMBR.MakeProtectiveMBR();
707 break;
srs56943c0af382010-01-15 19:19:18 -0500708 case use_abort:
709 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400710 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500711 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400712 } // switch
713
srs569455d92612010-03-07 22:16:07 -0500714 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500715 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500716 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400717 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400718 } else {
719 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400720 } // if/else
721 return (allOK);
722} // GPTData::LoadPartitions()
723
724// Loads the GPT, as much as possible. Returns 1 if this seems to have
725// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500726int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500727 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400728
srs5694cb76c672010-02-11 22:22:22 -0500729 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400730
srs5694cb76c672010-02-11 22:22:22 -0500731 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
732 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
733 } else {
srs569408bb0da2010-02-19 17:19:55 -0500734 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
735 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500736 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
737 << "secondary header from the last sector of the disk! You should use 'v' to\n"
738 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
739 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500740 } // if/else
741 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400742 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400743
744 // Return valid headers code: 0 = both headers bad; 1 = main header
745 // good, backup bad; 2 = backup header good, main header bad;
746 // 3 = both headers good. Note these codes refer to valid GPT
747 // signatures and version numbers; more subtle problems will elude
748 // this check!
749 validHeaders = CheckHeaderValidity();
750
751 // Read partitions (from primary array)
752 if (validHeaders > 0) { // if at least one header is OK....
753 // GPT appears to be valid....
754 state = gpt_valid;
755
756 // We're calling the GPT valid, but there's a possibility that one
757 // of the two headers is corrupt. If so, use the one that seems to
758 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500759 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500760 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
761 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400762 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500763 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400764 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500765 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500766 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
767 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500768 RebuildMainHeader();
769 state = gpt_corrupt;
770 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400771 } // if/else/if
772
srs5694546a9c72010-01-26 16:00:26 -0500773 // Figure out which partition table to load....
774 // Load the main partition table, since either its header's CRC is OK or the
775 // backup header's CRC is not OK....
776 if (mainCrcOk || !secondCrcOk) {
777 if (LoadMainTable() == 0)
778 allOK = 0;
779 } else { // bad main header CRC and backup header CRC is OK
780 state = gpt_corrupt;
781 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500782 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500783 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500784 } else { // backup table bad, bad main header CRC, but try main table in desperation....
785 if (LoadMainTable() == 0) {
786 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500787 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500788 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500789 } // if
790 } // if/else (LoadSecondTableAsMain())
791 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400792
srs5694cb76c672010-02-11 22:22:22 -0500793 if (loadedTable == 1)
794 secondPartsCrcOk = CheckTable(&secondHeader);
795 else if (loadedTable == 2)
796 mainPartsCrcOk = CheckTable(&mainHeader);
797 else
798 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400799
srs5694546a9c72010-01-26 16:00:26 -0500800 // Problem with main partition table; if backup is OK, use it instead....
801 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
802 state = gpt_corrupt;
803 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500804 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500805 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
806 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500807 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500808
srs5694e4ac11e2009-08-31 10:13:04 -0400809 // Check for valid CRCs and warn if there are problems
810 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
811 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500812 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400813 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500814 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400815 } else {
816 state = gpt_invalid;
817 } // if/else
818 return allOK;
819} // GPTData::ForceLoadGPTData()
820
srs5694247657a2009-11-26 18:36:12 -0500821// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400822// main GPT header in memory MUST be valid for this call to do anything
823// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500824// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400825int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500826 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400827} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400828
829// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500830// table. Used in repair functions, and when starting up if the main
831// partition table is damaged.
832// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
833int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500834 return LoadPartitionTable(secondHeader, myDisk);
835} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400836
srs5694cb76c672010-02-11 22:22:22 -0500837// Load a single GPT header (main or backup) from the specified disk device and
838// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
839// value appropriately.
840// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
841// failure.
842int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
843 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500844 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500845
846 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500847 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500848 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
849 allOK = 0;
850 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500851 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500852
srs56941c6f8b02010-02-21 11:09:20 -0500853 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500854 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500855 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500856 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500857
srs56940283dae2010-04-28 16:44:34 -0400858 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500859 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500860 }
srs56941c6f8b02010-02-21 11:09:20 -0500861
862 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500863 return allOK;
864} // GPTData::LoadHeader
865
866// Load a partition table (either main or secondary) from the specified disk,
867// using header as a reference for what to load. If sector != 0 (the default
868// is 0), loads from the specified sector; otherwise loads from the sector
869// indicated in header.
870// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
871int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
872 uint32_t sizeOfParts, newCRC;
873 int retval;
874
875 if (disk.OpenForRead()) {
876 if (sector == 0) {
877 retval = disk.Seek(header.partitionEntriesLBA);
878 } else {
879 retval = disk.Seek(sector);
880 } // if/else
srs569455d92612010-03-07 22:16:07 -0500881 if (retval == 1)
882 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500883 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500884 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
885 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500886 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500887 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500888 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400889 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500890 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400891 if (IsLittleEndian() == 0)
892 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500893 if (!mainPartsCrcOk) {
894 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400895 } // if
896 } else {
srs5694cb76c672010-02-11 22:22:22 -0500897 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400898 } // if/else
899 } else {
srs5694fed16d02010-01-27 23:03:40 -0500900 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500901 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500902 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400903 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500904 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500905} // GPTData::LoadPartitionsTable()
906
907// Check the partition table pointed to by header, but don't keep it
908// around.
909// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
910int GPTData::CheckTable(struct GPTHeader *header) {
911 uint32_t sizeOfParts, newCRC;
912 uint8_t *storage;
913 int newCrcOk = 0;
914
srs56940283dae2010-04-28 16:44:34 -0400915 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500916 // its CRC and store the results, then discard this temporary
917 // storage, since we don't use it in any but recovery operations
918 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400919 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500920 storage = new uint8_t[sizeOfParts];
921 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400922 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500923 } else {
924 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
925 newCrcOk = (newCRC == header->partitionEntriesCRC);
926 } // if/else
927 delete[] storage;
928 } // if
929 return newCrcOk;
930} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400931
srs569464cbd172011-03-01 22:03:54 -0500932// Writes GPT (and protective MBR) to disk. If quiet==1,
933// Returns 1 on successful
srs5694e7b4ff92009-08-18 13:16:10 -0400934// write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500935int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500936 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500937 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400938
srs56946699b012010-02-04 00:55:30 -0500939 littleEndian = IsLittleEndian();
940
srs5694e7b4ff92009-08-18 13:16:10 -0400941 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500942
943 // This test should only fail on read-only disks....
944 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500945 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500946 allOK = 0;
947 } // if
948
srs569464cbd172011-03-01 22:03:54 -0500949 // Check that disk is really big enough to handle the second header...
950 if (mainHeader.backupLBA >= diskSize) {
951 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
952 << "header, but other problems may occur!\n";
953 MoveSecondHeaderToEnd();
954 } // if
955
srs5694e7b4ff92009-08-18 13:16:10 -0400956 // Is there enough space to hold the GPT headers and partition tables,
957 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400958 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400959 allOK = 0;
960 } // if
961
srs5694247657a2009-11-26 18:36:12 -0500962 // Check that second header is properly placed. Warn and ask if this should
963 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -0500964 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
965 if (quiet == 0) {
966 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
967 << "correct this problem? ";
968 if (GetYN() == 'Y') {
969 MoveSecondHeaderToEnd();
970 cout << "Have moved second header and partition table to correct location.\n";
971 } else {
972 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
973 } // if correction requested
974 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -0500975 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -0500976 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -0500977 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400978
srs569455d92612010-03-07 22:16:07 -0500979 // Check for overlapping or insane partitions....
980 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400981 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500982 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400983 } // if
984
985 // Check for mismatched MBR and GPT data, but let it pass if found
986 // (function displays warning message)
987 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400988
989 RecomputeCRCs();
990
srs5694ba00fed2010-01-12 18:18:36 -0500991 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500992 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -0500993 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -0500994 answer = GetYN();
995 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500996 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400997 } else {
998 allOK = 0;
999 } // if/else
1000 } // if
1001
1002 // Do it!
1003 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001004 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001005 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001006 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1007 if (!allOK)
1008 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1009 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001010
1011 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001012 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1013
1014 // Now write the main partition tables...
1015 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1016
1017 // Now write the main GPT header...
1018 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1019
1020 // To top it off, write the protective MBR...
1021 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001022
1023 // re-read the partition table
1024 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001025 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001026 } // if
1027
1028 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001029 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001030 } else {
srs5694fed16d02010-01-27 23:03:40 -05001031 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001032 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001033 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001034
srs5694546a9c72010-01-26 16:00:26 -05001035 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001036 } else {
srs569464cbd172011-03-01 22:03:54 -05001037 cerr << "Unable to open device " << myDisk.GetName() << " for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001038 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001039 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001040 } // if/else
1041 } else {
srs5694fed16d02010-01-27 23:03:40 -05001042 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001043 } // if
1044
1045 return (allOK);
1046} // GPTData::SaveGPTData()
1047
1048// Save GPT data to a backup file. This function does much less error
1049// checking than SaveGPTData(). It can therefore preserve many types of
1050// corruption for later analysis; however, it preserves only the MBR,
1051// the main GPT header, the backup GPT header, and the main partition
1052// table; it discards the backup partition table, since it should be
1053// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001054int GPTData::SaveGPTBackup(const string & filename) {
1055 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001056 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001057
srs5694546a9c72010-01-26 16:00:26 -05001058 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001059 // Recomputing the CRCs is likely to alter them, which could be bad
1060 // if the intent is to save a potentially bad GPT for later analysis;
1061 // but if we don't do this, we get bogus errors when we load the
1062 // backup. I'm favoring misses over false alarms....
1063 RecomputeCRCs();
1064
srs5694546a9c72010-01-26 16:00:26 -05001065 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001066
srs5694cb76c672010-02-11 22:22:22 -05001067 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001068 // MBR write closed disk, so re-open and seek to end....
1069 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001070 allOK = SaveHeader(&mainHeader, backupFile, 1);
1071 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001072
srs5694e7b4ff92009-08-18 13:16:10 -04001073 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001074 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001075
srs5694cb76c672010-02-11 22:22:22 -05001076 if (allOK)
1077 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001078
1079 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001080 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001081 } else {
srs5694fed16d02010-01-27 23:03:40 -05001082 cerr << "Warning! An error was reported when writing the backup file.\n"
1083 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001084 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001085 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001086 } else {
srs5694fed16d02010-01-27 23:03:40 -05001087 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001088 allOK = 0;
1089 } // if/else
1090 return allOK;
1091} // GPTData::SaveGPTBackup()
1092
srs5694cb76c672010-02-11 22:22:22 -05001093// Write a GPT header (main or backup) to the specified sector. Used by both
1094// the SaveGPTData() and SaveGPTBackup() functions.
1095// Should be passed an architecture-appropriate header (DO NOT call
1096// ReverseHeaderBytes() on the header before calling this function)
1097// Returns 1 on success, 0 on failure
1098int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1099 int littleEndian, allOK = 1;
1100
1101 littleEndian = IsLittleEndian();
1102 if (!littleEndian)
1103 ReverseHeaderBytes(header);
1104 if (disk.Seek(sector)) {
1105 if (disk.Write(header, 512) == -1)
1106 allOK = 0;
1107 } else allOK = 0; // if (disk.Seek()...)
1108 if (!littleEndian)
1109 ReverseHeaderBytes(header);
1110 return allOK;
1111} // GPTData::SaveHeader()
1112
1113// Save the partitions to the specified sector. Used by both the SaveGPTData()
1114// and SaveGPTBackup() functions.
1115// Should be passed an architecture-appropriate header (DO NOT call
1116// ReverseHeaderBytes() on the header before calling this function)
1117// Returns 1 on success, 0 on failure
1118int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1119 int littleEndian, allOK = 1;
1120
1121 littleEndian = IsLittleEndian();
1122 if (disk.Seek(sector)) {
1123 if (!littleEndian)
1124 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001125 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001126 allOK = 0;
1127 if (!littleEndian)
1128 ReversePartitionBytes();
1129 } else allOK = 0; // if (myDisk.Seek()...)
1130 return allOK;
1131} // GPTData::SavePartitionTable()
1132
srs5694e7b4ff92009-08-18 13:16:10 -04001133// Load GPT data from a backup file created by SaveGPTBackup(). This function
1134// does minimal error checking. It returns 1 if it completed successfully,
1135// 0 if there was a problem. In the latter case, it creates a new empty
1136// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001137int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001138 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001139 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001140 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001141 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001142
srs5694546a9c72010-01-26 16:00:26 -05001143 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001144 if (IsLittleEndian() == 0)
1145 littleEndian = 0;
1146
srs5694e7b4ff92009-08-18 13:16:10 -04001147 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001148 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001149
srs5694cb76c672010-02-11 22:22:22 -05001150 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001151
srs5694cb76c672010-02-11 22:22:22 -05001152 // Check backup file size and rebuild second header if file is right
1153 // size to be direct dd copy of MBR, main header, and main partition
1154 // table; if other size, treat it like a GPT fdisk-generated backup
1155 // file
1156 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1157 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1158 if (shortBackup) {
1159 RebuildSecondHeader();
1160 secondCrcOk = mainCrcOk;
1161 } else {
1162 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1163 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001164
srs5694e7b4ff92009-08-18 13:16:10 -04001165 // Return valid headers code: 0 = both headers bad; 1 = main header
1166 // good, backup bad; 2 = backup header good, main header bad;
1167 // 3 = both headers good. Note these codes refer to valid GPT
1168 // signatures and version numbers; more subtle problems will elude
1169 // this check!
1170 if ((val = CheckHeaderValidity()) > 0) {
1171 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001172 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001173 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001174 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001175 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001176 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1177 } // if/else
1178
srs5694e7b4ff92009-08-18 13:16:10 -04001179 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001180 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1181 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001182 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001183 } // if
1184
srs5694cb76c672010-02-11 22:22:22 -05001185 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1186 cerr << "Warning! Read error " << errno
1187 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001188 } else {
1189 allOK = 0;
1190 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001191 // Something went badly wrong, so blank out partitions
1192 if (allOK == 0) {
1193 cerr << "Improper backup file! Clearing all partition data!\n";
1194 ClearGPTData();
1195 protectiveMBR.MakeProtectiveMBR();
1196 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001197 } else {
1198 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001199 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001200 } // if/else
1201
srs5694e7b4ff92009-08-18 13:16:10 -04001202 return allOK;
1203} // GPTData::LoadGPTBackup()
1204
srs569408bb0da2010-02-19 17:19:55 -05001205int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001206 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001207} // GPTData::SaveMBR()
1208
1209// This function destroys the on-disk GPT structures, but NOT the on-disk
1210// MBR.
1211// Returns 1 if the operation succeeds, 0 if not.
1212int GPTData::DestroyGPT(void) {
1213 int i, sum, tableSize, allOK = 1;
1214 uint8_t blankSector[512];
1215 uint8_t* emptyTable;
1216
1217 for (i = 0; i < 512; i++) {
1218 blankSector[i] = 0;
1219 } // for
1220
1221 if (myDisk.OpenForWrite()) {
1222 if (!myDisk.Seek(mainHeader.currentLBA))
1223 allOK = 0;
1224 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1225 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1226 allOK = 0;
1227 } // if
1228 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1229 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001230 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001231 emptyTable = new uint8_t[tableSize];
1232 for (i = 0; i < tableSize; i++)
1233 emptyTable[i] = 0;
1234 if (allOK) {
1235 sum = myDisk.Write(emptyTable, tableSize);
1236 if (sum != tableSize) {
1237 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1238 allOK = 0;
1239 } // if write failed
1240 } // if
1241 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1242 allOK = 0;
1243 if (allOK) {
1244 sum = myDisk.Write(emptyTable, tableSize);
1245 if (sum != tableSize) {
1246 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1247 << errno << "\n";
1248 allOK = 0;
1249 } // if wrong size written
1250 } // if
1251 if (!myDisk.Seek(secondHeader.currentLBA))
1252 allOK = 0;
1253 if (allOK) {
1254 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1255 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1256 allOK = 0;
1257 } // if
1258 } // if
1259 myDisk.DiskSync();
1260 myDisk.Close();
1261 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1262 << "other utilities.\n";
1263 delete[] emptyTable;
1264 } else {
1265 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1266 } // if/else (fd != -1)
1267 return (allOK);
1268} // GPTDataTextUI::DestroyGPT()
1269
1270// Wipe MBR data from the disk (zero it out completely)
1271// Returns 1 on success, 0 on failure.
1272int GPTData::DestroyMBR(void) {
1273 int allOK = 1, i;
1274 uint8_t blankSector[512];
1275
1276 for (i = 0; i < 512; i++)
1277 blankSector[i] = 0;
1278
1279 if (myDisk.OpenForWrite()) {
1280 if (myDisk.Seek(0)) {
1281 if (myDisk.Write(blankSector, 512) != 512)
1282 allOK = 0;
1283 } else allOK = 0;
1284 } else allOK = 0;
1285 if (!allOK)
1286 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1287 return allOK;
1288} // GPTData::DestroyMBR(void)
1289
srs5694e4ac11e2009-08-31 10:13:04 -04001290// Tell user whether Apple Partition Map (APM) was discovered....
1291void GPTData::ShowAPMState(void) {
1292 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001293 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001294 else
srs5694fed16d02010-01-27 23:03:40 -05001295 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001296} // GPTData::ShowAPMState()
1297
1298// Tell user about the state of the GPT data....
1299void GPTData::ShowGPTState(void) {
1300 switch (state) {
1301 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001302 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001303 break;
1304 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001305 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001306 break;
1307 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001308 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001309 break;
1310 default:
srs5694fed16d02010-01-27 23:03:40 -05001311 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001312 break;
1313 } // switch
1314} // GPTData::ShowGPTState()
1315
1316// Display the basic GPT data
1317void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001318 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001319 uint64_t temp, totalFree;
1320
srs5694fed16d02010-01-27 23:03:40 -05001321 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs56940873e9d2010-10-07 13:00:45 -04001322 << BytesToSI(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001323 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001324 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001325 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001326 cout << "First usable sector is " << mainHeader.firstUsableLBA
1327 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001328 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001329 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001330 cout << "Total free space is " << totalFree << " sectors ("
srs56940873e9d2010-10-07 13:00:45 -04001331 << BytesToSI(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001332 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001333 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001334 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001335 } // for
1336} // GPTData::DisplayGPTData()
1337
srs5694e4ac11e2009-08-31 10:13:04 -04001338// Show detailed information on the specified partition
1339void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001340 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001341 partitions[partNum].ShowDetails(blockSize);
1342 } else {
srs5694fed16d02010-01-27 23:03:40 -05001343 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001344 } // if
1345} // GPTData::ShowPartDetails()
1346
srs5694e4ac11e2009-08-31 10:13:04 -04001347/**************************************************************************
1348 * *
1349 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1350 * (some of these functions may require user interaction) *
1351 * *
1352 **************************************************************************/
1353
srs569408bb0da2010-02-19 17:19:55 -05001354// Examines the MBR & GPT data to determine which set of data to use: the
1355// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1356// a new set of partitions (use_new). A return value of use_abort indicates
1357// that this function couldn't determine what to do. Overriding functions
1358// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001359WhichToUse GPTData::UseWhichPartitions(void) {
1360 WhichToUse which = use_new;
1361 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001362
1363 mbrState = protectiveMBR.GetValidity();
1364
1365 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001366 cout << "\n***************************************************************\n"
1367 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001368 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001369 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001370 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001371 } // if
srs5694fed16d02010-01-27 23:03:40 -05001372 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001373 which = use_mbr;
1374 } // if
1375
1376 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001377 cout << "\n**********************************************************************\n"
1378 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1379 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001380 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001381 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001382 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1383 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001384 } // if
srs5694fed16d02010-01-27 23:03:40 -05001385 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001386 which = use_bsd;
1387 } // if
1388
1389 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001390 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001391 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001392 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001393 } // if
1394 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001395 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001396 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001397 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001398 } // if
1399 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001400 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001401 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001402 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001403 } // if
1404 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001405 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001406 } // if
1407
srs5694e4ac11e2009-08-31 10:13:04 -04001408 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001409 if (mbrState == gpt) {
1410 cout << "\a\a****************************************************************************\n"
1411 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1412 << "verification and recovery are STRONGLY recommended.\n"
1413 << "****************************************************************************\n";
1414 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001415 } else {
srs569408bb0da2010-02-19 17:19:55 -05001416 which = use_abort;
1417 } // if/else MBR says disk is GPT
1418 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001419
1420 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001421 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001422
1423 return which;
1424} // UseWhichPartitions()
1425
srs569408bb0da2010-02-19 17:19:55 -05001426// Convert MBR partition table into GPT form.
1427void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001428 int i, numToConvert;
1429 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001430
1431 // Clear out old data & prepare basics....
1432 ClearGPTData();
1433
1434 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001435 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001436 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001437 else
srs56940283dae2010-04-28 16:44:34 -04001438 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001439
1440 for (i = 0; i < numToConvert; i++) {
1441 origType = protectiveMBR.GetType(i);
1442 // don't waste CPU time trying to convert extended, hybrid protective, or
1443 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001444 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001445 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001446 partitions[i] = protectiveMBR.AsGPT(i);
1447 } // for
1448
1449 // Convert MBR into protective MBR
1450 protectiveMBR.MakeProtectiveMBR();
1451
1452 // Record that all original CRCs were OK so as not to raise flags
1453 // when doing a disk verification
1454 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001455} // GPTData::XFormPartitions()
1456
1457// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001458// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001459// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001460int GPTData::XFormDisklabel(uint32_t partNum) {
1461 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001462 int goOn = 1, numDone = 0;
1463 BSDData disklabel;
1464
srs569408bb0da2010-02-19 17:19:55 -05001465 if (GetPartRange(&low, &high) == 0) {
1466 goOn = 0;
1467 cout << "No partitions!\n";
1468 } // if
1469 if (partNum > high) {
1470 goOn = 0;
1471 cout << "Specified partition is invalid!\n";
1472 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001473
srs569408bb0da2010-02-19 17:19:55 -05001474 // If all is OK, read the disklabel and convert it.
1475 if (goOn) {
1476 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1477 partitions[partNum].GetLastLBA());
1478 if ((goOn) && (disklabel.IsDisklabel())) {
1479 numDone = XFormDisklabel(&disklabel);
1480 if (numDone == 1)
1481 cout << "Converted 1 BSD partition.\n";
1482 else
1483 cout << "Converted " << numDone << " BSD partitions.\n";
1484 } else {
1485 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1486 } // if/else
1487 } // if
1488 if (numDone > 0) { // converted partitions; delete carrier
1489 partitions[partNum].BlankPartition();
1490 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001491 return numDone;
srs569455d92612010-03-07 22:16:07 -05001492} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001493
1494// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001495int GPTData::XFormDisklabel(BSDData* disklabel) {
1496 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001497
srs569408bb0da2010-02-19 17:19:55 -05001498 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001499 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001500 partNum = FindFirstFreePart();
1501 if (partNum >= 0) {
1502 partitions[partNum] = disklabel->AsGPT(i);
1503 if (partitions[partNum].IsUsed())
1504 numDone++;
1505 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001506 } // for
srs569408bb0da2010-02-19 17:19:55 -05001507 if (partNum == -1)
1508 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001509 } // if
1510
1511 // Record that all original CRCs were OK so as not to raise flags
1512 // when doing a disk verification
1513 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1514
1515 return numDone;
1516} // GPTData::XFormDisklabel(BSDData* disklabel)
1517
srs569408bb0da2010-02-19 17:19:55 -05001518// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1519// partition has the active/bootable flag UNset and uses the GPT fdisk
1520// type code divided by 0x0100 as the MBR type code.
1521// Returns 1 if operation was 100% successful, 0 if there were ANY
1522// problems.
srs5694978041c2009-09-21 20:51:47 -04001523int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001524 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001525
srs5694978041c2009-09-21 20:51:47 -04001526 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001527 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001528 allOK = 0;
1529 } // if
srs56940283dae2010-04-28 16:44:34 -04001530 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001531 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001532 allOK = 0;
1533 } // if
1534 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001535 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001536 allOK = 0;
1537 } // if
1538 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1539 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1540 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001541 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1542 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001543 } // if
srs5694978041c2009-09-21 20:51:47 -04001544 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001545 (uint32_t) partitions[gptPart].GetLengthLBA(),
1546 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001547 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001548 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1549 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1550 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001551 allOK = 0;
1552 } // if/else
1553 return allOK;
1554} // GPTData::OnePartToMBR()
1555
srs5694e4ac11e2009-08-31 10:13:04 -04001556
1557/**********************************************************************
1558 * *
1559 * Functions that adjust GPT data structures WITHOUT user interaction *
1560 * (they may display information for the user's benefit, though) *
1561 * *
1562 **********************************************************************/
1563
1564// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001565// necessary, copies data if it already exists. Returns 1 if all goes
1566// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001567int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001568 GPTPart* newParts;
1569 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001570 uint32_t i, high, copyNum;
1571 int allOK = 1;
1572
1573 // First, adjust numEntries upward, if necessary, to get a number
1574 // that fills the allocated sectors
1575 i = blockSize / GPT_SIZE;
1576 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001577 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001578 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001579 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001580 } // if
1581
srs5694247657a2009-11-26 18:36:12 -05001582 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001583 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001584 // partition table, which causes problems when loading data from a RAID
1585 // array that's been expanded because this function is called when loading
1586 // data.
srs56940283dae2010-04-28 16:44:34 -04001587 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001588 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001589 if (newParts != NULL) {
1590 if (partitions != NULL) { // existing partitions; copy them over
1591 GetPartRange(&i, &high);
1592 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001593 cout << "The highest-numbered partition is " << high + 1
1594 << ", which is greater than the requested\n"
1595 << "partition table size of " << numEntries
1596 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001597 allOK = 0;
1598 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001599 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001600 copyNum = numEntries;
1601 else
srs56940283dae2010-04-28 16:44:34 -04001602 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001603 for (i = 0; i < copyNum; i++) {
1604 newParts[i] = partitions[i];
1605 } // for
1606 trash = partitions;
1607 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001608 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001609 } // if
1610 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001611 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001612 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001613 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001614 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1615 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1616 MoveSecondHeaderToEnd();
1617 if (diskSize > 0)
1618 CheckGPTSize();
1619 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001620 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001621 allOK = 0;
1622 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001623 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001624 mainHeader.numParts = numParts;
1625 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001626 return (allOK);
1627} // GPTData::SetGPTSize()
1628
1629// Blank the partition array
1630void GPTData::BlankPartitions(void) {
1631 uint32_t i;
1632
srs56940283dae2010-04-28 16:44:34 -04001633 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001634 partitions[i].BlankPartition();
1635 } // for
1636} // GPTData::BlankPartitions()
1637
srs5694ba00fed2010-01-12 18:18:36 -05001638// Delete a partition by number. Returns 1 if successful,
1639// 0 if there was a problem. Returns 1 if partition was in
1640// range, 0 if it was out of range.
1641int GPTData::DeletePartition(uint32_t partNum) {
1642 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001643 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001644
srs56940283dae2010-04-28 16:44:34 -04001645 numUsedParts = GetPartRange(&low, &high);
1646 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001647 // In case there's a protective MBR, look for & delete matching
1648 // MBR partition....
1649 startSector = partitions[partNum].GetFirstLBA();
1650 length = partitions[partNum].GetLengthLBA();
1651 protectiveMBR.DeleteByLocation(startSector, length);
1652
1653 // Now delete the GPT partition
1654 partitions[partNum].BlankPartition();
1655 } else {
srs5694fed16d02010-01-27 23:03:40 -05001656 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001657 retval = 0;
1658 } // if/else
1659 return retval;
1660} // GPTData::DeletePartition(uint32_t partNum)
1661
srs569408bb0da2010-02-19 17:19:55 -05001662// Non-interactively create a partition.
1663// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001664uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001665 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001666 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001667
1668 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001669 if (Align(&startSector)) {
1670 cout << "Information: Moved requested sector from " << origSector << " to "
1671 << startSector << " in\norder to align on " << sectorAlignment
1672 << "-sector boundaries.\n";
1673 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001674 if (IsFree(startSector) && (startSector <= endSector)) {
1675 if (FindLastInFree(startSector) >= endSector) {
1676 partitions[partNum].SetFirstLBA(startSector);
1677 partitions[partNum].SetLastLBA(endSector);
1678 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001679 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001680 } else retval = 0; // if free space until endSector
1681 } else retval = 0; // if startSector is free
1682 } else retval = 0; // if legal partition number
1683 return retval;
1684} // GPTData::CreatePartition(partNum, startSector, endSector)
1685
srs5694e4ac11e2009-08-31 10:13:04 -04001686// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001687// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001688void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001689 if (numParts > 0)
1690 sort(partitions, partitions + numParts - 1);
srs5694e4ac11e2009-08-31 10:13:04 -04001691} // GPTData::SortGPT()
1692
srs569408bb0da2010-02-19 17:19:55 -05001693// Swap the contents of two partitions.
1694// Returns 1 if successful, 0 if either partition is out of range
1695// (that is, not a legal number; either or both can be empty).
1696// Note that if partNum1 = partNum2 and this number is in range,
1697// it will be considered successful.
1698int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1699 GPTPart temp;
1700 int allOK = 1;
1701
srs56940283dae2010-04-28 16:44:34 -04001702 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001703 if (partNum1 != partNum2) {
1704 temp = partitions[partNum1];
1705 partitions[partNum1] = partitions[partNum2];
1706 partitions[partNum2] = temp;
1707 } // if
1708 } else allOK = 0; // partition numbers are valid
1709 return allOK;
1710} // GPTData::SwapPartitions()
1711
srs5694e4ac11e2009-08-31 10:13:04 -04001712// Set up data structures for entirely new set of partitions on the
1713// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001714// Note that this function does NOT clear the protectiveMBR data
1715// structure, since it may hold the original MBR partitions if the
1716// program was launched on an MBR disk, and those may need to be
1717// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001718int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001719 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001720
1721 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001722 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001723 partitions = NULL;
1724 SetGPTSize(NUM_GPT_ENTRIES);
1725
1726 // Now initialize a bunch of stuff that's static....
1727 mainHeader.signature = GPT_SIGNATURE;
1728 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001729 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001730 mainHeader.reserved = 0;
1731 mainHeader.currentLBA = UINT64_C(1);
1732 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1733 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1734 for (i = 0; i < GPT_RESERVED; i++) {
1735 mainHeader.reserved2[i] = '\0';
1736 } // for
srs56940873e9d2010-10-07 13:00:45 -04001737 if (blockSize > 0)
1738 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1739 else
1740 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001741
1742 // Now some semi-static items (computed based on end of disk)
1743 mainHeader.backupLBA = diskSize - UINT64_C(1);
1744 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1745
1746 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001747 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001748
1749 // Copy main header to backup header
1750 RebuildSecondHeader();
1751
1752 // Blank out the partitions array....
1753 BlankPartitions();
1754
1755 // Flag all CRCs as being OK....
1756 mainCrcOk = 1;
1757 secondCrcOk = 1;
1758 mainPartsCrcOk = 1;
1759 secondPartsCrcOk = 1;
1760
1761 return (goOn);
1762} // GPTData::ClearGPTData()
1763
srs5694247657a2009-11-26 18:36:12 -05001764// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001765// If the disk size has actually changed, this also adjusts the protective
1766// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001767// Used internally and called by the 'e' option on the recovery &
1768// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001769// to their arrays or to adjust data structures in restore operations
1770// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001771void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001772 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001773 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1774 if (protectiveMBR.GetValidity() == hybrid) {
1775 protectiveMBR.OptimizeEESize();
1776 RecomputeCHS();
1777 } // if
1778 if (protectiveMBR.GetValidity() == gpt)
1779 MakeProtectiveMBR();
1780 } // if
srs56948bb78762009-11-24 15:43:49 -05001781 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1782 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1783} // GPTData::FixSecondHeaderLocation()
1784
srs56940a697312010-01-28 21:10:52 -05001785int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001786 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001787
1788 if (!IsFreePartNum(partNum)) {
1789 partitions[partNum].SetName(theName);
1790 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001791
1792 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001793} // GPTData::SetName
1794
1795// Set the disk GUID to the specified value. Note that the header CRCs must
1796// be recomputed after calling this function.
1797void GPTData::SetDiskGUID(GUIDData newGUID) {
1798 mainHeader.diskGUID = newGUID;
1799 secondHeader.diskGUID = newGUID;
1800} // SetDiskGUID()
1801
1802// Set the unique GUID of the specified partition. Returns 1 on
1803// successful completion, 0 if there were problems (invalid
1804// partition number).
1805int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1806 int retval = 0;
1807
srs56940283dae2010-04-28 16:44:34 -04001808 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001809 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1810 partitions[pn].SetUniqueGUID(theGUID);
1811 retval = 1;
1812 } // if
1813 } // if
1814 return retval;
1815} // GPTData::SetPartitionGUID()
1816
srs56949ba54212010-05-18 23:24:02 -04001817// Set new random GUIDs for the disk and all partitions. Intended to be used
1818// after disk cloning or similar operations that don't randomize the GUIDs.
1819void GPTData::RandomizeGUIDs(void) {
1820 uint32_t i;
1821
1822 mainHeader.diskGUID.Randomize();
1823 secondHeader.diskGUID = mainHeader.diskGUID;
1824 for (i = 0; i < numParts; i++)
1825 if (partitions[i].IsUsed())
1826 partitions[i].RandomizeUniqueGUID();
1827} // GPTData::RandomizeGUIDs()
1828
srs5694ba00fed2010-01-12 18:18:36 -05001829// Change partition type code non-interactively. Returns 1 if
1830// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001831int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1832 int retval = 1;
1833
1834 if (!IsFreePartNum(partNum)) {
1835 partitions[partNum].SetType(theGUID);
1836 } else retval = 0;
1837 return retval;
1838} // GPTData::ChangePartType()
1839
srs56949ba54212010-05-18 23:24:02 -04001840// Recompute the CHS values of all the MBR partitions. Used to reset
1841// CHS values that some BIOSes require, despite the fact that the
1842// resulting CHS values violate the GPT standard.
1843void GPTData::RecomputeCHS(void) {
1844 int i;
1845
1846 for (i = 0; i < 4; i++)
1847 protectiveMBR.RecomputeCHS(i);
1848} // GPTData::RecomputeCHS()
1849
srs56941d1448a2009-12-31 21:20:19 -05001850// Adjust sector number so that it falls on a sector boundary that's a
1851// multiple of sectorAlignment. This is done to improve the performance
1852// of Western Digital Advanced Format disks and disks with similar
1853// technology from other companies, which use 4096-byte sectors
1854// internally although they translate to 512-byte sectors for the
1855// benefit of the OS. If partitions aren't properly aligned on these
1856// disks, some filesystem data structures can span multiple physical
1857// sectors, degrading performance. This function should be called
1858// only on the FIRST sector of the partition, not the last!
1859// This function returns 1 if the alignment was altered, 0 if it
1860// was unchanged.
1861int GPTData::Align(uint64_t* sector) {
1862 int retval = 0, sectorOK = 0;
1863 uint64_t earlier, later, testSector, original;
1864
1865 if ((*sector % sectorAlignment) != 0) {
1866 original = *sector;
srs56941d1448a2009-12-31 21:20:19 -05001867 earlier = (*sector / sectorAlignment) * sectorAlignment;
1868 later = earlier + (uint64_t) sectorAlignment;
1869
1870 // Check to see that every sector between the earlier one and the
1871 // requested one is clear, and that it's not too early....
1872 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001873 sectorOK = 1;
1874 testSector = earlier;
1875 do {
1876 sectorOK = IsFree(testSector++);
1877 } while ((sectorOK == 1) && (testSector < *sector));
1878 if (sectorOK == 1) {
1879 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001880 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001881 } // if
1882 } // if firstUsableLBA check
1883
1884 // If couldn't move the sector earlier, try to move it later instead....
1885 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1886 sectorOK = 1;
1887 testSector = later;
1888 do {
1889 sectorOK = IsFree(testSector--);
1890 } while ((sectorOK == 1) && (testSector > *sector));
1891 if (sectorOK == 1) {
1892 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001893 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001894 } // if
1895 } // if
srs56941d1448a2009-12-31 21:20:19 -05001896 } // if
1897 return retval;
1898} // GPTData::Align()
1899
srs5694e4ac11e2009-08-31 10:13:04 -04001900/********************************************************
1901 * *
1902 * Functions that return data about GPT data structures *
1903 * (most of these are inline in gpt.h) *
1904 * *
1905 ********************************************************/
1906
1907// Find the low and high used partition numbers (numbered from 0).
1908// Return value is the number of partitions found. Note that the
1909// *low and *high values are both set to 0 when no partitions
1910// are found, as well as when a single partition in the first
1911// position exists. Thus, the return value is the only way to
1912// tell when no partitions exist.
1913int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1914 uint32_t i;
1915 int numFound = 0;
1916
srs56940283dae2010-04-28 16:44:34 -04001917 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001918 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001919 for (i = 0; i < numParts; i++) {
1920 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1921 *high = i; // since we're counting up, set the high value
1922 // Set the low value only if it's not yet found...
1923 if (*low == (numParts + 1)) *low = i;
1924 numFound++;
1925 } // if
1926 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04001927
1928 // Above will leave *low pointing to its "not found" value if no partitions
1929 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001930 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001931 *low = 0;
1932 return numFound;
1933} // GPTData::GetPartRange()
1934
srs569408bb0da2010-02-19 17:19:55 -05001935// Returns the value of the first free partition, or -1 if none is
1936// unused.
1937int GPTData::FindFirstFreePart(void) {
1938 int i = 0;
1939
1940 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04001941 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05001942 i++;
srs56940283dae2010-04-28 16:44:34 -04001943 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001944 i = -1;
1945 } else i = -1;
1946 return i;
1947} // GPTData::FindFirstFreePart()
1948
srs5694978041c2009-09-21 20:51:47 -04001949// Returns the number of defined partitions.
1950uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001951 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001952
srs56940283dae2010-04-28 16:44:34 -04001953 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001954 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001955 counted++;
1956 } // for
1957 return counted;
1958} // GPTData::CountParts()
1959
srs5694e4ac11e2009-08-31 10:13:04 -04001960/****************************************************
1961 * *
1962 * Functions that return data about disk free space *
1963 * *
1964 ****************************************************/
1965
1966// Find the first available block after the starting point; returns 0 if
1967// there are no available blocks left
1968uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1969 uint64_t first;
1970 uint32_t i;
1971 int firstMoved = 0;
1972
1973 // Begin from the specified starting point or from the first usable
1974 // LBA, whichever is greater...
1975 if (start < mainHeader.firstUsableLBA)
1976 first = mainHeader.firstUsableLBA;
1977 else
1978 first = start;
1979
1980 // ...now search through all partitions; if first is within an
1981 // existing partition, move it to the next sector after that
1982 // partition and repeat. If first was moved, set firstMoved
1983 // flag; repeat until firstMoved is not set, so as to catch
1984 // cases where partitions are out of sequential order....
1985 do {
1986 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04001987 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001988 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001989 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001990 first = partitions[i].GetLastLBA() + 1;
1991 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001992 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001993 } // for
1994 } while (firstMoved == 1);
1995 if (first > mainHeader.lastUsableLBA)
1996 first = 0;
1997 return (first);
1998} // GPTData::FindFirstAvailable()
1999
2000// Finds the first available sector in the largest block of unallocated
2001// space on the disk. Returns 0 if there are no available blocks left
2002uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002003 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002004
2005 start = 0;
2006 do {
2007 firstBlock = FindFirstAvailable(start);
2008 if (firstBlock != UINT32_C(0)) { // something's free...
2009 lastBlock = FindLastInFree(firstBlock);
2010 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2011 if (segmentSize > selectedSize) {
2012 selectedSize = segmentSize;
2013 selectedSegment = firstBlock;
2014 } // if
2015 start = lastBlock + 1;
2016 } // if
2017 } while (firstBlock != 0);
2018 return selectedSegment;
2019} // GPTData::FindFirstInLargest()
2020
srs5694cb76c672010-02-11 22:22:22 -05002021// Find the last available block on the disk.
2022// Returns 0 if there are no available partitions
2023uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002024 uint64_t last;
2025 uint32_t i;
2026 int lastMoved = 0;
2027
2028 // Start by assuming the last usable LBA is available....
2029 last = mainHeader.lastUsableLBA;
2030
2031 // ...now, similar to algorithm in FindFirstAvailable(), search
2032 // through all partitions, moving last when it's in an existing
2033 // partition. Set the lastMoved flag so we repeat to catch cases
2034 // where partitions are out of logical order.
2035 do {
2036 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002037 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002038 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002039 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002040 last = partitions[i].GetFirstLBA() - 1;
2041 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002042 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002043 } // for
2044 } while (lastMoved == 1);
2045 if (last < mainHeader.firstUsableLBA)
2046 last = 0;
2047 return (last);
2048} // GPTData::FindLastAvailable()
2049
2050// Find the last available block in the free space pointed to by start.
2051uint64_t GPTData::FindLastInFree(uint64_t start) {
2052 uint64_t nearestStart;
2053 uint32_t i;
2054
2055 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002056 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002057 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002058 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002059 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002060 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002061 } // for
2062 return (nearestStart);
2063} // GPTData::FindLastInFree()
2064
2065// Finds the total number of free blocks, the number of segments in which
2066// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002067uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002068 uint64_t start = UINT64_C(0); // starting point for each search
2069 uint64_t totalFound = UINT64_C(0); // running total
2070 uint64_t firstBlock; // first block in a segment
2071 uint64_t lastBlock; // last block in a segment
2072 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002073 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002074
2075 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002076 if (diskSize > 0) {
2077 do {
2078 firstBlock = FindFirstAvailable(start);
2079 if (firstBlock != UINT64_C(0)) { // something's free...
2080 lastBlock = FindLastInFree(firstBlock);
2081 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2082 if (segmentSize > *largestSegment) {
2083 *largestSegment = segmentSize;
2084 } // if
2085 totalFound += segmentSize;
2086 num++;
2087 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002088 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002089 } while (firstBlock != 0);
2090 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002091 *numSegments = num;
2092 return totalFound;
2093} // GPTData::FindFreeBlocks()
2094
srs569455d92612010-03-07 22:16:07 -05002095// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2096// If it's allocated, return the partition number to which it's allocated
2097// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2098// returned in partNum if the sector is in use by basic GPT data structures.)
2099int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002100 int isFree = 1;
2101 uint32_t i;
2102
srs56940283dae2010-04-28 16:44:34 -04002103 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002104 if ((sector >= partitions[i].GetFirstLBA()) &&
2105 (sector <= partitions[i].GetLastLBA())) {
2106 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002107 if (partNum != NULL)
2108 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002109 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002110 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002111 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002112 (sector > mainHeader.lastUsableLBA)) {
2113 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002114 if (partNum != NULL)
2115 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002116 } // if
2117 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002118} // GPTData::IsFree()
2119
srs5694ba00fed2010-01-12 18:18:36 -05002120// Returns 1 if partNum is unused.
2121int GPTData::IsFreePartNum(uint32_t partNum) {
2122 int retval = 1;
2123
srs56940283dae2010-04-28 16:44:34 -04002124 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002125 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002126 retval = 0;
2127 } // if partition is in use
2128 } else retval = 0;
2129
2130 return retval;
2131} // GPTData::IsFreePartNum()
2132
srs5694a8582cf2010-03-19 14:21:59 -04002133
2134/***********************************************************
2135 * *
2136 * Change how functions work or return information on them *
2137 * *
2138 ***********************************************************/
2139
2140// Set partition alignment value; partitions will begin on multiples of
2141// the specified value
2142void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002143 if (n > 0)
2144 sectorAlignment = n;
2145 else
2146 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002147} // GPTData::SetAlignment()
2148
2149// Compute sector alignment based on the current partitions (if any). Each
2150// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002151// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2152// sector size), but not by the previously-located alignment value, then the
2153// alignment value is adjusted down. If the computed alignment is less than 8
2154// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2155// is a safety measure for WD Advanced Format and similar drives. If no partitions
2156// are defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2157// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002158// drives are aligned to 2048-sector multiples but the program won't complain
2159// about other alignments on existing disks unless a smaller-than-8 alignment
srs56940873e9d2010-10-07 13:00:45 -04002160// is used on big disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002161// Returns the computed alignment value.
2162uint32_t GPTData::ComputeAlignment(void) {
2163 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002164 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002165
srs56940873e9d2010-10-07 13:00:45 -04002166 if (blockSize > 0)
2167 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2168 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002169 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002170 if (partitions[i].IsUsed()) {
2171 found = 0;
2172 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002173 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002174 if ((partitions[i].GetFirstLBA() % align) == 0) {
2175 found = 1;
2176 } else {
2177 exponent--;
2178 } // if/else
2179 } // while
2180 } // if
2181 } // for
srs56940873e9d2010-10-07 13:00:45 -04002182 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2183 align = MIN_AF_ALIGNMENT;
2184 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002185 return align;
2186} // GPTData::ComputeAlignment()
2187
srs5694e4ac11e2009-08-31 10:13:04 -04002188/********************************
2189 * *
2190 * Endianness support functions *
2191 * *
2192 ********************************/
2193
srs56942a9f5da2009-08-26 00:48:01 -04002194void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002195 ReverseBytes(&header->signature, 8);
2196 ReverseBytes(&header->revision, 4);
2197 ReverseBytes(&header->headerSize, 4);
2198 ReverseBytes(&header->headerCRC, 4);
2199 ReverseBytes(&header->reserved, 4);
2200 ReverseBytes(&header->currentLBA, 8);
2201 ReverseBytes(&header->backupLBA, 8);
2202 ReverseBytes(&header->firstUsableLBA, 8);
2203 ReverseBytes(&header->lastUsableLBA, 8);
2204 ReverseBytes(&header->partitionEntriesLBA, 8);
2205 ReverseBytes(&header->numParts, 4);
2206 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2207 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002208 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002209} // GPTData::ReverseHeaderBytes()
2210
srs56940283dae2010-04-28 16:44:34 -04002211// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002212void GPTData::ReversePartitionBytes() {
2213 uint32_t i;
2214
srs56940283dae2010-04-28 16:44:34 -04002215 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002216 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002217 } // for
2218} // GPTData::ReversePartitionBytes()
2219
srs56949ddc14b2010-08-22 22:44:42 -04002220// Validate partition number
2221bool GPTData::ValidPartNum (const uint32_t partNum) {
2222 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002223 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002224 return false;
2225 } // if
2226 return true;
2227} // GPTData::ValidPartNum
2228
srs56945a081752010-09-24 20:39:41 -04002229// Return a single partition for inspection (not modification!) by other
2230// functions.
2231const GPTPart & GPTData::operator[](uint32_t partNum) const {
2232 if (partNum >= numParts) {
2233 cerr << "Partition number out of range: " << partNum << "\n";
2234 partNum = 0;
srs56949a46b042011-03-15 00:34:10 -04002235 if ((numParts == 0) || (partitions == NULL)) {
2236 cerr << "No partitions defined; fatal error!\n";
2237 exit(1);
2238 } // if
srs56945a081752010-09-24 20:39:41 -04002239 } // if
2240 return partitions[partNum];
2241} // operator[]
2242
2243// Return (not for modification!) the disk's GUID value
2244const GUIDData & GPTData::GetDiskGUID(void) const {
2245 return mainHeader.diskGUID;
2246} // GPTData::GetDiskGUID()
2247
srs56949ddc14b2010-08-22 22:44:42 -04002248// Manage attributes for a partition, based on commands passed to this function.
2249// (Function is non-interactive.)
2250// Returns 1 if a modification command succeeded, 0 if the command should not have
2251// modified data, and -1 if a modification command failed.
2252int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2253 int retval = 0;
2254 Attributes theAttr;
2255
2256 if (command == "show") {
2257 ShowAttributes(partNum);
2258 } else if (command == "get") {
2259 GetAttribute(partNum, bits);
2260 } else {
2261 theAttr = partitions[partNum].GetAttributes();
2262 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2263 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2264 retval = 1;
2265 } else {
2266 retval = -1;
2267 } // if/else
2268 } // if/elseif/else
2269
2270 return retval;
2271} // GPTData::ManageAttributes()
2272
2273// Show all attributes for a specified partition....
2274void GPTData::ShowAttributes(const uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04002275 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002276} // GPTData::ShowAttributes
2277
2278// Show whether a single attribute bit is set (terse output)...
2279void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002280 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002281} // GPTData::GetAttribute
2282
2283
srs56942a9f5da2009-08-26 00:48:01 -04002284/******************************************
2285 * *
2286 * Additional non-class support functions *
2287 * *
2288 ******************************************/
2289
srs5694e7b4ff92009-08-18 13:16:10 -04002290// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2291// never fail these tests, but the struct types may fail depending on compile options.
2292// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2293// sizes.
2294int SizesOK(void) {
2295 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002296
2297 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002298 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002299 allOK = 0;
2300 } // if
2301 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002302 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002303 allOK = 0;
2304 } // if
2305 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002306 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002307 allOK = 0;
2308 } // if
2309 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002310 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002311 allOK = 0;
2312 } // if
2313 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002314 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002315 allOK = 0;
2316 } // if
srs5694978041c2009-09-21 20:51:47 -04002317 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002318 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002319 allOK = 0;
2320 } // if
2321 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002322 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002323 allOK = 0;
2324 } // if
srs5694221e0872009-08-29 15:00:31 -04002325 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002326 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002327 allOK = 0;
2328 } // if
srs56946699b012010-02-04 00:55:30 -05002329 if (sizeof(GUIDData) != 16) {
2330 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2331 allOK = 0;
2332 } // if
2333 if (sizeof(PartType) != 16) {
2334 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2335 allOK = 0;
2336 } // if
srs5694fed16d02010-01-27 23:03:40 -05002337 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56940873e9d2010-10-07 13:00:45 -04002338// if (IsLittleEndian() == 0) {
2339// cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2340// " tested!\n";
2341// } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002342 return (allOK);
2343} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002344