blob: 309a038fb8264080dec82347ec1260f05cf01362 [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>
srs5694e7b4ff92009-08-18 13:16:10 -040022#include "crc32.h"
23#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040024#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040025#include "support.h"
26#include "parttypes.h"
27#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050028#include "diskio.h"
srs569455d92612010-03-07 22:16:07 -050029#include "partnotes.h"
srs5694e7b4ff92009-08-18 13:16:10 -040030
31using namespace std;
32
srs56948f1b2d62010-05-23 13:07:19 -040033#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040034#define log2(x) (log(x) / M_LN2)
35#endif // __FreeBSD__
36
srs56948f1b2d62010-05-23 13:07:19 -040037#ifdef _MSC_VER
38#define log2(x) (log((double) x) / log(2.0))
39#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040040
srs5694e7b4ff92009-08-18 13:16:10 -040041/****************************************
42 * *
43 * GPTData class and related structures *
44 * *
45 ****************************************/
46
srs5694e4ac11e2009-08-31 10:13:04 -040047// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040048GPTData::GPTData(void) {
49 blockSize = SECTOR_SIZE; // set a default
50 diskSize = 0;
51 partitions = NULL;
52 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050053 device = "";
srs56945d58fe02010-01-03 20:57:08 -050054 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040055 mainCrcOk = 0;
56 secondCrcOk = 0;
57 mainPartsCrcOk = 0;
58 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040059 apmFound = 0;
60 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040061 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050062 beQuiet = 0;
63 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040064 srand((unsigned int) time(NULL));
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;
srs5694e7b4ff92009-08-18 13:16:10 -040087 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050088 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040089 numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050090 if (!LoadPartitions(filename))
91 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050092} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040093
srs5694e4ac11e2009-08-31 10:13:04 -040094// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040095GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050096 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040097} // GPTData destructor
98
srs569464cbd172011-03-01 22:03:54 -050099// Assignment operator
100GPTData & GPTData::operator=(const GPTData & orig) {
101 uint32_t i;
102
103 mainHeader = orig.mainHeader;
104 numParts = orig.numParts;
105 secondHeader = orig.secondHeader;
106 protectiveMBR = orig.protectiveMBR;
107 device = orig.device;
108 blockSize = orig.blockSize;
109 diskSize = orig.diskSize;
110 state = orig.state;
111 justLooking = orig.justLooking;
112 mainCrcOk = orig.mainCrcOk;
113 secondCrcOk = orig.secondCrcOk;
114 mainPartsCrcOk = orig.mainPartsCrcOk;
115 secondPartsCrcOk = orig.secondPartsCrcOk;
116 apmFound = orig.apmFound;
117 bsdFound = orig.bsdFound;
118 sectorAlignment = orig.sectorAlignment;
119 beQuiet = orig.beQuiet;
120 whichWasUsed = orig.whichWasUsed;
121
122 myDisk.OpenForRead(orig.myDisk.GetName());
123
124 delete[] partitions;
125 partitions = new GPTPart [numParts * sizeof (GPTPart)];
126 if (partitions != NULL) {
127 for (i = 0; i < numParts; i++) {
128 partitions[i] = orig.partitions[i];
129 }
130 } else {
131 numParts = 0;
132 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
133 << "Continuing, but strange problems may occur!\n";
134 } // if/else
135 return *this;
136} // GPTData::operator=()
137
srs5694e4ac11e2009-08-31 10:13:04 -0400138/*********************************************************************
139 * *
140 * Begin functions that verify data, or that adjust the verification *
141 * information (compute CRCs, rebuild headers) *
142 * *
143 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400144
srs5694e4ac11e2009-08-31 10:13:04 -0400145// Perform detailed verification, reporting on any problems found, but
146// do *NOT* recover from these problems. Returns the total number of
147// problems identified.
148int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500149 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500150 uint32_t i, numSegments;
151 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400152
153 // First, check for CRC errors in the GPT data....
154 if (!mainCrcOk) {
155 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500156 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
157 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
158 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
159 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400160 } // if
161 if (!mainPartsCrcOk) {
162 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500163 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
164 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
165 << "transformation menu). This report may be a false alarm if you've already\n"
166 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400167 } // if
168 if (!secondCrcOk) {
169 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500170 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
171 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
172 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
173 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400174 } // if
175 if (!secondPartsCrcOk) {
176 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500177 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
178 << "be corrupt. This program will automatically create a new backup partition\n"
179 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400180 } // if
181
srs5694978041c2009-09-21 20:51:47 -0400182 // Now check that the main and backup headers both point to themselves....
183 if (mainHeader.currentLBA != 1) {
184 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500185 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
186 << "is being automatically corrected, but it may be a symptom of more serious\n"
187 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400188 mainHeader.currentLBA = 1;
189 } // if
190 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
191 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500192 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
193 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
194 << "option on the experts' menu to adjust the secondary header's and partition\n"
195 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400196 } // if
197
198 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400199 if (mainHeader.currentLBA != secondHeader.backupLBA) {
200 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500201 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
202 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
203 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400204 } // if
205 if (mainHeader.backupLBA != secondHeader.currentLBA) {
206 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500207 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
208 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
209 << secondHeader.currentLBA << ").\n"
210 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400211 } // if
212 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
213 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500214 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
215 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
216 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400217 } // if
218 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
219 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500220 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
221 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
222 << secondHeader.lastUsableLBA << ")\n"
223 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400224 } // if
srs56946699b012010-02-04 00:55:30 -0500225 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400226 problems++;
srs56945a081752010-09-24 20:39:41 -0400227 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500228 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400229 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500230 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
231 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400232 } // if
233 if (mainHeader.numParts != secondHeader.numParts) {
234 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500235 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
236 << ") doesn't\nmatch the backup GPT header's number of partitions ("
237 << secondHeader.numParts << ")\n"
238 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400239 } // if
240 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
241 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500242 cout << "\nProblem: main GPT header's size of partition entries ("
243 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
244 << "match the backup GPT header's size of partition entries ("
245 << secondHeader.sizeOfPartitionEntries << ")\n"
246 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
247 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400248 } // if
249
250 // Now check for a few other miscellaneous problems...
251 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500252 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400253 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500254 cout << "\nProblem: Disk is too small to hold all the data!\n"
255 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500256 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500257 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400258 } // if
259
260 // Check for overlapping partitions....
261 problems += FindOverlaps();
262
srs569455d92612010-03-07 22:16:07 -0500263 // Check for insane partitions (start after end, hugely big, etc.)
264 problems += FindInsanePartitions();
265
srs5694e4ac11e2009-08-31 10:13:04 -0400266 // Check for mismatched MBR and GPT partitions...
267 problems += FindHybridMismatches();
268
srs5694327129e2010-09-22 01:07:31 -0400269 // Check for MBR-specific problems....
270 problems += VerifyMBR();
271
srs5694e4ac11e2009-08-31 10:13:04 -0400272 // Verify that partitions don't run into GPT data areas....
273 problems += CheckGPTSize();
274
srs56941d1448a2009-12-31 21:20:19 -0500275 // Check that partitions are aligned on proper boundaries (for WD Advanced
276 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400277 for (i = 0; i < numParts; i++) {
srs56941d1448a2009-12-31 21:20:19 -0500278 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
280 << sectorAlignment << "-sector boundary. This may\nresult "
281 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500282 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500283 } // if
284 } // for
srs569464cbd172011-03-01 22:03:54 -0500285 if (alignProbs > 0)
286 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
287 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500288
srs5694e4ac11e2009-08-31 10:13:04 -0400289 // Now compute available space, but only if no problems found, since
290 // problems could affect the results
291 if (problems == 0) {
292 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500293 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs56940873e9d2010-10-07 13:00:45 -0400294 << BytesToSI(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500295 << numSegments << "\nsegments, the largest of which is "
srs56940873e9d2010-10-07 13:00:45 -0400296 << largestSegment << " (" << BytesToSI(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400297 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400298 } else {
srs56940a697312010-01-28 21:10:52 -0500299 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400300 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400301
302 return (problems);
303} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400304
305// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400306// do, issues a warning but takes no action. Returns number of problems
307// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400308int GPTData::CheckGPTSize(void) {
309 uint64_t overlap, firstUsedBlock, lastUsedBlock;
310 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400311 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400312
313 // first, locate the first & last used blocks
314 firstUsedBlock = UINT64_MAX;
315 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400316 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400317 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400318 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400319 firstUsedBlock = partitions[i].GetFirstLBA();
320 if (partitions[i].GetLastLBA() > lastUsedBlock)
321 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400322 } // for
323
324 // If the disk size is 0 (the default), then it means that various
325 // variables aren't yet set, so the below tests will be useless;
326 // therefore we should skip everything
327 if (diskSize != 0) {
328 if (mainHeader.firstUsableLBA > firstUsedBlock) {
329 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500330 cout << "Warning! Main partition table overlaps the first partition by "
331 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400332 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500333 cout << "Try reducing the partition table size by " << overlap * 4
334 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400335 } else {
srs5694fed16d02010-01-27 23:03:40 -0500336 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400337 } // if/else
338 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400339 } // Problem at start of disk
340 if (mainHeader.lastUsableLBA < lastUsedBlock) {
341 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500342 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500343 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400344 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500345 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400346 } else {
srs5694fed16d02010-01-27 23:03:40 -0500347 cout << "Try reducing the partition table size by " << overlap * 4
348 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400349 } // if/else
350 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400351 } // Problem at end of disk
352 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400353 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400354} // GPTData::CheckGPTSize()
355
srs5694e7b4ff92009-08-18 13:16:10 -0400356// Check the validity of the GPT header. Returns 1 if the main header
357// is valid, 2 if the backup header is valid, 3 if both are valid, and
358// 0 if neither is valid. Note that this function just checks the GPT
359// signature and revision numbers, not CRCs or other data.
360int GPTData::CheckHeaderValidity(void) {
361 int valid = 3;
362
srs5694fed16d02010-01-27 23:03:40 -0500363 cout.setf(ios::uppercase);
364 cout.fill('0');
365
366 // Note: failed GPT signature checks produce no error message because
367 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400368 if (mainHeader.signature != GPT_SIGNATURE) {
369 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400370 } else if ((mainHeader.revision != 0x00010000) && valid) {
371 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500372 cout << "Unsupported GPT version in main header; read 0x";
373 cout.width(8);
374 cout << hex << mainHeader.revision << ", should be\n0x";
375 cout.width(8);
376 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400377 } // if/else/if
378
379 if (secondHeader.signature != GPT_SIGNATURE) {
380 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400381 } else if ((secondHeader.revision != 0x00010000) && valid) {
382 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500383 cout << "Unsupported GPT version in backup header; read 0x";
384 cout.width(8);
385 cout << hex << secondHeader.revision << ", should be\n0x";
386 cout.width(8);
387 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400388 } // if/else/if
389
srs5694df9d3632011-01-08 18:33:24 -0500390 // Check for an Apple disk signature
391 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
392 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400393 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500394 } // if
srs5694fed16d02010-01-27 23:03:40 -0500395 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400396
srs5694fed16d02010-01-27 23:03:40 -0500397 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400398} // GPTData::CheckHeaderValidity()
399
400// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500401// Note: Must be called with header in LITTLE-ENDIAN
402// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400403int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400404 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400405
srs56942a9f5da2009-08-26 00:48:01 -0400406 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400407 // computation to be valid
408 oldCRC = header->headerCRC;
409 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400410 hSize = header->headerSize;
411
412 // If big-endian system, reverse byte order
413 if (IsLittleEndian() == 0) {
414 ReverseBytes(&oldCRC, 4);
415 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400416
417 // Initialize CRC functions...
418 chksum_crc32gentab();
419
420 // Compute CRC, restore original, and return result of comparison
421 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400422 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400423 return (oldCRC == newCRC);
424} // GPTData::CheckHeaderCRC()
425
srs56946699b012010-02-04 00:55:30 -0500426// Recompute all the CRCs. Must be called before saving if any changes have
427// been made. Must be called on platform-ordered data (this function reverses
428// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400429void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400430 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400431 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400432
433 // Initialize CRC functions...
434 chksum_crc32gentab();
435
srs56946699b012010-02-04 00:55:30 -0500436 // Save some key data from header before reversing byte order....
srs5694978041c2009-09-21 20:51:47 -0400437 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500438
439 if ((littleEndian = IsLittleEndian()) == 0) {
440 ReversePartitionBytes();
441 ReverseHeaderBytes(&mainHeader);
442 ReverseHeaderBytes(&secondHeader);
443 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400444
srs5694e7b4ff92009-08-18 13:16:10 -0400445 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400446 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400447 mainHeader.partitionEntriesCRC = crc;
448 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400449 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400450 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
451 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400452 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400453
454 // Zero out GPT tables' own CRCs (required for correct computation)
455 mainHeader.headerCRC = 0;
456 secondHeader.headerCRC = 0;
457
458 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400459 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400460 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400461 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400462 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400463 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400464 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400465 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400466 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500467
468 if ((littleEndian = IsLittleEndian()) == 0) {
469 ReverseHeaderBytes(&mainHeader);
470 ReverseHeaderBytes(&secondHeader);
471 ReversePartitionBytes();
472 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400473} // GPTData::RecomputeCRCs()
474
srs5694e7b4ff92009-08-18 13:16:10 -0400475// Rebuild the main GPT header, using the secondary header as a model.
476// Typically called when the main header has been found to be corrupt.
477void GPTData::RebuildMainHeader(void) {
478 int i;
479
480 mainHeader.signature = GPT_SIGNATURE;
481 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400482 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400483 mainHeader.headerCRC = UINT32_C(0);
484 mainHeader.reserved = secondHeader.reserved;
485 mainHeader.currentLBA = secondHeader.backupLBA;
486 mainHeader.backupLBA = secondHeader.currentLBA;
487 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
488 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500489 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400490 mainHeader.partitionEntriesLBA = UINT64_C(2);
491 mainHeader.numParts = secondHeader.numParts;
492 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
493 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
494 for (i = 0 ; i < GPT_RESERVED; i++)
495 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500496 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400497 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400498} // GPTData::RebuildMainHeader()
499
500// Rebuild the secondary GPT header, using the main header as a model.
501void GPTData::RebuildSecondHeader(void) {
502 int i;
503
504 secondHeader.signature = GPT_SIGNATURE;
505 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400506 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400507 secondHeader.headerCRC = UINT32_C(0);
508 secondHeader.reserved = mainHeader.reserved;
509 secondHeader.currentLBA = mainHeader.backupLBA;
510 secondHeader.backupLBA = mainHeader.currentLBA;
511 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
512 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500513 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400514 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
515 secondHeader.numParts = mainHeader.numParts;
516 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
517 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
518 for (i = 0 ; i < GPT_RESERVED; i++)
519 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500520 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400521 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400522} // GPTData::RebuildSecondHeader()
523
524// Search for hybrid MBR entries that have no corresponding GPT partition.
525// Returns number of such mismatches found
526int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500527 int i, found, numFound = 0;
528 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400529 uint64_t mbrFirst, mbrLast;
530
531 for (i = 0; i < 4; i++) {
532 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
533 j = 0;
534 found = 0;
535 do {
536 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
537 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
538 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
539 (partitions[j].GetLastLBA() == mbrLast))
540 found = 1;
541 j++;
srs56940283dae2010-04-28 16:44:34 -0400542 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400543 if (!found) {
544 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500545 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
546 << i + 1 << ", of type 0x";
547 cout.fill('0');
548 cout.setf(ios::uppercase);
549 cout.width(2);
550 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
551 << "has no corresponding GPT partition! You may continue, but this condition\n"
552 << "might cause data loss in the future!\a\n" << dec;
553 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400554 } // if
555 } // if
556 } // for
557 return numFound;
558} // GPTData::FindHybridMismatches
559
560// Find overlapping partitions and warn user about them. Returns number of
561// overlapping partitions.
562int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500563 int problems = 0;
564 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400565
srs56940283dae2010-04-28 16:44:34 -0400566 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400567 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500568 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400569 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500570 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
571 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
572 << " to " << partitions[i].GetLastLBA() << "\n";
573 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
574 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400575 } // if
576 } // for j...
577 } // for i...
578 return problems;
579} // GPTData::FindOverlaps()
580
srs569455d92612010-03-07 22:16:07 -0500581// Find partitions that are insane -- they start after they end or are too
582// big for the disk. (The latter should duplicate detection of overlaps
583// with GPT backup data structures, but better to err on the side of
584// redundant tests than to miss something....)
585int GPTData::FindInsanePartitions(void) {
586 uint32_t i;
587 int problems = 0;
588
srs56940283dae2010-04-28 16:44:34 -0400589 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500590 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
591 problems++;
srs56940283dae2010-04-28 16:44:34 -0400592 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500593 } // if
594 if (partitions[i].GetLastLBA() >= diskSize) {
595 problems++;
srs56940873e9d2010-10-07 13:00:45 -0400596 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500597 } // if
598 } // for
599 return problems;
600} // GPTData::FindInsanePartitions(void)
601
602
srs5694e4ac11e2009-08-31 10:13:04 -0400603/******************************************************************
604 * *
605 * Begin functions that load data from disk or save data to disk. *
606 * *
607 ******************************************************************/
608
srs569464cbd172011-03-01 22:03:54 -0500609// Change the filename associated with the GPT. Used for duplicating
610// the partition table to a new disk and saving backups.
611// Returns 1 on success, 0 on failure.
612int GPTData::SetFile(const string & deviceFilename) {
613 int err, allOK = 1;
614
615 device = deviceFilename;
616 if (allOK && myDisk.OpenForRead(deviceFilename)) {
617 // store disk information....
618 diskSize = myDisk.DiskSize(&err);
619 blockSize = (uint32_t) myDisk.GetBlockSize();
620 } // if
621 protectiveMBR.SetDisk(&myDisk);
622 protectiveMBR.SetDiskSize(diskSize);
623 protectiveMBR.SetBlockSize(blockSize);
624 return allOK;
625} // GPTData::SetFile()
626
srs5694e4ac11e2009-08-31 10:13:04 -0400627// Scan for partition data. This function loads the MBR data (regular MBR or
628// protective MBR) and loads BSD disklabel data (which is probably invalid).
629// It also looks for APM data, forces a load of GPT data, and summarizes
630// the results.
srs5694546a9c72010-01-26 16:00:26 -0500631void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400632 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400633
634 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500635 protectiveMBR.ReadMBRData(&myDisk);
636 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400637
638 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500639 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500640
641 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500642 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500643 protectiveMBR.ShowState();
644 bsdDisklabel.ShowState();
645 ShowAPMState(); // Show whether there's an Apple Partition Map present
646 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500647 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500648 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400649
650 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500651 cout << "\n*******************************************************************\n"
652 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500653 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500654 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500655 } // if
srs5694fed16d02010-01-27 23:03:40 -0500656 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400657 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400658} // GPTData::PartitionScan()
659
660// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500661int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500662 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500663 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500664 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400665
srs5694546a9c72010-01-26 16:00:26 -0500666 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500667 err = myDisk.OpenForWrite(deviceFilename);
668 if ((err == 0) && (!justLooking)) {
669 cout << "\aNOTE: Write test failed with error number " << errno
670 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
671#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
672 cout << "You may be able to enable writes by exiting this program, typing\n"
673 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
674 << "program.\n";
675#endif
676 cout << "\n";
677 } // if
678 myDisk.Close(); // Close and re-open read-only in case of bugs
679 } else allOK = 0; // if
680
681 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400682 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500683 diskSize = myDisk.DiskSize(&err);
684 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500685 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500686 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400687
srs5694ba00fed2010-01-12 18:18:36 -0500688 whichWasUsed = UseWhichPartitions();
689 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400690 case use_mbr:
691 XFormPartitions();
692 break;
693 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500694 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400695// bsdDisklabel.DisplayBSDData();
696 ClearGPTData();
697 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500698 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400699 break;
700 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500701 mbrState = protectiveMBR.GetValidity();
702 if ((mbrState == invalid) || (mbrState == mbr))
703 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400704 break;
705 case use_new:
706 ClearGPTData();
707 protectiveMBR.MakeProtectiveMBR();
708 break;
srs56943c0af382010-01-15 19:19:18 -0500709 case use_abort:
710 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400711 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500712 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400713 } // switch
714
srs569455d92612010-03-07 22:16:07 -0500715 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500716 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500717 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400718 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400719 } else {
720 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400721 } // if/else
722 return (allOK);
723} // GPTData::LoadPartitions()
724
725// Loads the GPT, as much as possible. Returns 1 if this seems to have
726// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500727int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500728 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400729
srs5694cb76c672010-02-11 22:22:22 -0500730 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400731
srs5694cb76c672010-02-11 22:22:22 -0500732 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
733 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
734 } else {
srs569408bb0da2010-02-19 17:19:55 -0500735 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
736 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500737 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
738 << "secondary header from the last sector of the disk! You should use 'v' to\n"
739 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
740 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500741 } // if/else
742 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400743 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400744
745 // Return valid headers code: 0 = both headers bad; 1 = main header
746 // good, backup bad; 2 = backup header good, main header bad;
747 // 3 = both headers good. Note these codes refer to valid GPT
748 // signatures and version numbers; more subtle problems will elude
749 // this check!
750 validHeaders = CheckHeaderValidity();
751
752 // Read partitions (from primary array)
753 if (validHeaders > 0) { // if at least one header is OK....
754 // GPT appears to be valid....
755 state = gpt_valid;
756
757 // We're calling the GPT valid, but there's a possibility that one
758 // of the two headers is corrupt. If so, use the one that seems to
759 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500760 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500761 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
762 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400763 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500764 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400765 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500766 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500767 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
768 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500769 RebuildMainHeader();
770 state = gpt_corrupt;
771 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400772 } // if/else/if
773
srs5694546a9c72010-01-26 16:00:26 -0500774 // Figure out which partition table to load....
775 // Load the main partition table, since either its header's CRC is OK or the
776 // backup header's CRC is not OK....
777 if (mainCrcOk || !secondCrcOk) {
778 if (LoadMainTable() == 0)
779 allOK = 0;
780 } else { // bad main header CRC and backup header CRC is OK
781 state = gpt_corrupt;
782 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500783 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500784 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500785 } else { // backup table bad, bad main header CRC, but try main table in desperation....
786 if (LoadMainTable() == 0) {
787 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500788 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500789 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500790 } // if
791 } // if/else (LoadSecondTableAsMain())
792 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400793
srs5694cb76c672010-02-11 22:22:22 -0500794 if (loadedTable == 1)
795 secondPartsCrcOk = CheckTable(&secondHeader);
796 else if (loadedTable == 2)
797 mainPartsCrcOk = CheckTable(&mainHeader);
798 else
799 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400800
srs5694546a9c72010-01-26 16:00:26 -0500801 // Problem with main partition table; if backup is OK, use it instead....
802 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
803 state = gpt_corrupt;
804 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500805 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500806 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
807 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500808 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500809
srs5694e4ac11e2009-08-31 10:13:04 -0400810 // Check for valid CRCs and warn if there are problems
811 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
812 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500813 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400814 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500815 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400816 } else {
817 state = gpt_invalid;
818 } // if/else
819 return allOK;
820} // GPTData::ForceLoadGPTData()
821
srs5694247657a2009-11-26 18:36:12 -0500822// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400823// main GPT header in memory MUST be valid for this call to do anything
824// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500825// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400826int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500827 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400828} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400829
830// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500831// table. Used in repair functions, and when starting up if the main
832// partition table is damaged.
833// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
834int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500835 return LoadPartitionTable(secondHeader, myDisk);
836} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400837
srs5694cb76c672010-02-11 22:22:22 -0500838// Load a single GPT header (main or backup) from the specified disk device and
839// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
840// value appropriately.
841// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
842// failure.
843int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
844 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500845 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500846
847 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500848 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500849 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
850 allOK = 0;
851 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500852 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500853
srs56941c6f8b02010-02-21 11:09:20 -0500854 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500855 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500856 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500857 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500858
srs56940283dae2010-04-28 16:44:34 -0400859 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500860 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500861 }
srs56941c6f8b02010-02-21 11:09:20 -0500862
863 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500864 return allOK;
865} // GPTData::LoadHeader
866
867// Load a partition table (either main or secondary) from the specified disk,
868// using header as a reference for what to load. If sector != 0 (the default
869// is 0), loads from the specified sector; otherwise loads from the sector
870// indicated in header.
871// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
872int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
873 uint32_t sizeOfParts, newCRC;
874 int retval;
875
876 if (disk.OpenForRead()) {
877 if (sector == 0) {
878 retval = disk.Seek(header.partitionEntriesLBA);
879 } else {
880 retval = disk.Seek(sector);
881 } // if/else
srs569455d92612010-03-07 22:16:07 -0500882 if (retval == 1)
883 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500884 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500885 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
886 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500887 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500888 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500889 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400890 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500891 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400892 if (IsLittleEndian() == 0)
893 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500894 if (!mainPartsCrcOk) {
895 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400896 } // if
897 } else {
srs5694cb76c672010-02-11 22:22:22 -0500898 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400899 } // if/else
900 } else {
srs5694fed16d02010-01-27 23:03:40 -0500901 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500902 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500903 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400904 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500905 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500906} // GPTData::LoadPartitionsTable()
907
908// Check the partition table pointed to by header, but don't keep it
909// around.
910// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
911int GPTData::CheckTable(struct GPTHeader *header) {
912 uint32_t sizeOfParts, newCRC;
913 uint8_t *storage;
914 int newCrcOk = 0;
915
srs56940283dae2010-04-28 16:44:34 -0400916 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500917 // its CRC and store the results, then discard this temporary
918 // storage, since we don't use it in any but recovery operations
919 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400920 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500921 storage = new uint8_t[sizeOfParts];
922 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400923 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500924 } else {
925 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
926 newCrcOk = (newCRC == header->partitionEntriesCRC);
927 } // if/else
928 delete[] storage;
929 } // if
930 return newCrcOk;
931} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400932
srs569464cbd172011-03-01 22:03:54 -0500933// Writes GPT (and protective MBR) to disk. If quiet==1,
934// Returns 1 on successful
srs5694e7b4ff92009-08-18 13:16:10 -0400935// write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500936int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500937 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500938 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400939
srs56946699b012010-02-04 00:55:30 -0500940 littleEndian = IsLittleEndian();
941
srs5694e7b4ff92009-08-18 13:16:10 -0400942 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500943
944 // This test should only fail on read-only disks....
945 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500946 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500947 allOK = 0;
948 } // if
949
srs569464cbd172011-03-01 22:03:54 -0500950 // Check that disk is really big enough to handle the second header...
951 if (mainHeader.backupLBA >= diskSize) {
952 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
953 << "header, but other problems may occur!\n";
954 MoveSecondHeaderToEnd();
955 } // if
956
srs5694e7b4ff92009-08-18 13:16:10 -0400957 // Is there enough space to hold the GPT headers and partition tables,
958 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400959 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400960 allOK = 0;
961 } // if
962
srs5694247657a2009-11-26 18:36:12 -0500963 // Check that second header is properly placed. Warn and ask if this should
964 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -0500965 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
966 if (quiet == 0) {
967 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
968 << "correct this problem? ";
969 if (GetYN() == 'Y') {
970 MoveSecondHeaderToEnd();
971 cout << "Have moved second header and partition table to correct location.\n";
972 } else {
973 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
974 } // if correction requested
975 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -0500976 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -0500977 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -0500978 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400979
srs569455d92612010-03-07 22:16:07 -0500980 // Check for overlapping or insane partitions....
981 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400982 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500983 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400984 } // if
985
986 // Check for mismatched MBR and GPT data, but let it pass if found
987 // (function displays warning message)
988 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400989
990 RecomputeCRCs();
991
srs5694ba00fed2010-01-12 18:18:36 -0500992 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500993 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
994 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500995 answer = GetYN();
996 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500997 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400998 } else {
999 allOK = 0;
1000 } // if/else
1001 } // if
1002
1003 // Do it!
1004 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001005 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001006 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001007 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1008 if (!allOK)
1009 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1010 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001011
1012 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001013 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1014
1015 // Now write the main partition tables...
1016 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1017
1018 // Now write the main GPT header...
1019 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1020
1021 // To top it off, write the protective MBR...
1022 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001023
1024 // re-read the partition table
1025 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001026 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001027 } // if
1028
1029 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001030 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001031 } else {
srs5694fed16d02010-01-27 23:03:40 -05001032 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001033 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001034 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001035
srs5694546a9c72010-01-26 16:00:26 -05001036 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001037 } else {
srs569464cbd172011-03-01 22:03:54 -05001038 cerr << "Unable to open device " << myDisk.GetName() << " for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001039 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001040 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001041 } // if/else
1042 } else {
srs5694fed16d02010-01-27 23:03:40 -05001043 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001044 } // if
1045
1046 return (allOK);
1047} // GPTData::SaveGPTData()
1048
1049// Save GPT data to a backup file. This function does much less error
1050// checking than SaveGPTData(). It can therefore preserve many types of
1051// corruption for later analysis; however, it preserves only the MBR,
1052// the main GPT header, the backup GPT header, and the main partition
1053// table; it discards the backup partition table, since it should be
1054// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001055int GPTData::SaveGPTBackup(const string & filename) {
1056 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001057 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001058
srs5694546a9c72010-01-26 16:00:26 -05001059 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001060 // Recomputing the CRCs is likely to alter them, which could be bad
1061 // if the intent is to save a potentially bad GPT for later analysis;
1062 // but if we don't do this, we get bogus errors when we load the
1063 // backup. I'm favoring misses over false alarms....
1064 RecomputeCRCs();
1065
srs5694546a9c72010-01-26 16:00:26 -05001066 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -04001067
srs5694cb76c672010-02-11 22:22:22 -05001068 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001069 // MBR write closed disk, so re-open and seek to end....
1070 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001071 allOK = SaveHeader(&mainHeader, backupFile, 1);
1072 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001073
srs5694e7b4ff92009-08-18 13:16:10 -04001074 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001075 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001076
srs5694cb76c672010-02-11 22:22:22 -05001077 if (allOK)
1078 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001079
1080 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001081 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001082 } else {
srs5694fed16d02010-01-27 23:03:40 -05001083 cerr << "Warning! An error was reported when writing the backup file.\n"
1084 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001085 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001086 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001087 } else {
srs5694fed16d02010-01-27 23:03:40 -05001088 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001089 allOK = 0;
1090 } // if/else
1091 return allOK;
1092} // GPTData::SaveGPTBackup()
1093
srs5694cb76c672010-02-11 22:22:22 -05001094// Write a GPT header (main or backup) to the specified sector. Used by both
1095// the SaveGPTData() and SaveGPTBackup() functions.
1096// Should be passed an architecture-appropriate header (DO NOT call
1097// ReverseHeaderBytes() on the header before calling this function)
1098// Returns 1 on success, 0 on failure
1099int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1100 int littleEndian, allOK = 1;
1101
1102 littleEndian = IsLittleEndian();
1103 if (!littleEndian)
1104 ReverseHeaderBytes(header);
1105 if (disk.Seek(sector)) {
1106 if (disk.Write(header, 512) == -1)
1107 allOK = 0;
1108 } else allOK = 0; // if (disk.Seek()...)
1109 if (!littleEndian)
1110 ReverseHeaderBytes(header);
1111 return allOK;
1112} // GPTData::SaveHeader()
1113
1114// Save the partitions to the specified sector. Used by both the SaveGPTData()
1115// and SaveGPTBackup() functions.
1116// Should be passed an architecture-appropriate header (DO NOT call
1117// ReverseHeaderBytes() on the header before calling this function)
1118// Returns 1 on success, 0 on failure
1119int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1120 int littleEndian, allOK = 1;
1121
1122 littleEndian = IsLittleEndian();
1123 if (disk.Seek(sector)) {
1124 if (!littleEndian)
1125 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001126 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001127 allOK = 0;
1128 if (!littleEndian)
1129 ReversePartitionBytes();
1130 } else allOK = 0; // if (myDisk.Seek()...)
1131 return allOK;
1132} // GPTData::SavePartitionTable()
1133
srs5694e7b4ff92009-08-18 13:16:10 -04001134// Load GPT data from a backup file created by SaveGPTBackup(). This function
1135// does minimal error checking. It returns 1 if it completed successfully,
1136// 0 if there was a problem. In the latter case, it creates a new empty
1137// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001138int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001139 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001140 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001141 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001142 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001143
srs5694546a9c72010-01-26 16:00:26 -05001144 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001145 if (IsLittleEndian() == 0)
1146 littleEndian = 0;
1147
srs5694e7b4ff92009-08-18 13:16:10 -04001148 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001149 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001150
srs5694cb76c672010-02-11 22:22:22 -05001151 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001152
srs5694cb76c672010-02-11 22:22:22 -05001153 // Check backup file size and rebuild second header if file is right
1154 // size to be direct dd copy of MBR, main header, and main partition
1155 // table; if other size, treat it like a GPT fdisk-generated backup
1156 // file
1157 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1158 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1159 if (shortBackup) {
1160 RebuildSecondHeader();
1161 secondCrcOk = mainCrcOk;
1162 } else {
1163 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1164 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001165
srs5694e7b4ff92009-08-18 13:16:10 -04001166 // Return valid headers code: 0 = both headers bad; 1 = main header
1167 // good, backup bad; 2 = backup header good, main header bad;
1168 // 3 = both headers good. Note these codes refer to valid GPT
1169 // signatures and version numbers; more subtle problems will elude
1170 // this check!
1171 if ((val = CheckHeaderValidity()) > 0) {
1172 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001173 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001174 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001175 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001176 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001177 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1178 } // if/else
1179
srs5694e7b4ff92009-08-18 13:16:10 -04001180 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001181 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1182 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001183 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001184 } // if
1185
srs5694cb76c672010-02-11 22:22:22 -05001186 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1187 cerr << "Warning! Read error " << errno
1188 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001189 } else {
1190 allOK = 0;
1191 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001192 // Something went badly wrong, so blank out partitions
1193 if (allOK == 0) {
1194 cerr << "Improper backup file! Clearing all partition data!\n";
1195 ClearGPTData();
1196 protectiveMBR.MakeProtectiveMBR();
1197 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001198 } else {
1199 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001200 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001201 } // if/else
1202
srs5694e7b4ff92009-08-18 13:16:10 -04001203 return allOK;
1204} // GPTData::LoadGPTBackup()
1205
srs569408bb0da2010-02-19 17:19:55 -05001206int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001207 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001208} // GPTData::SaveMBR()
1209
1210// This function destroys the on-disk GPT structures, but NOT the on-disk
1211// MBR.
1212// Returns 1 if the operation succeeds, 0 if not.
1213int GPTData::DestroyGPT(void) {
1214 int i, sum, tableSize, allOK = 1;
1215 uint8_t blankSector[512];
1216 uint8_t* emptyTable;
1217
1218 for (i = 0; i < 512; i++) {
1219 blankSector[i] = 0;
1220 } // for
1221
1222 if (myDisk.OpenForWrite()) {
1223 if (!myDisk.Seek(mainHeader.currentLBA))
1224 allOK = 0;
1225 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1226 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1227 allOK = 0;
1228 } // if
1229 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1230 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001231 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001232 emptyTable = new uint8_t[tableSize];
1233 for (i = 0; i < tableSize; i++)
1234 emptyTable[i] = 0;
1235 if (allOK) {
1236 sum = myDisk.Write(emptyTable, tableSize);
1237 if (sum != tableSize) {
1238 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1239 allOK = 0;
1240 } // if write failed
1241 } // if
1242 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1243 allOK = 0;
1244 if (allOK) {
1245 sum = myDisk.Write(emptyTable, tableSize);
1246 if (sum != tableSize) {
1247 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1248 << errno << "\n";
1249 allOK = 0;
1250 } // if wrong size written
1251 } // if
1252 if (!myDisk.Seek(secondHeader.currentLBA))
1253 allOK = 0;
1254 if (allOK) {
1255 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1256 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1257 allOK = 0;
1258 } // if
1259 } // if
1260 myDisk.DiskSync();
1261 myDisk.Close();
1262 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1263 << "other utilities.\n";
1264 delete[] emptyTable;
1265 } else {
1266 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1267 } // if/else (fd != -1)
1268 return (allOK);
1269} // GPTDataTextUI::DestroyGPT()
1270
1271// Wipe MBR data from the disk (zero it out completely)
1272// Returns 1 on success, 0 on failure.
1273int GPTData::DestroyMBR(void) {
1274 int allOK = 1, i;
1275 uint8_t blankSector[512];
1276
1277 for (i = 0; i < 512; i++)
1278 blankSector[i] = 0;
1279
1280 if (myDisk.OpenForWrite()) {
1281 if (myDisk.Seek(0)) {
1282 if (myDisk.Write(blankSector, 512) != 512)
1283 allOK = 0;
1284 } else allOK = 0;
1285 } else allOK = 0;
1286 if (!allOK)
1287 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1288 return allOK;
1289} // GPTData::DestroyMBR(void)
1290
srs5694e4ac11e2009-08-31 10:13:04 -04001291// Tell user whether Apple Partition Map (APM) was discovered....
1292void GPTData::ShowAPMState(void) {
1293 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001294 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001295 else
srs5694fed16d02010-01-27 23:03:40 -05001296 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001297} // GPTData::ShowAPMState()
1298
1299// Tell user about the state of the GPT data....
1300void GPTData::ShowGPTState(void) {
1301 switch (state) {
1302 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001303 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001304 break;
1305 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001306 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001307 break;
1308 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001309 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001310 break;
1311 default:
srs5694fed16d02010-01-27 23:03:40 -05001312 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001313 break;
1314 } // switch
1315} // GPTData::ShowGPTState()
1316
1317// Display the basic GPT data
1318void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001319 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001320 uint64_t temp, totalFree;
1321
srs5694fed16d02010-01-27 23:03:40 -05001322 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs56940873e9d2010-10-07 13:00:45 -04001323 << BytesToSI(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001324 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001325 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001326 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001327 cout << "First usable sector is " << mainHeader.firstUsableLBA
1328 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001329 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001330 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001331 cout << "Total free space is " << totalFree << " sectors ("
srs56940873e9d2010-10-07 13:00:45 -04001332 << BytesToSI(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001333 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001334 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001335 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001336 } // for
1337} // GPTData::DisplayGPTData()
1338
srs5694e4ac11e2009-08-31 10:13:04 -04001339// Show detailed information on the specified partition
1340void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001341 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001342 partitions[partNum].ShowDetails(blockSize);
1343 } else {
srs5694fed16d02010-01-27 23:03:40 -05001344 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001345 } // if
1346} // GPTData::ShowPartDetails()
1347
srs5694e4ac11e2009-08-31 10:13:04 -04001348/**************************************************************************
1349 * *
1350 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1351 * (some of these functions may require user interaction) *
1352 * *
1353 **************************************************************************/
1354
srs569408bb0da2010-02-19 17:19:55 -05001355// Examines the MBR & GPT data to determine which set of data to use: the
1356// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1357// a new set of partitions (use_new). A return value of use_abort indicates
1358// that this function couldn't determine what to do. Overriding functions
1359// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001360WhichToUse GPTData::UseWhichPartitions(void) {
1361 WhichToUse which = use_new;
1362 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001363
1364 mbrState = protectiveMBR.GetValidity();
1365
1366 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001367 cout << "\n***************************************************************\n"
1368 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001369 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001370 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001371 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001372 } // if
srs5694fed16d02010-01-27 23:03:40 -05001373 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001374 which = use_mbr;
1375 } // if
1376
1377 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001378 cout << "\n**********************************************************************\n"
1379 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1380 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001381 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001382 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001383 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1384 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001385 } // if
srs5694fed16d02010-01-27 23:03:40 -05001386 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001387 which = use_bsd;
1388 } // if
1389
1390 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001391 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001392 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001393 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001394 } // if
1395 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001396 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001397 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001398 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001399 } // if
1400 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001401 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001402 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001403 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001404 } // if
1405 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001406 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001407 } // if
1408
srs5694e4ac11e2009-08-31 10:13:04 -04001409 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001410 if (mbrState == gpt) {
1411 cout << "\a\a****************************************************************************\n"
1412 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1413 << "verification and recovery are STRONGLY recommended.\n"
1414 << "****************************************************************************\n";
1415 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001416 } else {
srs569408bb0da2010-02-19 17:19:55 -05001417 which = use_abort;
1418 } // if/else MBR says disk is GPT
1419 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001420
1421 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001422 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001423
1424 return which;
1425} // UseWhichPartitions()
1426
srs569408bb0da2010-02-19 17:19:55 -05001427// Convert MBR partition table into GPT form.
1428void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001429 int i, numToConvert;
1430 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001431
1432 // Clear out old data & prepare basics....
1433 ClearGPTData();
1434
1435 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001436 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001437 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001438 else
srs56940283dae2010-04-28 16:44:34 -04001439 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001440
1441 for (i = 0; i < numToConvert; i++) {
1442 origType = protectiveMBR.GetType(i);
1443 // don't waste CPU time trying to convert extended, hybrid protective, or
1444 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001445 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001446 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001447 partitions[i] = protectiveMBR.AsGPT(i);
1448 } // for
1449
1450 // Convert MBR into protective MBR
1451 protectiveMBR.MakeProtectiveMBR();
1452
1453 // Record that all original CRCs were OK so as not to raise flags
1454 // when doing a disk verification
1455 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001456} // GPTData::XFormPartitions()
1457
1458// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001459// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001460// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001461int GPTData::XFormDisklabel(uint32_t partNum) {
1462 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001463 int goOn = 1, numDone = 0;
1464 BSDData disklabel;
1465
srs569408bb0da2010-02-19 17:19:55 -05001466 if (GetPartRange(&low, &high) == 0) {
1467 goOn = 0;
1468 cout << "No partitions!\n";
1469 } // if
1470 if (partNum > high) {
1471 goOn = 0;
1472 cout << "Specified partition is invalid!\n";
1473 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001474
srs569408bb0da2010-02-19 17:19:55 -05001475 // If all is OK, read the disklabel and convert it.
1476 if (goOn) {
1477 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1478 partitions[partNum].GetLastLBA());
1479 if ((goOn) && (disklabel.IsDisklabel())) {
1480 numDone = XFormDisklabel(&disklabel);
1481 if (numDone == 1)
1482 cout << "Converted 1 BSD partition.\n";
1483 else
1484 cout << "Converted " << numDone << " BSD partitions.\n";
1485 } else {
1486 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1487 } // if/else
1488 } // if
1489 if (numDone > 0) { // converted partitions; delete carrier
1490 partitions[partNum].BlankPartition();
1491 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001492 return numDone;
srs569455d92612010-03-07 22:16:07 -05001493} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001494
1495// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001496int GPTData::XFormDisklabel(BSDData* disklabel) {
1497 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001498
srs569408bb0da2010-02-19 17:19:55 -05001499 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001500 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001501 partNum = FindFirstFreePart();
1502 if (partNum >= 0) {
1503 partitions[partNum] = disklabel->AsGPT(i);
1504 if (partitions[partNum].IsUsed())
1505 numDone++;
1506 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001507 } // for
srs569408bb0da2010-02-19 17:19:55 -05001508 if (partNum == -1)
1509 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001510 } // if
1511
1512 // Record that all original CRCs were OK so as not to raise flags
1513 // when doing a disk verification
1514 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1515
1516 return numDone;
1517} // GPTData::XFormDisklabel(BSDData* disklabel)
1518
srs569408bb0da2010-02-19 17:19:55 -05001519// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1520// partition has the active/bootable flag UNset and uses the GPT fdisk
1521// type code divided by 0x0100 as the MBR type code.
1522// Returns 1 if operation was 100% successful, 0 if there were ANY
1523// problems.
srs5694978041c2009-09-21 20:51:47 -04001524int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001525 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001526
srs5694978041c2009-09-21 20:51:47 -04001527 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001528 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001529 allOK = 0;
1530 } // if
srs56940283dae2010-04-28 16:44:34 -04001531 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001532 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001533 allOK = 0;
1534 } // if
1535 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001536 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001537 allOK = 0;
1538 } // if
1539 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1540 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1541 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001542 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1543 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001544 } // if
srs5694978041c2009-09-21 20:51:47 -04001545 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001546 (uint32_t) partitions[gptPart].GetLengthLBA(),
1547 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001548 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001549 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1550 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1551 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001552 allOK = 0;
1553 } // if/else
1554 return allOK;
1555} // GPTData::OnePartToMBR()
1556
srs569455d92612010-03-07 22:16:07 -05001557// Convert partitions to MBR form (primary and logical) and return
1558// the number done. Partitions are specified in a PartNotes variable,
1559// which includes pointers to GPT partition numbers. A partition number
1560// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1561// location in the table, and MBR_EMPTY means not to create a partition
1562// in that table position. If the partition type entry for a partition
1563// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001564// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001565// protective partitions or extended partitions.
srs5694058d4a52010-10-12 12:42:47 -04001566int GPTData::PartsToMBR(PartNotes * notes) {
srs569455d92612010-03-07 22:16:07 -05001567 int mbrNum = 0, numConverted = 0;
1568 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001569
srs56949ddc14b2010-08-22 22:44:42 -04001570 protectiveMBR.EmptyMBR(0);
srs569455d92612010-03-07 22:16:07 -05001571 protectiveMBR.SetDiskSize(diskSize);
srs5694058d4a52010-10-12 12:42:47 -04001572 if (!notes->IsLegal())
1573 notes->MakeItLegal();
1574 notes->Rewind();
1575 while (notes->GetNextInfo(&convInfo) >= 0) {
srs569464cbd172011-03-01 22:03:54 -05001576 if ((convInfo.origPartNum >= 0) && (convInfo.type == PRIMARY)) {
1577 numConverted += OnePartToMBR((uint32_t) convInfo.origPartNum, mbrNum);
srs569455d92612010-03-07 22:16:07 -05001578 if (convInfo.hexCode != 0)
1579 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1580 if (convInfo.active)
1581 protectiveMBR.SetPartBootable(mbrNum);
1582 mbrNum++;
1583 } // if
srs569464cbd172011-03-01 22:03:54 -05001584 if (convInfo.origPartNum == MBR_EFI_GPT)
srs569461768bc2010-07-04 01:54:00 -04001585 mbrNum++;
1586 } // for
1587 // Now go through and set sizes for MBR_EFI_GPT partitions....
srs5694058d4a52010-10-12 12:42:47 -04001588 notes->Rewind();
srs569461768bc2010-07-04 01:54:00 -04001589 mbrNum = 0;
srs5694058d4a52010-10-12 12:42:47 -04001590 while (notes->GetNextInfo(&convInfo) >= 0) {
srs569464cbd172011-03-01 22:03:54 -05001591 if ((convInfo.origPartNum >= 0) && (convInfo.type == PRIMARY))
srs569461768bc2010-07-04 01:54:00 -04001592 mbrNum++;
srs569464cbd172011-03-01 22:03:54 -05001593 if (convInfo.origPartNum == MBR_EFI_GPT) {
srs569455d92612010-03-07 22:16:07 -05001594 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1595 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1596 protectiveMBR.SetHybrid();
1597 } else {
1598 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1599 } // if/else
1600 mbrNum++;
srs569461768bc2010-07-04 01:54:00 -04001601 } // if
1602 } // while
srs569455d92612010-03-07 22:16:07 -05001603 // Now do logical partition(s)...
1604 protectiveMBR.SetDisk(&myDisk);
1605 numConverted += protectiveMBR.CreateLogicals(notes);
srs569408bb0da2010-02-19 17:19:55 -05001606 return numConverted;
1607} // GPTData::PartsToMBR()
1608
srs5694e4ac11e2009-08-31 10:13:04 -04001609
1610/**********************************************************************
1611 * *
1612 * Functions that adjust GPT data structures WITHOUT user interaction *
1613 * (they may display information for the user's benefit, though) *
1614 * *
1615 **********************************************************************/
1616
1617// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001618// necessary, copies data if it already exists. Returns 1 if all goes
1619// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001620int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001621 GPTPart* newParts;
1622 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001623 uint32_t i, high, copyNum;
1624 int allOK = 1;
1625
1626 // First, adjust numEntries upward, if necessary, to get a number
1627 // that fills the allocated sectors
1628 i = blockSize / GPT_SIZE;
1629 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001630 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001631 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001632 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001633 } // if
1634
srs5694247657a2009-11-26 18:36:12 -05001635 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001636 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001637 // partition table, which causes problems when loading data from a RAID
1638 // array that's been expanded because this function is called when loading
1639 // data.
srs56940283dae2010-04-28 16:44:34 -04001640 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001641 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001642 if (newParts != NULL) {
1643 if (partitions != NULL) { // existing partitions; copy them over
1644 GetPartRange(&i, &high);
1645 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001646 cout << "The highest-numbered partition is " << high + 1
1647 << ", which is greater than the requested\n"
1648 << "partition table size of " << numEntries
1649 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001650 allOK = 0;
1651 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001652 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001653 copyNum = numEntries;
1654 else
srs56940283dae2010-04-28 16:44:34 -04001655 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001656 for (i = 0; i < copyNum; i++) {
1657 newParts[i] = partitions[i];
1658 } // for
1659 trash = partitions;
1660 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001661 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001662 } // if
1663 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001664 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001665 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001666 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001667 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1668 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1669 MoveSecondHeaderToEnd();
1670 if (diskSize > 0)
1671 CheckGPTSize();
1672 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001673 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001674 allOK = 0;
1675 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001676 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001677 mainHeader.numParts = numParts;
1678 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001679 return (allOK);
1680} // GPTData::SetGPTSize()
1681
1682// Blank the partition array
1683void GPTData::BlankPartitions(void) {
1684 uint32_t i;
1685
srs56940283dae2010-04-28 16:44:34 -04001686 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001687 partitions[i].BlankPartition();
1688 } // for
1689} // GPTData::BlankPartitions()
1690
srs5694ba00fed2010-01-12 18:18:36 -05001691// Delete a partition by number. Returns 1 if successful,
1692// 0 if there was a problem. Returns 1 if partition was in
1693// range, 0 if it was out of range.
1694int GPTData::DeletePartition(uint32_t partNum) {
1695 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001696 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001697
srs56940283dae2010-04-28 16:44:34 -04001698 numUsedParts = GetPartRange(&low, &high);
1699 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001700 // In case there's a protective MBR, look for & delete matching
1701 // MBR partition....
1702 startSector = partitions[partNum].GetFirstLBA();
1703 length = partitions[partNum].GetLengthLBA();
1704 protectiveMBR.DeleteByLocation(startSector, length);
1705
1706 // Now delete the GPT partition
1707 partitions[partNum].BlankPartition();
1708 } else {
srs5694fed16d02010-01-27 23:03:40 -05001709 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001710 retval = 0;
1711 } // if/else
1712 return retval;
1713} // GPTData::DeletePartition(uint32_t partNum)
1714
srs569408bb0da2010-02-19 17:19:55 -05001715// Non-interactively create a partition.
1716// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001717uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001718 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001719 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001720
1721 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001722 if (Align(&startSector)) {
1723 cout << "Information: Moved requested sector from " << origSector << " to "
1724 << startSector << " in\norder to align on " << sectorAlignment
1725 << "-sector boundaries.\n";
1726 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001727 if (IsFree(startSector) && (startSector <= endSector)) {
1728 if (FindLastInFree(startSector) >= endSector) {
1729 partitions[partNum].SetFirstLBA(startSector);
1730 partitions[partNum].SetLastLBA(endSector);
1731 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001732 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001733 } else retval = 0; // if free space until endSector
1734 } else retval = 0; // if startSector is free
1735 } else retval = 0; // if legal partition number
1736 return retval;
1737} // GPTData::CreatePartition(partNum, startSector, endSector)
1738
srs5694e4ac11e2009-08-31 10:13:04 -04001739// Sort the GPT entries, eliminating gaps and making for a logical
1740// ordering. Relies on QuickSortGPT() for the bulk of the work
1741void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001742 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001743
1744 // First, find the last partition with data, so as not to
1745 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001746 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001747
1748 // Now swap empties with the last partitions, to simplify the logic
1749 // in the Quicksort function....
1750 i = 0;
1751 while (i < lastPart) {
1752 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001753 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001754 do {
1755 lastPart--;
1756 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001757 } // if
1758 i++;
1759 } // while
1760
srs5694546a9c72010-01-26 16:00:26 -05001761 // If there are more empties than partitions in the range from 0 to lastPart,
1762 // the above leaves lastPart set too high, so we've got to adjust it to
1763 // prevent empties from migrating to the top of the list....
1764 GetPartRange(&firstPart, &lastPart);
1765
srs5694e4ac11e2009-08-31 10:13:04 -04001766 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001767 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001768} // GPTData::SortGPT()
1769
srs569408bb0da2010-02-19 17:19:55 -05001770// Recursive quick sort algorithm for GPT partitions. Note that if there
1771// are any empties in the specified range, they'll be sorted to the
1772// start, resulting in a sorted set of partitions that begins with
1773// partition 2, 3, or higher.
1774void GPTData::QuickSortGPT(int start, int finish) {
1775 uint64_t starterValue; // starting location of median partition
1776 int left, right;
1777
1778 left = start;
1779 right = finish;
1780 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1781 do {
1782 while (partitions[left].GetFirstLBA() < starterValue)
1783 left++;
1784 while (partitions[right].GetFirstLBA() > starterValue)
1785 right--;
1786 if (left <= right)
1787 SwapPartitions(left++, right--);
1788 } while (left <= right);
1789 if (start < right) QuickSortGPT(start, right);
1790 if (finish > left) QuickSortGPT(left, finish);
1791} // GPTData::QuickSortGPT()
1792
1793// Swap the contents of two partitions.
1794// Returns 1 if successful, 0 if either partition is out of range
1795// (that is, not a legal number; either or both can be empty).
1796// Note that if partNum1 = partNum2 and this number is in range,
1797// it will be considered successful.
1798int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1799 GPTPart temp;
1800 int allOK = 1;
1801
srs56940283dae2010-04-28 16:44:34 -04001802 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001803 if (partNum1 != partNum2) {
1804 temp = partitions[partNum1];
1805 partitions[partNum1] = partitions[partNum2];
1806 partitions[partNum2] = temp;
1807 } // if
1808 } else allOK = 0; // partition numbers are valid
1809 return allOK;
1810} // GPTData::SwapPartitions()
1811
srs5694e4ac11e2009-08-31 10:13:04 -04001812// Set up data structures for entirely new set of partitions on the
1813// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001814// Note that this function does NOT clear the protectiveMBR data
1815// structure, since it may hold the original MBR partitions if the
1816// program was launched on an MBR disk, and those may need to be
1817// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001818int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001819 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001820
1821 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001822 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001823 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001824 partitions = NULL;
1825 SetGPTSize(NUM_GPT_ENTRIES);
1826
1827 // Now initialize a bunch of stuff that's static....
1828 mainHeader.signature = GPT_SIGNATURE;
1829 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001830 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001831 mainHeader.reserved = 0;
1832 mainHeader.currentLBA = UINT64_C(1);
1833 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1834 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1835 for (i = 0; i < GPT_RESERVED; i++) {
1836 mainHeader.reserved2[i] = '\0';
1837 } // for
srs56940873e9d2010-10-07 13:00:45 -04001838 if (blockSize > 0)
1839 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1840 else
1841 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001842
1843 // Now some semi-static items (computed based on end of disk)
1844 mainHeader.backupLBA = diskSize - UINT64_C(1);
1845 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1846
1847 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001848 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001849
1850 // Copy main header to backup header
1851 RebuildSecondHeader();
1852
1853 // Blank out the partitions array....
1854 BlankPartitions();
1855
1856 // Flag all CRCs as being OK....
1857 mainCrcOk = 1;
1858 secondCrcOk = 1;
1859 mainPartsCrcOk = 1;
1860 secondPartsCrcOk = 1;
1861
1862 return (goOn);
1863} // GPTData::ClearGPTData()
1864
srs5694247657a2009-11-26 18:36:12 -05001865// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001866// If the disk size has actually changed, this also adjusts the protective
1867// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001868// Used internally and called by the 'e' option on the recovery &
1869// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001870// to their arrays or to adjust data structures in restore operations
1871// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001872void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001873 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001874 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1875 if (protectiveMBR.GetValidity() == hybrid) {
1876 protectiveMBR.OptimizeEESize();
1877 RecomputeCHS();
1878 } // if
1879 if (protectiveMBR.GetValidity() == gpt)
1880 MakeProtectiveMBR();
1881 } // if
srs56948bb78762009-11-24 15:43:49 -05001882 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1883 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1884} // GPTData::FixSecondHeaderLocation()
1885
srs56940a697312010-01-28 21:10:52 -05001886int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001887 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001888
1889 if (!IsFreePartNum(partNum)) {
1890 partitions[partNum].SetName(theName);
1891 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001892
1893 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001894} // GPTData::SetName
1895
1896// Set the disk GUID to the specified value. Note that the header CRCs must
1897// be recomputed after calling this function.
1898void GPTData::SetDiskGUID(GUIDData newGUID) {
1899 mainHeader.diskGUID = newGUID;
1900 secondHeader.diskGUID = newGUID;
1901} // SetDiskGUID()
1902
1903// Set the unique GUID of the specified partition. Returns 1 on
1904// successful completion, 0 if there were problems (invalid
1905// partition number).
1906int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1907 int retval = 0;
1908
srs56940283dae2010-04-28 16:44:34 -04001909 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001910 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1911 partitions[pn].SetUniqueGUID(theGUID);
1912 retval = 1;
1913 } // if
1914 } // if
1915 return retval;
1916} // GPTData::SetPartitionGUID()
1917
srs56949ba54212010-05-18 23:24:02 -04001918// Set new random GUIDs for the disk and all partitions. Intended to be used
1919// after disk cloning or similar operations that don't randomize the GUIDs.
1920void GPTData::RandomizeGUIDs(void) {
1921 uint32_t i;
1922
1923 mainHeader.diskGUID.Randomize();
1924 secondHeader.diskGUID = mainHeader.diskGUID;
1925 for (i = 0; i < numParts; i++)
1926 if (partitions[i].IsUsed())
1927 partitions[i].RandomizeUniqueGUID();
1928} // GPTData::RandomizeGUIDs()
1929
srs5694ba00fed2010-01-12 18:18:36 -05001930// Change partition type code non-interactively. Returns 1 if
1931// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001932int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1933 int retval = 1;
1934
1935 if (!IsFreePartNum(partNum)) {
1936 partitions[partNum].SetType(theGUID);
1937 } else retval = 0;
1938 return retval;
1939} // GPTData::ChangePartType()
1940
srs56949ba54212010-05-18 23:24:02 -04001941// Recompute the CHS values of all the MBR partitions. Used to reset
1942// CHS values that some BIOSes require, despite the fact that the
1943// resulting CHS values violate the GPT standard.
1944void GPTData::RecomputeCHS(void) {
1945 int i;
1946
1947 for (i = 0; i < 4; i++)
1948 protectiveMBR.RecomputeCHS(i);
1949} // GPTData::RecomputeCHS()
1950
srs56941d1448a2009-12-31 21:20:19 -05001951// Adjust sector number so that it falls on a sector boundary that's a
1952// multiple of sectorAlignment. This is done to improve the performance
1953// of Western Digital Advanced Format disks and disks with similar
1954// technology from other companies, which use 4096-byte sectors
1955// internally although they translate to 512-byte sectors for the
1956// benefit of the OS. If partitions aren't properly aligned on these
1957// disks, some filesystem data structures can span multiple physical
1958// sectors, degrading performance. This function should be called
1959// only on the FIRST sector of the partition, not the last!
1960// This function returns 1 if the alignment was altered, 0 if it
1961// was unchanged.
1962int GPTData::Align(uint64_t* sector) {
1963 int retval = 0, sectorOK = 0;
1964 uint64_t earlier, later, testSector, original;
1965
1966 if ((*sector % sectorAlignment) != 0) {
1967 original = *sector;
srs56941d1448a2009-12-31 21:20:19 -05001968 earlier = (*sector / sectorAlignment) * sectorAlignment;
1969 later = earlier + (uint64_t) sectorAlignment;
1970
1971 // Check to see that every sector between the earlier one and the
1972 // requested one is clear, and that it's not too early....
1973 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001974 sectorOK = 1;
1975 testSector = earlier;
1976 do {
1977 sectorOK = IsFree(testSector++);
1978 } while ((sectorOK == 1) && (testSector < *sector));
1979 if (sectorOK == 1) {
1980 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001981 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001982 } // if
1983 } // if firstUsableLBA check
1984
1985 // If couldn't move the sector earlier, try to move it later instead....
1986 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1987 sectorOK = 1;
1988 testSector = later;
1989 do {
1990 sectorOK = IsFree(testSector--);
1991 } while ((sectorOK == 1) && (testSector > *sector));
1992 if (sectorOK == 1) {
1993 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001994 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001995 } // if
1996 } // if
srs56941d1448a2009-12-31 21:20:19 -05001997 } // if
1998 return retval;
1999} // GPTData::Align()
2000
srs5694e4ac11e2009-08-31 10:13:04 -04002001/********************************************************
2002 * *
2003 * Functions that return data about GPT data structures *
2004 * (most of these are inline in gpt.h) *
2005 * *
2006 ********************************************************/
2007
2008// Find the low and high used partition numbers (numbered from 0).
2009// Return value is the number of partitions found. Note that the
2010// *low and *high values are both set to 0 when no partitions
2011// are found, as well as when a single partition in the first
2012// position exists. Thus, the return value is the only way to
2013// tell when no partitions exist.
2014int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2015 uint32_t i;
2016 int numFound = 0;
2017
srs56940283dae2010-04-28 16:44:34 -04002018 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04002019 *high = 0;
srs56940283dae2010-04-28 16:44:34 -04002020 if (numParts > 0) { // only try if partition table exists...
2021 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002022 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
2023 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05002024 // Set the low value only if it's not yet found...
srs56940283dae2010-04-28 16:44:34 -04002025 if (*low == (numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05002026 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04002027 } // if
2028 } // for
2029 } // if
2030
2031 // Above will leave *low pointing to its "not found" value if no partitions
2032 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002033 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002034 *low = 0;
2035 return numFound;
2036} // GPTData::GetPartRange()
2037
srs569408bb0da2010-02-19 17:19:55 -05002038// Returns the value of the first free partition, or -1 if none is
2039// unused.
2040int GPTData::FindFirstFreePart(void) {
2041 int i = 0;
2042
2043 if (partitions != NULL) {
srs56940283dae2010-04-28 16:44:34 -04002044 while ((partitions[i].IsUsed()) && (i < (int) numParts))
srs569408bb0da2010-02-19 17:19:55 -05002045 i++;
srs56940283dae2010-04-28 16:44:34 -04002046 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002047 i = -1;
2048 } else i = -1;
2049 return i;
2050} // GPTData::FindFirstFreePart()
2051
srs5694978041c2009-09-21 20:51:47 -04002052// Returns the number of defined partitions.
2053uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002054 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002055
srs56940283dae2010-04-28 16:44:34 -04002056 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002057 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002058 counted++;
2059 } // for
2060 return counted;
2061} // GPTData::CountParts()
2062
srs5694e4ac11e2009-08-31 10:13:04 -04002063/****************************************************
2064 * *
2065 * Functions that return data about disk free space *
2066 * *
2067 ****************************************************/
2068
2069// Find the first available block after the starting point; returns 0 if
2070// there are no available blocks left
2071uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2072 uint64_t first;
2073 uint32_t i;
2074 int firstMoved = 0;
2075
2076 // Begin from the specified starting point or from the first usable
2077 // LBA, whichever is greater...
2078 if (start < mainHeader.firstUsableLBA)
2079 first = mainHeader.firstUsableLBA;
2080 else
2081 first = start;
2082
2083 // ...now search through all partitions; if first is within an
2084 // existing partition, move it to the next sector after that
2085 // partition and repeat. If first was moved, set firstMoved
2086 // flag; repeat until firstMoved is not set, so as to catch
2087 // cases where partitions are out of sequential order....
2088 do {
2089 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002090 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002091 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002092 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002093 first = partitions[i].GetLastLBA() + 1;
2094 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002095 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002096 } // for
2097 } while (firstMoved == 1);
2098 if (first > mainHeader.lastUsableLBA)
2099 first = 0;
2100 return (first);
2101} // GPTData::FindFirstAvailable()
2102
2103// Finds the first available sector in the largest block of unallocated
2104// space on the disk. Returns 0 if there are no available blocks left
2105uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002106 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002107
2108 start = 0;
2109 do {
2110 firstBlock = FindFirstAvailable(start);
2111 if (firstBlock != UINT32_C(0)) { // something's free...
2112 lastBlock = FindLastInFree(firstBlock);
2113 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2114 if (segmentSize > selectedSize) {
2115 selectedSize = segmentSize;
2116 selectedSegment = firstBlock;
2117 } // if
2118 start = lastBlock + 1;
2119 } // if
2120 } while (firstBlock != 0);
2121 return selectedSegment;
2122} // GPTData::FindFirstInLargest()
2123
srs5694cb76c672010-02-11 22:22:22 -05002124// Find the last available block on the disk.
2125// Returns 0 if there are no available partitions
2126uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002127 uint64_t last;
2128 uint32_t i;
2129 int lastMoved = 0;
2130
2131 // Start by assuming the last usable LBA is available....
2132 last = mainHeader.lastUsableLBA;
2133
2134 // ...now, similar to algorithm in FindFirstAvailable(), search
2135 // through all partitions, moving last when it's in an existing
2136 // partition. Set the lastMoved flag so we repeat to catch cases
2137 // where partitions are out of logical order.
2138 do {
2139 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002140 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002141 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002142 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002143 last = partitions[i].GetFirstLBA() - 1;
2144 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002145 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002146 } // for
2147 } while (lastMoved == 1);
2148 if (last < mainHeader.firstUsableLBA)
2149 last = 0;
2150 return (last);
2151} // GPTData::FindLastAvailable()
2152
2153// Find the last available block in the free space pointed to by start.
2154uint64_t GPTData::FindLastInFree(uint64_t start) {
2155 uint64_t nearestStart;
2156 uint32_t i;
2157
2158 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002159 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002160 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002161 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002162 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002163 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002164 } // for
2165 return (nearestStart);
2166} // GPTData::FindLastInFree()
2167
2168// Finds the total number of free blocks, the number of segments in which
2169// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002170uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002171 uint64_t start = UINT64_C(0); // starting point for each search
2172 uint64_t totalFound = UINT64_C(0); // running total
2173 uint64_t firstBlock; // first block in a segment
2174 uint64_t lastBlock; // last block in a segment
2175 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002176 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002177
2178 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002179 if (diskSize > 0) {
2180 do {
2181 firstBlock = FindFirstAvailable(start);
2182 if (firstBlock != UINT64_C(0)) { // something's free...
2183 lastBlock = FindLastInFree(firstBlock);
2184 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2185 if (segmentSize > *largestSegment) {
2186 *largestSegment = segmentSize;
2187 } // if
2188 totalFound += segmentSize;
2189 num++;
2190 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002191 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002192 } while (firstBlock != 0);
2193 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002194 *numSegments = num;
2195 return totalFound;
2196} // GPTData::FindFreeBlocks()
2197
srs569455d92612010-03-07 22:16:07 -05002198// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2199// If it's allocated, return the partition number to which it's allocated
2200// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2201// returned in partNum if the sector is in use by basic GPT data structures.)
2202int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002203 int isFree = 1;
2204 uint32_t i;
2205
srs56940283dae2010-04-28 16:44:34 -04002206 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002207 if ((sector >= partitions[i].GetFirstLBA()) &&
2208 (sector <= partitions[i].GetLastLBA())) {
2209 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002210 if (partNum != NULL)
2211 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002212 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002213 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002214 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002215 (sector > mainHeader.lastUsableLBA)) {
2216 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002217 if (partNum != NULL)
2218 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002219 } // if
2220 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002221} // GPTData::IsFree()
2222
srs5694ba00fed2010-01-12 18:18:36 -05002223// Returns 1 if partNum is unused.
2224int GPTData::IsFreePartNum(uint32_t partNum) {
2225 int retval = 1;
2226
srs56940283dae2010-04-28 16:44:34 -04002227 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002228 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002229 retval = 0;
2230 } // if partition is in use
2231 } else retval = 0;
2232
2233 return retval;
2234} // GPTData::IsFreePartNum()
2235
srs5694a8582cf2010-03-19 14:21:59 -04002236
2237/***********************************************************
2238 * *
2239 * Change how functions work or return information on them *
2240 * *
2241 ***********************************************************/
2242
2243// Set partition alignment value; partitions will begin on multiples of
2244// the specified value
2245void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002246 if (n > 0)
2247 sectorAlignment = n;
2248 else
2249 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002250} // GPTData::SetAlignment()
2251
2252// Compute sector alignment based on the current partitions (if any). Each
2253// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002254// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2255// sector size), but not by the previously-located alignment value, then the
2256// alignment value is adjusted down. If the computed alignment is less than 8
2257// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2258// is a safety measure for WD Advanced Format and similar drives. If no partitions
2259// are defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2260// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002261// drives are aligned to 2048-sector multiples but the program won't complain
2262// about other alignments on existing disks unless a smaller-than-8 alignment
srs56940873e9d2010-10-07 13:00:45 -04002263// is used on big disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002264// Returns the computed alignment value.
2265uint32_t GPTData::ComputeAlignment(void) {
2266 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002267 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002268
srs56940873e9d2010-10-07 13:00:45 -04002269 if (blockSize > 0)
2270 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2271 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002272 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002273 if (partitions[i].IsUsed()) {
2274 found = 0;
2275 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002276 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002277 if ((partitions[i].GetFirstLBA() % align) == 0) {
2278 found = 1;
2279 } else {
2280 exponent--;
2281 } // if/else
2282 } // while
2283 } // if
2284 } // for
srs56940873e9d2010-10-07 13:00:45 -04002285 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2286 align = MIN_AF_ALIGNMENT;
2287 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002288 return align;
2289} // GPTData::ComputeAlignment()
2290
srs5694e4ac11e2009-08-31 10:13:04 -04002291/********************************
2292 * *
2293 * Endianness support functions *
2294 * *
2295 ********************************/
2296
srs56942a9f5da2009-08-26 00:48:01 -04002297void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002298 ReverseBytes(&header->signature, 8);
2299 ReverseBytes(&header->revision, 4);
2300 ReverseBytes(&header->headerSize, 4);
2301 ReverseBytes(&header->headerCRC, 4);
2302 ReverseBytes(&header->reserved, 4);
2303 ReverseBytes(&header->currentLBA, 8);
2304 ReverseBytes(&header->backupLBA, 8);
2305 ReverseBytes(&header->firstUsableLBA, 8);
2306 ReverseBytes(&header->lastUsableLBA, 8);
2307 ReverseBytes(&header->partitionEntriesLBA, 8);
2308 ReverseBytes(&header->numParts, 4);
2309 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2310 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002311 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002312} // GPTData::ReverseHeaderBytes()
2313
srs56940283dae2010-04-28 16:44:34 -04002314// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002315void GPTData::ReversePartitionBytes() {
2316 uint32_t i;
2317
srs56940283dae2010-04-28 16:44:34 -04002318 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002319 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002320 } // for
2321} // GPTData::ReversePartitionBytes()
2322
srs56949ddc14b2010-08-22 22:44:42 -04002323// Validate partition number
2324bool GPTData::ValidPartNum (const uint32_t partNum) {
2325 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002326 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002327 return false;
2328 } // if
2329 return true;
2330} // GPTData::ValidPartNum
2331
srs56945a081752010-09-24 20:39:41 -04002332// Return a single partition for inspection (not modification!) by other
2333// functions.
2334const GPTPart & GPTData::operator[](uint32_t partNum) const {
2335 if (partNum >= numParts) {
2336 cerr << "Partition number out of range: " << partNum << "\n";
2337 partNum = 0;
2338 } // if
2339 return partitions[partNum];
2340} // operator[]
2341
2342// Return (not for modification!) the disk's GUID value
2343const GUIDData & GPTData::GetDiskGUID(void) const {
2344 return mainHeader.diskGUID;
2345} // GPTData::GetDiskGUID()
2346
srs56949ddc14b2010-08-22 22:44:42 -04002347// Manage attributes for a partition, based on commands passed to this function.
2348// (Function is non-interactive.)
2349// Returns 1 if a modification command succeeded, 0 if the command should not have
2350// modified data, and -1 if a modification command failed.
2351int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2352 int retval = 0;
2353 Attributes theAttr;
2354
2355 if (command == "show") {
2356 ShowAttributes(partNum);
2357 } else if (command == "get") {
2358 GetAttribute(partNum, bits);
2359 } else {
2360 theAttr = partitions[partNum].GetAttributes();
2361 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2362 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2363 retval = 1;
2364 } else {
2365 retval = -1;
2366 } // if/else
2367 } // if/elseif/else
2368
2369 return retval;
2370} // GPTData::ManageAttributes()
2371
2372// Show all attributes for a specified partition....
2373void GPTData::ShowAttributes(const uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04002374 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002375} // GPTData::ShowAttributes
2376
2377// Show whether a single attribute bit is set (terse output)...
2378void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002379 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002380} // GPTData::GetAttribute
2381
2382
srs56942a9f5da2009-08-26 00:48:01 -04002383/******************************************
2384 * *
2385 * Additional non-class support functions *
2386 * *
2387 ******************************************/
2388
srs5694e7b4ff92009-08-18 13:16:10 -04002389// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2390// never fail these tests, but the struct types may fail depending on compile options.
2391// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2392// sizes.
2393int SizesOK(void) {
2394 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002395
2396 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002397 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002398 allOK = 0;
2399 } // if
2400 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002401 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002402 allOK = 0;
2403 } // if
2404 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002405 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002406 allOK = 0;
2407 } // if
2408 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002409 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002410 allOK = 0;
2411 } // if
2412 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002413 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002414 allOK = 0;
2415 } // if
srs5694978041c2009-09-21 20:51:47 -04002416 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002417 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002418 allOK = 0;
2419 } // if
2420 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002421 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002422 allOK = 0;
2423 } // if
srs5694221e0872009-08-29 15:00:31 -04002424 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002425 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002426 allOK = 0;
2427 } // if
srs56946699b012010-02-04 00:55:30 -05002428 if (sizeof(GUIDData) != 16) {
2429 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2430 allOK = 0;
2431 } // if
2432 if (sizeof(PartType) != 16) {
2433 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2434 allOK = 0;
2435 } // if
srs5694fed16d02010-01-27 23:03:40 -05002436 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56940873e9d2010-10-07 13:00:45 -04002437// if (IsLittleEndian() == 0) {
2438// cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2439// " tested!\n";
2440// } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002441 return (allOK);
2442} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002443