blob: 0dc5acf1a9a697dee0e7a7a605dae54c2c9fec90 [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
Roderick W. Smithe3ee7332013-09-24 12:56:11 -04006/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040022#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "crc32.h"
24#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040025#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040026#include "support.h"
27#include "parttypes.h"
28#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050029#include "diskio.h"
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;
srs56941e093722010-01-05 00:14:19 -050064 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040065 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040066 SetGPTSize(NUM_GPT_ENTRIES);
srs5694d1b11e82011-09-18 21:12:28 -040067 // Initialize CRC functions...
68 chksum_crc32gentab();
srs5694e7b4ff92009-08-18 13:16:10 -040069} // GPTData default constructor
70
71// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050072GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040073 blockSize = SECTOR_SIZE; // set a default
74 diskSize = 0;
75 partitions = NULL;
76 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050077 device = "";
srs56945d58fe02010-01-03 20:57:08 -050078 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040079 mainCrcOk = 0;
80 secondCrcOk = 0;
81 mainPartsCrcOk = 0;
82 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040083 apmFound = 0;
84 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040085 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050086 beQuiet = 0;
87 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050088 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040089 numParts = 0;
srs5694d1b11e82011-09-18 21:12:28 -040090 // Initialize CRC functions...
91 chksum_crc32gentab();
srs56943c0af382010-01-15 19:19:18 -050092 if (!LoadPartitions(filename))
93 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050094} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040095
srs5694e4ac11e2009-08-31 10:13:04 -040096// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040097GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050098 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040099} // GPTData destructor
100
srs569464cbd172011-03-01 22:03:54 -0500101// Assignment operator
102GPTData & GPTData::operator=(const GPTData & orig) {
103 uint32_t i;
104
105 mainHeader = orig.mainHeader;
106 numParts = orig.numParts;
107 secondHeader = orig.secondHeader;
108 protectiveMBR = orig.protectiveMBR;
109 device = orig.device;
110 blockSize = orig.blockSize;
111 diskSize = orig.diskSize;
112 state = orig.state;
113 justLooking = orig.justLooking;
114 mainCrcOk = orig.mainCrcOk;
115 secondCrcOk = orig.secondCrcOk;
116 mainPartsCrcOk = orig.mainPartsCrcOk;
117 secondPartsCrcOk = orig.secondPartsCrcOk;
118 apmFound = orig.apmFound;
119 bsdFound = orig.bsdFound;
120 sectorAlignment = orig.sectorAlignment;
121 beQuiet = orig.beQuiet;
122 whichWasUsed = orig.whichWasUsed;
123
124 myDisk.OpenForRead(orig.myDisk.GetName());
125
126 delete[] partitions;
srs569401f7f082011-03-15 23:53:31 -0400127 partitions = new GPTPart [numParts];
srs56946aae2a92011-06-10 01:16:51 -0400128 if (partitions == NULL) {
srs569464cbd172011-03-01 22:03:54 -0500129 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
srs56946aae2a92011-06-10 01:16:51 -0400130 << "Terminating!\n";
131 exit(1);
132 } // if
133 for (i = 0; i < numParts; i++) {
134 partitions[i] = orig.partitions[i];
srs5694d1b11e82011-09-18 21:12:28 -0400135 } // for
136
srs569464cbd172011-03-01 22:03:54 -0500137 return *this;
138} // GPTData::operator=()
139
srs5694e4ac11e2009-08-31 10:13:04 -0400140/*********************************************************************
141 * *
142 * Begin functions that verify data, or that adjust the verification *
143 * information (compute CRCs, rebuild headers) *
144 * *
145 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400146
srs5694e4ac11e2009-08-31 10:13:04 -0400147// Perform detailed verification, reporting on any problems found, but
148// do *NOT* recover from these problems. Returns the total number of
149// problems identified.
150int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500151 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500152 uint32_t i, numSegments;
153 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400154
155 // First, check for CRC errors in the GPT data....
156 if (!mainCrcOk) {
157 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500158 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
159 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
160 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
161 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (!mainPartsCrcOk) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
166 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
167 << "transformation menu). This report may be a false alarm if you've already\n"
168 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400169 } // if
170 if (!secondCrcOk) {
171 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500172 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
173 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
174 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
175 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400176 } // if
177 if (!secondPartsCrcOk) {
178 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500179 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
180 << "be corrupt. This program will automatically create a new backup partition\n"
181 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400182 } // if
183
srs5694978041c2009-09-21 20:51:47 -0400184 // Now check that the main and backup headers both point to themselves....
185 if (mainHeader.currentLBA != 1) {
186 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500187 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
188 << "is being automatically corrected, but it may be a symptom of more serious\n"
189 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400190 mainHeader.currentLBA = 1;
191 } // if
192 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
193 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500194 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
195 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
196 << "option on the experts' menu to adjust the secondary header's and partition\n"
197 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400198 } // if
199
200 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400201 if (mainHeader.currentLBA != secondHeader.backupLBA) {
202 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500203 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
204 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
205 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400206 } // if
207 if (mainHeader.backupLBA != secondHeader.currentLBA) {
208 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500209 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
210 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
211 << secondHeader.currentLBA << ").\n"
212 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400213 } // if
214 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
215 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500216 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
217 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
218 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400219 } // if
220 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
221 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500222 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
223 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
224 << secondHeader.lastUsableLBA << ")\n"
225 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400226 } // if
srs56946699b012010-02-04 00:55:30 -0500227 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400228 problems++;
srs56945a081752010-09-24 20:39:41 -0400229 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500230 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400231 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500232 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
233 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400234 } // if
235 if (mainHeader.numParts != secondHeader.numParts) {
236 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500237 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
238 << ") doesn't\nmatch the backup GPT header's number of partitions ("
239 << secondHeader.numParts << ")\n"
240 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } // if
242 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
243 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500244 cout << "\nProblem: main GPT header's size of partition entries ("
245 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
246 << "match the backup GPT header's size of partition entries ("
247 << secondHeader.sizeOfPartitionEntries << ")\n"
248 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
249 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400250 } // if
251
252 // Now check for a few other miscellaneous problems...
253 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500254 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400255 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500256 cout << "\nProblem: Disk is too small to hold all the data!\n"
257 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500258 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500259 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400260 } // if
261
srs5694d8eed462012-12-15 01:55:21 -0500262 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
263 problems++;
srs56940741fa22013-01-09 12:55:40 -0500264 cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
265 << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
266 << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
267 << "The 'e' option on the experts' menu will probably fix this problem\n";
srs5694d8eed462012-12-15 01:55:21 -0500268 }
269
srs5694e4ac11e2009-08-31 10:13:04 -0400270 // Check for overlapping partitions....
271 problems += FindOverlaps();
272
srs569455d92612010-03-07 22:16:07 -0500273 // Check for insane partitions (start after end, hugely big, etc.)
274 problems += FindInsanePartitions();
275
srs5694e4ac11e2009-08-31 10:13:04 -0400276 // Check for mismatched MBR and GPT partitions...
277 problems += FindHybridMismatches();
278
srs5694327129e2010-09-22 01:07:31 -0400279 // Check for MBR-specific problems....
280 problems += VerifyMBR();
281
Roderick W. Smith042f38a2013-08-31 17:40:15 -0400282 // Check for a 0xEE protective partition that's marked as active....
283 if (protectiveMBR.IsEEActive()) {
284 cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
285 << "technically a violation of the GPT specification, and can cause some EFIs to\n"
286 << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
287 << "computers. You can clear this flag by creating a fresh protective MBR using\n"
288 << "the 'n' option on the experts' menu.\n";
289 }
290
srs5694e4ac11e2009-08-31 10:13:04 -0400291 // Verify that partitions don't run into GPT data areas....
292 problems += CheckGPTSize();
293
srs56941d1448a2009-12-31 21:20:19 -0500294 // Check that partitions are aligned on proper boundaries (for WD Advanced
295 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400296 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500297 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500298 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
299 << sectorAlignment << "-sector boundary. This may\nresult "
300 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500301 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500302 } // if
303 } // for
srs569464cbd172011-03-01 22:03:54 -0500304 if (alignProbs > 0)
305 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
306 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500307
srs5694e4ac11e2009-08-31 10:13:04 -0400308 // Now compute available space, but only if no problems found, since
309 // problems could affect the results
310 if (problems == 0) {
311 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500312 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400313 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500314 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400315 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400316 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400317 } else {
srs56940a697312010-01-28 21:10:52 -0500318 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400319 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400320
321 return (problems);
322} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400323
324// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400325// do, issues a warning but takes no action. Returns number of problems
326// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400327int GPTData::CheckGPTSize(void) {
328 uint64_t overlap, firstUsedBlock, lastUsedBlock;
329 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400330 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400331
332 // first, locate the first & last used blocks
333 firstUsedBlock = UINT64_MAX;
334 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400335 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500336 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500337 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500338 firstUsedBlock = partitions[i].GetFirstLBA();
339 if (partitions[i].GetLastLBA() > lastUsedBlock) {
340 lastUsedBlock = partitions[i].GetLastLBA();
341 } // if
342 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400343 } // for
344
345 // If the disk size is 0 (the default), then it means that various
346 // variables aren't yet set, so the below tests will be useless;
347 // therefore we should skip everything
348 if (diskSize != 0) {
349 if (mainHeader.firstUsableLBA > firstUsedBlock) {
350 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500351 cout << "Warning! Main partition table overlaps the first partition by "
352 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400353 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500354 cout << "Try reducing the partition table size by " << overlap * 4
355 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400356 } else {
srs5694fed16d02010-01-27 23:03:40 -0500357 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400358 } // if/else
359 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400360 } // Problem at start of disk
361 if (mainHeader.lastUsableLBA < lastUsedBlock) {
362 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500363 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500364 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400365 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500366 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400367 } else {
srs5694fed16d02010-01-27 23:03:40 -0500368 cout << "Try reducing the partition table size by " << overlap * 4
369 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400370 } // if/else
371 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400372 } // Problem at end of disk
373 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400374 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400375} // GPTData::CheckGPTSize()
376
srs5694e7b4ff92009-08-18 13:16:10 -0400377// Check the validity of the GPT header. Returns 1 if the main header
378// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400379// 0 if neither is valid. Note that this function checks the GPT signature,
380// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400381int GPTData::CheckHeaderValidity(void) {
382 int valid = 3;
383
srs5694fed16d02010-01-27 23:03:40 -0500384 cout.setf(ios::uppercase);
385 cout.fill('0');
386
387 // Note: failed GPT signature checks produce no error message because
388 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400389 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400390 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400391 } else if ((mainHeader.revision != 0x00010000) && valid) {
392 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500393 cout << "Unsupported GPT version in main header; read 0x";
394 cout.width(8);
395 cout << hex << mainHeader.revision << ", should be\n0x";
396 cout.width(8);
397 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400398 } // if/else/if
399
srs5694d1b11e82011-09-18 21:12:28 -0400400 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400401 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400402 } else if ((secondHeader.revision != 0x00010000) && valid) {
403 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500404 cout << "Unsupported GPT version in backup header; read 0x";
405 cout.width(8);
406 cout << hex << secondHeader.revision << ", should be\n0x";
407 cout.width(8);
408 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400409 } // if/else/if
410
srs5694df9d3632011-01-08 18:33:24 -0500411 // Check for an Apple disk signature
412 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
413 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400414 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500415 } // if
srs5694fed16d02010-01-27 23:03:40 -0500416 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400417
srs5694fed16d02010-01-27 23:03:40 -0500418 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400419} // GPTData::CheckHeaderValidity()
420
421// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400422// Note: Must be called with header in platform-ordered byte order.
423// Returns 1 if header's computed CRC matches the stored value, 0 if the
424// computed and stored values don't match
425int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400426 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400427 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400428
srs56942a9f5da2009-08-26 00:48:01 -0400429 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400430 // computation to be valid
431 oldCRC = header->headerCRC;
432 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400433
srs5694978041c2009-09-21 20:51:47 -0400434 hSize = header->headerSize;
435
srs5694d1b11e82011-09-18 21:12:28 -0400436 if (IsLittleEndian() == 0)
437 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400438
srs5694d1b11e82011-09-18 21:12:28 -0400439 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
440 if (warn) {
441 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
442 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
443 } // if
444 hSize = HEADER_SIZE;
445 } else if ((hSize > sizeof(GPTHeader)) && warn) {
446 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
447 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
448 << "which may result in a CRC false alarm.\n";
449 } // if/elseif
450 temp = new uint8_t[hSize];
451 if (temp != NULL) {
452 memset(temp, 0, hSize);
453 if (hSize < sizeof(GPTHeader))
454 memcpy(temp, header, hSize);
455 else
456 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400457
srs5694d1b11e82011-09-18 21:12:28 -0400458 newCRC = chksum_crc32((unsigned char*) temp, hSize);
459 delete[] temp;
460 } else {
461 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
462 exit(1);
463 }
464 if (IsLittleEndian() == 0)
465 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400466 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400467 return (oldCRC == newCRC);
468} // GPTData::CheckHeaderCRC()
469
srs56946699b012010-02-04 00:55:30 -0500470// Recompute all the CRCs. Must be called before saving if any changes have
471// been made. Must be called on platform-ordered data (this function reverses
472// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400473void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400474 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400475 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400476
srs5694d1b11e82011-09-18 21:12:28 -0400477 // If the header size is bigger than the GPT header data structure, reset it;
478 // otherwise, set both header sizes to whatever the main one is....
479 if (mainHeader.headerSize > sizeof(GPTHeader))
480 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
481 else
482 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500483
484 if ((littleEndian = IsLittleEndian()) == 0) {
485 ReversePartitionBytes();
486 ReverseHeaderBytes(&mainHeader);
487 ReverseHeaderBytes(&secondHeader);
488 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400489
srs5694e7b4ff92009-08-18 13:16:10 -0400490 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400491 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400492 mainHeader.partitionEntriesCRC = crc;
493 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400494 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400495 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
496 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400497 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400498
srs5694d1b11e82011-09-18 21:12:28 -0400499 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400500 mainHeader.headerCRC = 0;
501 secondHeader.headerCRC = 0;
502
srs5694978041c2009-09-21 20:51:47 -0400503 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400504 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400505 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400506 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400507 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400508 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400509 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400510 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500511
srs5694d1b11e82011-09-18 21:12:28 -0400512 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500513 ReverseHeaderBytes(&mainHeader);
514 ReverseHeaderBytes(&secondHeader);
515 ReversePartitionBytes();
516 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400517} // GPTData::RecomputeCRCs()
518
srs5694e7b4ff92009-08-18 13:16:10 -0400519// Rebuild the main GPT header, using the secondary header as a model.
520// Typically called when the main header has been found to be corrupt.
521void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400522 mainHeader.signature = GPT_SIGNATURE;
523 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400524 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400525 mainHeader.headerCRC = UINT32_C(0);
526 mainHeader.reserved = secondHeader.reserved;
527 mainHeader.currentLBA = secondHeader.backupLBA;
528 mainHeader.backupLBA = secondHeader.currentLBA;
529 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
530 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500531 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400532 mainHeader.partitionEntriesLBA = UINT64_C(2);
533 mainHeader.numParts = secondHeader.numParts;
534 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
535 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400536 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500537 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500538 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400539} // GPTData::RebuildMainHeader()
540
541// Rebuild the secondary GPT header, using the main header as a model.
542void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400543 secondHeader.signature = GPT_SIGNATURE;
544 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400545 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400546 secondHeader.headerCRC = UINT32_C(0);
547 secondHeader.reserved = mainHeader.reserved;
548 secondHeader.currentLBA = mainHeader.backupLBA;
549 secondHeader.backupLBA = mainHeader.currentLBA;
550 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
551 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500552 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400553 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
554 secondHeader.numParts = mainHeader.numParts;
555 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
556 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400557 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500558 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500559 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400560} // GPTData::RebuildSecondHeader()
561
562// Search for hybrid MBR entries that have no corresponding GPT partition.
563// Returns number of such mismatches found
564int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500565 int i, found, numFound = 0;
566 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400567 uint64_t mbrFirst, mbrLast;
568
569 for (i = 0; i < 4; i++) {
570 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
571 j = 0;
572 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400573 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
574 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400575 do {
srs5694e4ac11e2009-08-31 10:13:04 -0400576 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500577 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400578 found = 1;
579 j++;
srs56940283dae2010-04-28 16:44:34 -0400580 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400581 if (!found) {
582 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500583 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
584 << i + 1 << ", of type 0x";
585 cout.fill('0');
586 cout.setf(ios::uppercase);
587 cout.width(2);
588 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
589 << "has no corresponding GPT partition! You may continue, but this condition\n"
590 << "might cause data loss in the future!\a\n" << dec;
591 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400592 } // if
593 } // if
594 } // for
595 return numFound;
596} // GPTData::FindHybridMismatches
597
598// Find overlapping partitions and warn user about them. Returns number of
599// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400600// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400601int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500602 int problems = 0;
603 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400604
srs56940283dae2010-04-28 16:44:34 -0400605 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400606 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500607 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
608 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400609 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500610 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
611 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
612 << " to " << partitions[i].GetLastLBA() << "\n";
613 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
614 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400615 } // if
616 } // for j...
617 } // for i...
618 return problems;
619} // GPTData::FindOverlaps()
620
srs569455d92612010-03-07 22:16:07 -0500621// Find partitions that are insane -- they start after they end or are too
622// big for the disk. (The latter should duplicate detection of overlaps
623// with GPT backup data structures, but better to err on the side of
624// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400625// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500626int GPTData::FindInsanePartitions(void) {
627 uint32_t i;
628 int problems = 0;
629
srs56940283dae2010-04-28 16:44:34 -0400630 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500631 if (partitions[i].IsUsed()) {
632 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
633 problems++;
634 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
635 } // if
636 if (partitions[i].GetLastLBA() >= diskSize) {
637 problems++;
638 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
639 } // if
srs569455d92612010-03-07 22:16:07 -0500640 } // if
641 } // for
642 return problems;
643} // GPTData::FindInsanePartitions(void)
644
645
srs5694e4ac11e2009-08-31 10:13:04 -0400646/******************************************************************
647 * *
648 * Begin functions that load data from disk or save data to disk. *
649 * *
650 ******************************************************************/
651
srs569464cbd172011-03-01 22:03:54 -0500652// Change the filename associated with the GPT. Used for duplicating
653// the partition table to a new disk and saving backups.
654// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500655int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500656 int err, allOK = 1;
657
658 device = deviceFilename;
659 if (allOK && myDisk.OpenForRead(deviceFilename)) {
660 // store disk information....
661 diskSize = myDisk.DiskSize(&err);
662 blockSize = (uint32_t) myDisk.GetBlockSize();
663 } // if
664 protectiveMBR.SetDisk(&myDisk);
665 protectiveMBR.SetDiskSize(diskSize);
666 protectiveMBR.SetBlockSize(blockSize);
667 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500668} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500669
srs5694e4ac11e2009-08-31 10:13:04 -0400670// Scan for partition data. This function loads the MBR data (regular MBR or
671// protective MBR) and loads BSD disklabel data (which is probably invalid).
672// It also looks for APM data, forces a load of GPT data, and summarizes
673// the results.
srs5694546a9c72010-01-26 16:00:26 -0500674void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400675 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400676
677 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500678 protectiveMBR.ReadMBRData(&myDisk);
679 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400680
681 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500682 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500683
684 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500685 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500686 protectiveMBR.ShowState();
687 bsdDisklabel.ShowState();
688 ShowAPMState(); // Show whether there's an Apple Partition Map present
689 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500690 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500691 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400692
693 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500694 cout << "\n*******************************************************************\n"
695 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500696 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500697 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500698 } // if
srs5694fed16d02010-01-27 23:03:40 -0500699 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400700 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400701} // GPTData::PartitionScan()
702
703// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500704int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500705 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500706 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500707 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400708
srs5694546a9c72010-01-26 16:00:26 -0500709 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500710 err = myDisk.OpenForWrite(deviceFilename);
711 if ((err == 0) && (!justLooking)) {
712 cout << "\aNOTE: Write test failed with error number " << errno
713 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
714#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
715 cout << "You may be able to enable writes by exiting this program, typing\n"
716 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
717 << "program.\n";
718#endif
719 cout << "\n";
720 } // if
721 myDisk.Close(); // Close and re-open read-only in case of bugs
722 } else allOK = 0; // if
723
724 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400725 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500726 diskSize = myDisk.DiskSize(&err);
727 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500728 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500729 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400730
srs5694ba00fed2010-01-12 18:18:36 -0500731 whichWasUsed = UseWhichPartitions();
732 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400733 case use_mbr:
734 XFormPartitions();
735 break;
736 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500737 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400738// bsdDisklabel.DisplayBSDData();
739 ClearGPTData();
740 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500741 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400742 break;
743 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500744 mbrState = protectiveMBR.GetValidity();
745 if ((mbrState == invalid) || (mbrState == mbr))
746 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400747 break;
748 case use_new:
749 ClearGPTData();
750 protectiveMBR.MakeProtectiveMBR();
751 break;
srs56943c0af382010-01-15 19:19:18 -0500752 case use_abort:
753 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400754 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500755 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400756 } // switch
757
srs569455d92612010-03-07 22:16:07 -0500758 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500759 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500760 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400761 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400762 } else {
763 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400764 } // if/else
765 return (allOK);
766} // GPTData::LoadPartitions()
767
768// Loads the GPT, as much as possible. Returns 1 if this seems to have
769// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500770int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500771 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400772
srs5694cb76c672010-02-11 22:22:22 -0500773 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400774
srs5694cb76c672010-02-11 22:22:22 -0500775 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
776 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
777 } else {
srs569408bb0da2010-02-19 17:19:55 -0500778 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
779 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500780 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
781 << "secondary header from the last sector of the disk! You should use 'v' to\n"
782 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
783 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500784 } // if/else
785 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400786 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400787
788 // Return valid headers code: 0 = both headers bad; 1 = main header
789 // good, backup bad; 2 = backup header good, main header bad;
790 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400791 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400792 validHeaders = CheckHeaderValidity();
793
794 // Read partitions (from primary array)
795 if (validHeaders > 0) { // if at least one header is OK....
796 // GPT appears to be valid....
797 state = gpt_valid;
798
799 // We're calling the GPT valid, but there's a possibility that one
800 // of the two headers is corrupt. If so, use the one that seems to
801 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500802 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500803 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
804 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400805 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500806 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400807 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500808 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500809 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
810 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500811 RebuildMainHeader();
812 state = gpt_corrupt;
813 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400814 } // if/else/if
815
srs5694546a9c72010-01-26 16:00:26 -0500816 // Figure out which partition table to load....
817 // Load the main partition table, since either its header's CRC is OK or the
818 // backup header's CRC is not OK....
819 if (mainCrcOk || !secondCrcOk) {
820 if (LoadMainTable() == 0)
821 allOK = 0;
822 } else { // bad main header CRC and backup header CRC is OK
823 state = gpt_corrupt;
824 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500825 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500826 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500827 } else { // backup table bad, bad main header CRC, but try main table in desperation....
828 if (LoadMainTable() == 0) {
829 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500830 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500831 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500832 } // if
833 } // if/else (LoadSecondTableAsMain())
834 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400835
srs5694cb76c672010-02-11 22:22:22 -0500836 if (loadedTable == 1)
837 secondPartsCrcOk = CheckTable(&secondHeader);
838 else if (loadedTable == 2)
839 mainPartsCrcOk = CheckTable(&mainHeader);
840 else
841 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400842
srs5694546a9c72010-01-26 16:00:26 -0500843 // Problem with main partition table; if backup is OK, use it instead....
844 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
845 state = gpt_corrupt;
846 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500847 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500848 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
849 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500850 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500851
srs5694e4ac11e2009-08-31 10:13:04 -0400852 // Check for valid CRCs and warn if there are problems
853 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
854 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500855 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400856 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500857 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400858 } else {
859 state = gpt_invalid;
860 } // if/else
861 return allOK;
862} // GPTData::ForceLoadGPTData()
863
srs5694247657a2009-11-26 18:36:12 -0500864// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400865// main GPT header in memory MUST be valid for this call to do anything
866// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500867// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400868int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500869 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400870} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400871
872// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500873// table. Used in repair functions, and when starting up if the main
874// partition table is damaged.
875// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
876int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500877 return LoadPartitionTable(secondHeader, myDisk);
878} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400879
srs5694cb76c672010-02-11 22:22:22 -0500880// Load a single GPT header (main or backup) from the specified disk device and
881// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
882// value appropriately.
883// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
884// failure.
885int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
886 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500887 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500888
889 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500890 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500891 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
892 allOK = 0;
893 } // if
srs5694cb76c672010-02-11 22:22:22 -0500894
srs56941c6f8b02010-02-21 11:09:20 -0500895 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500896 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500897 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500898 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400899 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500900
srs56940283dae2010-04-28 16:44:34 -0400901 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500902 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500903 }
srs56941c6f8b02010-02-21 11:09:20 -0500904
905 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500906 return allOK;
907} // GPTData::LoadHeader
908
909// Load a partition table (either main or secondary) from the specified disk,
910// using header as a reference for what to load. If sector != 0 (the default
911// is 0), loads from the specified sector; otherwise loads from the sector
912// indicated in header.
913// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
914int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
915 uint32_t sizeOfParts, newCRC;
916 int retval;
917
918 if (disk.OpenForRead()) {
919 if (sector == 0) {
920 retval = disk.Seek(header.partitionEntriesLBA);
921 } else {
922 retval = disk.Seek(sector);
923 } // if/else
srs569455d92612010-03-07 22:16:07 -0500924 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500925 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500926 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500927 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
928 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500929 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500930 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500931 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400932 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500933 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400934 if (IsLittleEndian() == 0)
935 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500936 if (!mainPartsCrcOk) {
937 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400938 } // if
939 } else {
srs5694cb76c672010-02-11 22:22:22 -0500940 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400941 } // if/else
942 } else {
srs5694fed16d02010-01-27 23:03:40 -0500943 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500944 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500945 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400946 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500947 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500948} // GPTData::LoadPartitionsTable()
949
950// Check the partition table pointed to by header, but don't keep it
951// around.
srs5694a17fe692011-09-10 20:30:20 -0400952// Returns 1 if the CRC is OK & this table matches the one already in memory,
953// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500954int GPTData::CheckTable(struct GPTHeader *header) {
955 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400956 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400957 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400958 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500959
srs56940283dae2010-04-28 16:44:34 -0400960 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500961 // its CRC and store the results, then discard this temporary
962 // storage, since we don't use it in any but recovery operations
963 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400964 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400965 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -0400966 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -0400967 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
968 exit(1);
969 } // if
srs5694a17fe692011-09-10 20:30:20 -0400970 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400971 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500972 } else {
srs5694d1b11e82011-09-18 21:12:28 -0400973 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -0400974 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -0400975 if (header == &mainHeader)
976 otherHeader = &secondHeader;
977 else
978 otherHeader = &mainHeader;
979 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -0400980 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
981 << "on the recovery & transformation menu to examine the two tables.\n\n";
982 allOK = 0;
983 } // if
srs5694cb76c672010-02-11 22:22:22 -0500984 } // if/else
srs5694a17fe692011-09-10 20:30:20 -0400985 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -0500986 } // if
srs5694a17fe692011-09-10 20:30:20 -0400987 return allOK;
srs5694cb76c672010-02-11 22:22:22 -0500988} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400989
srs56944307ef22012-05-30 12:30:48 -0400990// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
991// header later on the disk without asking for permission, if necessary, and
992// doesn't confirm the operation before writing. If quiet==0, asks permission
993// before moving the second header and asks for final confirmation of any
994// write.
srs5694a17fe692011-09-10 20:30:20 -0400995// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500996int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -0400997 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -0500998 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400999
srs5694e7b4ff92009-08-18 13:16:10 -04001000 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -05001001
1002 // This test should only fail on read-only disks....
1003 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001004 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -05001005 allOK = 0;
1006 } // if
1007
srs569464cbd172011-03-01 22:03:54 -05001008 // Check that disk is really big enough to handle the second header...
1009 if (mainHeader.backupLBA >= diskSize) {
1010 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1011 << "header, but other problems may occur!\n";
1012 MoveSecondHeaderToEnd();
1013 } // if
1014
srs5694e7b4ff92009-08-18 13:16:10 -04001015 // Is there enough space to hold the GPT headers and partition tables,
1016 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001017 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001018 allOK = 0;
1019 } // if
1020
srs5694247657a2009-11-26 18:36:12 -05001021 // Check that second header is properly placed. Warn and ask if this should
1022 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001023 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1024 if (quiet == 0) {
1025 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1026 << "correct this problem? ";
1027 if (GetYN() == 'Y') {
1028 MoveSecondHeaderToEnd();
1029 cout << "Have moved second header and partition table to correct location.\n";
1030 } else {
1031 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1032 } // if correction requested
1033 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001034 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001035 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001036 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001037
srs5694d8eed462012-12-15 01:55:21 -05001038 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1039 if (quiet == 0) {
1040 cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1041 << "this problem? ";
1042 if (GetYN() == 'Y') {
1043 MoveSecondHeaderToEnd();
1044 cout << "Have adjusted the second header and last usable sector value.\n";
1045 } else {
1046 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1047 } // if correction requested
1048 } else { // go ahead and do correction automatically
1049 MoveSecondHeaderToEnd();
1050 } // if/else quiet
1051 } // if
1052
srs569455d92612010-03-07 22:16:07 -05001053 // Check for overlapping or insane partitions....
1054 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001055 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001056 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001057 } // if
1058
1059 // Check for mismatched MBR and GPT data, but let it pass if found
1060 // (function displays warning message)
1061 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001062
1063 RecomputeCRCs();
1064
srs5694ba00fed2010-01-12 18:18:36 -05001065 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001066 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001067 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001068 answer = GetYN();
1069 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001070 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001071 } else {
1072 allOK = 0;
1073 } // if/else
1074 } // if
1075
1076 // Do it!
1077 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001078 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001079 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001080 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001081 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001082 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1083 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001084 syncIt = 0;
1085 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001086
1087 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001088 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1089
1090 // Now write the main partition tables...
1091 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1092
1093 // Now write the main GPT header...
1094 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1095
1096 // To top it off, write the protective MBR...
1097 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001098
1099 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001100 // Note: Done even if some write operations failed, but not if all of them failed.
1101 // Done this way because I've received one problem report from a user one whose
1102 // system the MBR write failed but everything else was OK (on a GPT disk under
1103 // Windows), and the failure to sync therefore caused Windows to restore the
1104 // original partition table from its cache. OTOH, such restoration might be
1105 // desirable if the error occurs later; but that seems unlikely unless the initial
1106 // write fails....
1107 if (syncIt)
srs5694546a9c72010-01-26 16:00:26 -05001108 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001109
1110 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001111 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001112 } else {
srs5694fed16d02010-01-27 23:03:40 -05001113 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001114 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001115 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001116
srs5694546a9c72010-01-26 16:00:26 -05001117 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001118 } else {
srs56945a608532011-03-17 13:53:01 -04001119 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001120 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001121 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001122 } // if/else
1123 } else {
srs5694fed16d02010-01-27 23:03:40 -05001124 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001125 } // if
1126
1127 return (allOK);
1128} // GPTData::SaveGPTData()
1129
1130// Save GPT data to a backup file. This function does much less error
1131// checking than SaveGPTData(). It can therefore preserve many types of
1132// corruption for later analysis; however, it preserves only the MBR,
1133// the main GPT header, the backup GPT header, and the main partition
1134// table; it discards the backup partition table, since it should be
1135// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001136int GPTData::SaveGPTBackup(const string & filename) {
1137 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001138 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001139
srs5694546a9c72010-01-26 16:00:26 -05001140 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001141 // Recomputing the CRCs is likely to alter them, which could be bad
1142 // if the intent is to save a potentially bad GPT for later analysis;
1143 // but if we don't do this, we get bogus errors when we load the
1144 // backup. I'm favoring misses over false alarms....
1145 RecomputeCRCs();
1146
srs5694546a9c72010-01-26 16:00:26 -05001147 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001148 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001149
srs5694cb76c672010-02-11 22:22:22 -05001150 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001151 // MBR write closed disk, so re-open and seek to end....
1152 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001153 allOK = SaveHeader(&mainHeader, backupFile, 1);
1154 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001155
srs5694e7b4ff92009-08-18 13:16:10 -04001156 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001157 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001158
srs5694cb76c672010-02-11 22:22:22 -05001159 if (allOK)
1160 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001161
1162 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001163 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001164 } else {
srs5694fed16d02010-01-27 23:03:40 -05001165 cerr << "Warning! An error was reported when writing the backup file.\n"
1166 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001167 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001168 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001169 } else {
srs56945a608532011-03-17 13:53:01 -04001170 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001171 allOK = 0;
1172 } // if/else
1173 return allOK;
1174} // GPTData::SaveGPTBackup()
1175
srs5694cb76c672010-02-11 22:22:22 -05001176// Write a GPT header (main or backup) to the specified sector. Used by both
1177// the SaveGPTData() and SaveGPTBackup() functions.
1178// Should be passed an architecture-appropriate header (DO NOT call
1179// ReverseHeaderBytes() on the header before calling this function)
1180// Returns 1 on success, 0 on failure
1181int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1182 int littleEndian, allOK = 1;
1183
1184 littleEndian = IsLittleEndian();
1185 if (!littleEndian)
1186 ReverseHeaderBytes(header);
1187 if (disk.Seek(sector)) {
1188 if (disk.Write(header, 512) == -1)
1189 allOK = 0;
1190 } else allOK = 0; // if (disk.Seek()...)
1191 if (!littleEndian)
1192 ReverseHeaderBytes(header);
1193 return allOK;
1194} // GPTData::SaveHeader()
1195
1196// Save the partitions to the specified sector. Used by both the SaveGPTData()
1197// and SaveGPTBackup() functions.
1198// Should be passed an architecture-appropriate header (DO NOT call
1199// ReverseHeaderBytes() on the header before calling this function)
1200// Returns 1 on success, 0 on failure
1201int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1202 int littleEndian, allOK = 1;
1203
1204 littleEndian = IsLittleEndian();
1205 if (disk.Seek(sector)) {
1206 if (!littleEndian)
1207 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001208 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001209 allOK = 0;
1210 if (!littleEndian)
1211 ReversePartitionBytes();
1212 } else allOK = 0; // if (myDisk.Seek()...)
1213 return allOK;
1214} // GPTData::SavePartitionTable()
1215
srs5694e7b4ff92009-08-18 13:16:10 -04001216// Load GPT data from a backup file created by SaveGPTBackup(). This function
1217// does minimal error checking. It returns 1 if it completed successfully,
1218// 0 if there was a problem. In the latter case, it creates a new empty
1219// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001220int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001221 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001222 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001223 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001224
srs5694546a9c72010-01-26 16:00:26 -05001225 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001226 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001227 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001228 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001229
srs5694cb76c672010-02-11 22:22:22 -05001230 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001231
srs5694cb76c672010-02-11 22:22:22 -05001232 // Check backup file size and rebuild second header if file is right
1233 // size to be direct dd copy of MBR, main header, and main partition
1234 // table; if other size, treat it like a GPT fdisk-generated backup
1235 // file
1236 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1237 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1238 if (shortBackup) {
1239 RebuildSecondHeader();
1240 secondCrcOk = mainCrcOk;
1241 } else {
1242 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1243 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001244
srs5694e7b4ff92009-08-18 13:16:10 -04001245 // Return valid headers code: 0 = both headers bad; 1 = main header
1246 // good, backup bad; 2 = backup header good, main header bad;
1247 // 3 = both headers good. Note these codes refer to valid GPT
1248 // signatures and version numbers; more subtle problems will elude
1249 // this check!
1250 if ((val = CheckHeaderValidity()) > 0) {
1251 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001252 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001253 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001254 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001255 } // if/else
1256
srs5694e7b4ff92009-08-18 13:16:10 -04001257 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001258 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1259 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001260 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001261 } // if
1262
srs5694cb76c672010-02-11 22:22:22 -05001263 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1264 cerr << "Warning! Read error " << errno
1265 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001266 } else {
1267 allOK = 0;
1268 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001269 // Something went badly wrong, so blank out partitions
1270 if (allOK == 0) {
1271 cerr << "Improper backup file! Clearing all partition data!\n";
1272 ClearGPTData();
1273 protectiveMBR.MakeProtectiveMBR();
1274 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001275 } else {
1276 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001277 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001278 } // if/else
1279
srs5694e7b4ff92009-08-18 13:16:10 -04001280 return allOK;
1281} // GPTData::LoadGPTBackup()
1282
srs569408bb0da2010-02-19 17:19:55 -05001283int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001284 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001285} // GPTData::SaveMBR()
1286
1287// This function destroys the on-disk GPT structures, but NOT the on-disk
1288// MBR.
1289// Returns 1 if the operation succeeds, 0 if not.
1290int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001291 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001292 uint8_t blankSector[512];
1293 uint8_t* emptyTable;
1294
srs569401f7f082011-03-15 23:53:31 -04001295 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001296
1297 if (myDisk.OpenForWrite()) {
1298 if (!myDisk.Seek(mainHeader.currentLBA))
1299 allOK = 0;
1300 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1301 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1302 allOK = 0;
1303 } // if
1304 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1305 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001306 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001307 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001308 if (emptyTable == NULL) {
srs5694a17fe692011-09-10 20:30:20 -04001309 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
srs56946aae2a92011-06-10 01:16:51 -04001310 exit(1);
1311 } // if
srs569401f7f082011-03-15 23:53:31 -04001312 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001313 if (allOK) {
1314 sum = myDisk.Write(emptyTable, tableSize);
1315 if (sum != tableSize) {
1316 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1317 allOK = 0;
1318 } // if write failed
1319 } // if
1320 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1321 allOK = 0;
1322 if (allOK) {
1323 sum = myDisk.Write(emptyTable, tableSize);
1324 if (sum != tableSize) {
1325 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1326 << errno << "\n";
1327 allOK = 0;
1328 } // if wrong size written
1329 } // if
1330 if (!myDisk.Seek(secondHeader.currentLBA))
1331 allOK = 0;
1332 if (allOK) {
1333 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1334 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1335 allOK = 0;
1336 } // if
1337 } // if
1338 myDisk.DiskSync();
1339 myDisk.Close();
1340 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1341 << "other utilities.\n";
1342 delete[] emptyTable;
1343 } else {
srs56945a608532011-03-17 13:53:01 -04001344 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001345 } // if/else (fd != -1)
1346 return (allOK);
1347} // GPTDataTextUI::DestroyGPT()
1348
1349// Wipe MBR data from the disk (zero it out completely)
1350// Returns 1 on success, 0 on failure.
1351int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001352 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001353 uint8_t blankSector[512];
1354
srs569401f7f082011-03-15 23:53:31 -04001355 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001356
srs569401f7f082011-03-15 23:53:31 -04001357 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1358
srs569408bb0da2010-02-19 17:19:55 -05001359 if (!allOK)
1360 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1361 return allOK;
1362} // GPTData::DestroyMBR(void)
1363
srs5694e4ac11e2009-08-31 10:13:04 -04001364// Tell user whether Apple Partition Map (APM) was discovered....
1365void GPTData::ShowAPMState(void) {
1366 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001367 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001368 else
srs5694fed16d02010-01-27 23:03:40 -05001369 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001370} // GPTData::ShowAPMState()
1371
1372// Tell user about the state of the GPT data....
1373void GPTData::ShowGPTState(void) {
1374 switch (state) {
1375 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001376 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001377 break;
1378 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001379 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001380 break;
1381 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001382 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001383 break;
1384 default:
srs5694fed16d02010-01-27 23:03:40 -05001385 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001386 break;
1387 } // switch
1388} // GPTData::ShowGPTState()
1389
1390// Display the basic GPT data
1391void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001392 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001393 uint64_t temp, totalFree;
1394
srs5694fed16d02010-01-27 23:03:40 -05001395 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001396 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001397 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001398 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001399 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001400 cout << "First usable sector is " << mainHeader.firstUsableLBA
1401 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001402 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001403 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001404 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001405 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001406 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001407 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001408 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001409 } // for
1410} // GPTData::DisplayGPTData()
1411
srs5694e4ac11e2009-08-31 10:13:04 -04001412// Show detailed information on the specified partition
1413void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001414 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001415 partitions[partNum].ShowDetails(blockSize);
1416 } else {
srs5694fed16d02010-01-27 23:03:40 -05001417 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001418 } // if
1419} // GPTData::ShowPartDetails()
1420
srs5694e4ac11e2009-08-31 10:13:04 -04001421/**************************************************************************
1422 * *
1423 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1424 * (some of these functions may require user interaction) *
1425 * *
1426 **************************************************************************/
1427
srs569408bb0da2010-02-19 17:19:55 -05001428// Examines the MBR & GPT data to determine which set of data to use: the
1429// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1430// a new set of partitions (use_new). A return value of use_abort indicates
1431// that this function couldn't determine what to do. Overriding functions
1432// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001433WhichToUse GPTData::UseWhichPartitions(void) {
1434 WhichToUse which = use_new;
1435 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001436
1437 mbrState = protectiveMBR.GetValidity();
1438
1439 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001440 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001441 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1442 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001443 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001444 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1445 << "typing 'q' if you don't want to convert your MBR partitions\n"
1446 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001447 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001448 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001449 which = use_mbr;
1450 } // if
1451
1452 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001453 cout << "\n**********************************************************************\n"
1454 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1455 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001456 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001457 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001458 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1459 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001460 } // if
srs5694fed16d02010-01-27 23:03:40 -05001461 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001462 which = use_bsd;
1463 } // if
1464
1465 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001466 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001467 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001468 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001469 } // if
1470 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001471 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001472 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001473 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001474 } // if
1475 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001476 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001477 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001478 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001479 } // if
1480 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001481 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001482 } // if
1483
srs5694e4ac11e2009-08-31 10:13:04 -04001484 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001485 if (mbrState == gpt) {
1486 cout << "\a\a****************************************************************************\n"
1487 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1488 << "verification and recovery are STRONGLY recommended.\n"
1489 << "****************************************************************************\n";
1490 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001491 } else {
srs569408bb0da2010-02-19 17:19:55 -05001492 which = use_abort;
1493 } // if/else MBR says disk is GPT
1494 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001495
1496 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001497 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001498
1499 return which;
1500} // UseWhichPartitions()
1501
srs569408bb0da2010-02-19 17:19:55 -05001502// Convert MBR partition table into GPT form.
1503void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001504 int i, numToConvert;
1505 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001506
1507 // Clear out old data & prepare basics....
1508 ClearGPTData();
1509
1510 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001511 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001512 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001513 else
srs56940283dae2010-04-28 16:44:34 -04001514 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001515
1516 for (i = 0; i < numToConvert; i++) {
1517 origType = protectiveMBR.GetType(i);
1518 // don't waste CPU time trying to convert extended, hybrid protective, or
1519 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001520 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001521 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001522 partitions[i] = protectiveMBR.AsGPT(i);
1523 } // for
1524
1525 // Convert MBR into protective MBR
1526 protectiveMBR.MakeProtectiveMBR();
1527
1528 // Record that all original CRCs were OK so as not to raise flags
1529 // when doing a disk verification
1530 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001531} // GPTData::XFormPartitions()
1532
1533// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001534// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001535// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001536int GPTData::XFormDisklabel(uint32_t partNum) {
1537 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001538 int goOn = 1, numDone = 0;
1539 BSDData disklabel;
1540
srs569408bb0da2010-02-19 17:19:55 -05001541 if (GetPartRange(&low, &high) == 0) {
1542 goOn = 0;
1543 cout << "No partitions!\n";
1544 } // if
1545 if (partNum > high) {
1546 goOn = 0;
1547 cout << "Specified partition is invalid!\n";
1548 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001549
srs569408bb0da2010-02-19 17:19:55 -05001550 // If all is OK, read the disklabel and convert it.
1551 if (goOn) {
1552 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1553 partitions[partNum].GetLastLBA());
1554 if ((goOn) && (disklabel.IsDisklabel())) {
1555 numDone = XFormDisklabel(&disklabel);
1556 if (numDone == 1)
1557 cout << "Converted 1 BSD partition.\n";
1558 else
1559 cout << "Converted " << numDone << " BSD partitions.\n";
1560 } else {
1561 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1562 } // if/else
1563 } // if
1564 if (numDone > 0) { // converted partitions; delete carrier
1565 partitions[partNum].BlankPartition();
1566 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001567 return numDone;
srs569455d92612010-03-07 22:16:07 -05001568} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001569
1570// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001571int GPTData::XFormDisklabel(BSDData* disklabel) {
1572 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001573
srs569408bb0da2010-02-19 17:19:55 -05001574 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001575 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001576 partNum = FindFirstFreePart();
1577 if (partNum >= 0) {
1578 partitions[partNum] = disklabel->AsGPT(i);
1579 if (partitions[partNum].IsUsed())
1580 numDone++;
1581 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001582 } // for
srs569408bb0da2010-02-19 17:19:55 -05001583 if (partNum == -1)
1584 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001585 } // if
1586
1587 // Record that all original CRCs were OK so as not to raise flags
1588 // when doing a disk verification
1589 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1590
1591 return numDone;
1592} // GPTData::XFormDisklabel(BSDData* disklabel)
1593
srs569408bb0da2010-02-19 17:19:55 -05001594// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1595// partition has the active/bootable flag UNset and uses the GPT fdisk
1596// type code divided by 0x0100 as the MBR type code.
1597// Returns 1 if operation was 100% successful, 0 if there were ANY
1598// problems.
srs5694978041c2009-09-21 20:51:47 -04001599int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001600 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001601
srs5694978041c2009-09-21 20:51:47 -04001602 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001603 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001604 allOK = 0;
1605 } // if
srs56940283dae2010-04-28 16:44:34 -04001606 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001607 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001608 allOK = 0;
1609 } // if
1610 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001611 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001612 allOK = 0;
1613 } // if
1614 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1615 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1616 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001617 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1618 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001619 } // if
srs5694978041c2009-09-21 20:51:47 -04001620 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001621 (uint32_t) partitions[gptPart].GetLengthLBA(),
1622 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001623 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001624 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1625 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1626 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001627 allOK = 0;
1628 } // if/else
1629 return allOK;
1630} // GPTData::OnePartToMBR()
1631
srs5694e4ac11e2009-08-31 10:13:04 -04001632
1633/**********************************************************************
1634 * *
1635 * Functions that adjust GPT data structures WITHOUT user interaction *
1636 * (they may display information for the user's benefit, though) *
1637 * *
1638 **********************************************************************/
1639
1640// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001641// necessary, copies data if it already exists. If fillGPTSectors is 1
1642// (the default), rounds numEntries to fill all the sectors necessary to
1643// hold the GPT.
1644// Returns 1 if all goes well, 0 if an error is encountered.
1645int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001646 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001647 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001648 int allOK = 1;
1649
1650 // First, adjust numEntries upward, if necessary, to get a number
1651 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001652 entriesPerSector = blockSize / GPT_SIZE;
1653 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001654 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001655 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001656 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001657 } // if
1658
srs5694247657a2009-11-26 18:36:12 -05001659 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001660 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001661 // partition table, which causes problems when loading data from a RAID
1662 // array that's been expanded because this function is called when loading
1663 // data.
srs56940283dae2010-04-28 16:44:34 -04001664 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001665 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001666 if (newParts != NULL) {
1667 if (partitions != NULL) { // existing partitions; copy them over
1668 GetPartRange(&i, &high);
1669 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001670 cout << "The highest-numbered partition is " << high + 1
1671 << ", which is greater than the requested\n"
1672 << "partition table size of " << numEntries
1673 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001674 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001675 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001676 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001677 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001678 copyNum = numEntries;
1679 else
srs56940283dae2010-04-28 16:44:34 -04001680 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001681 for (i = 0; i < copyNum; i++) {
1682 newParts[i] = partitions[i];
1683 } // for
srs569401f7f082011-03-15 23:53:31 -04001684 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001685 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001686 } // if
1687 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001688 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001689 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001690 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001691 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001692 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1693 MoveSecondHeaderToEnd();
1694 if (diskSize > 0)
1695 CheckGPTSize();
1696 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001697 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001698 allOK = 0;
1699 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001700 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001701 mainHeader.numParts = numParts;
1702 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001703 return (allOK);
1704} // GPTData::SetGPTSize()
1705
1706// Blank the partition array
1707void GPTData::BlankPartitions(void) {
1708 uint32_t i;
1709
srs56940283dae2010-04-28 16:44:34 -04001710 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001711 partitions[i].BlankPartition();
1712 } // for
1713} // GPTData::BlankPartitions()
1714
srs5694ba00fed2010-01-12 18:18:36 -05001715// Delete a partition by number. Returns 1 if successful,
1716// 0 if there was a problem. Returns 1 if partition was in
1717// range, 0 if it was out of range.
1718int GPTData::DeletePartition(uint32_t partNum) {
1719 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001720 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001721
srs56940283dae2010-04-28 16:44:34 -04001722 numUsedParts = GetPartRange(&low, &high);
1723 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001724 // In case there's a protective MBR, look for & delete matching
1725 // MBR partition....
1726 startSector = partitions[partNum].GetFirstLBA();
1727 length = partitions[partNum].GetLengthLBA();
1728 protectiveMBR.DeleteByLocation(startSector, length);
1729
1730 // Now delete the GPT partition
1731 partitions[partNum].BlankPartition();
1732 } else {
srs5694fed16d02010-01-27 23:03:40 -05001733 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001734 retval = 0;
1735 } // if/else
1736 return retval;
1737} // GPTData::DeletePartition(uint32_t partNum)
1738
srs569408bb0da2010-02-19 17:19:55 -05001739// Non-interactively create a partition.
1740// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001741uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001742 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001743 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001744
1745 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001746 if (Align(&startSector)) {
1747 cout << "Information: Moved requested sector from " << origSector << " to "
1748 << startSector << " in\norder to align on " << sectorAlignment
1749 << "-sector boundaries.\n";
1750 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001751 if (IsFree(startSector) && (startSector <= endSector)) {
1752 if (FindLastInFree(startSector) >= endSector) {
1753 partitions[partNum].SetFirstLBA(startSector);
1754 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001755 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001756 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001757 } else retval = 0; // if free space until endSector
1758 } else retval = 0; // if startSector is free
1759 } else retval = 0; // if legal partition number
1760 return retval;
1761} // GPTData::CreatePartition(partNum, startSector, endSector)
1762
srs5694e4ac11e2009-08-31 10:13:04 -04001763// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001764// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001765void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001766 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001767 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001768} // GPTData::SortGPT()
1769
srs569408bb0da2010-02-19 17:19:55 -05001770// Swap the contents of two partitions.
1771// Returns 1 if successful, 0 if either partition is out of range
1772// (that is, not a legal number; either or both can be empty).
1773// Note that if partNum1 = partNum2 and this number is in range,
1774// it will be considered successful.
1775int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1776 GPTPart temp;
1777 int allOK = 1;
1778
srs56940283dae2010-04-28 16:44:34 -04001779 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001780 if (partNum1 != partNum2) {
1781 temp = partitions[partNum1];
1782 partitions[partNum1] = partitions[partNum2];
1783 partitions[partNum2] = temp;
1784 } // if
1785 } else allOK = 0; // partition numbers are valid
1786 return allOK;
1787} // GPTData::SwapPartitions()
1788
srs5694e4ac11e2009-08-31 10:13:04 -04001789// Set up data structures for entirely new set of partitions on the
1790// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001791// Note that this function does NOT clear the protectiveMBR data
1792// structure, since it may hold the original MBR partitions if the
1793// program was launched on an MBR disk, and those may need to be
1794// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001795int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001796 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001797
1798 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001799 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001800 partitions = NULL;
1801 SetGPTSize(NUM_GPT_ENTRIES);
1802
1803 // Now initialize a bunch of stuff that's static....
1804 mainHeader.signature = GPT_SIGNATURE;
1805 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001806 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001807 mainHeader.reserved = 0;
1808 mainHeader.currentLBA = UINT64_C(1);
1809 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1810 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1811 for (i = 0; i < GPT_RESERVED; i++) {
1812 mainHeader.reserved2[i] = '\0';
1813 } // for
srs56940873e9d2010-10-07 13:00:45 -04001814 if (blockSize > 0)
1815 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1816 else
1817 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001818
1819 // Now some semi-static items (computed based on end of disk)
1820 mainHeader.backupLBA = diskSize - UINT64_C(1);
1821 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1822
1823 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001824 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001825
1826 // Copy main header to backup header
1827 RebuildSecondHeader();
1828
1829 // Blank out the partitions array....
1830 BlankPartitions();
1831
1832 // Flag all CRCs as being OK....
1833 mainCrcOk = 1;
1834 secondCrcOk = 1;
1835 mainPartsCrcOk = 1;
1836 secondPartsCrcOk = 1;
1837
1838 return (goOn);
1839} // GPTData::ClearGPTData()
1840
srs5694247657a2009-11-26 18:36:12 -05001841// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001842// If the disk size has actually changed, this also adjusts the protective
1843// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001844// Used internally and called by the 'e' option on the recovery &
1845// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001846// to their arrays or to adjust data structures in restore operations
1847// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001848void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001849 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001850 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1851 if (protectiveMBR.GetValidity() == hybrid) {
1852 protectiveMBR.OptimizeEESize();
1853 RecomputeCHS();
1854 } // if
1855 if (protectiveMBR.GetValidity() == gpt)
1856 MakeProtectiveMBR();
1857 } // if
srs56948bb78762009-11-24 15:43:49 -05001858 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1859 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1860} // GPTData::FixSecondHeaderLocation()
1861
srs5694699941e2011-03-21 21:33:57 -04001862// Sets the partition's name to the specified UnicodeString without
1863// user interaction.
1864// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001865int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001866 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001867
srs5694699941e2011-03-21 21:33:57 -04001868 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001869 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001870 else
1871 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001872
1873 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001874} // GPTData::SetName
1875
1876// Set the disk GUID to the specified value. Note that the header CRCs must
1877// be recomputed after calling this function.
1878void GPTData::SetDiskGUID(GUIDData newGUID) {
1879 mainHeader.diskGUID = newGUID;
1880 secondHeader.diskGUID = newGUID;
1881} // SetDiskGUID()
1882
1883// Set the unique GUID of the specified partition. Returns 1 on
1884// successful completion, 0 if there were problems (invalid
1885// partition number).
1886int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1887 int retval = 0;
1888
srs56940283dae2010-04-28 16:44:34 -04001889 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001890 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001891 partitions[pn].SetUniqueGUID(theGUID);
1892 retval = 1;
1893 } // if
1894 } // if
1895 return retval;
1896} // GPTData::SetPartitionGUID()
1897
srs56949ba54212010-05-18 23:24:02 -04001898// Set new random GUIDs for the disk and all partitions. Intended to be used
1899// after disk cloning or similar operations that don't randomize the GUIDs.
1900void GPTData::RandomizeGUIDs(void) {
1901 uint32_t i;
1902
1903 mainHeader.diskGUID.Randomize();
1904 secondHeader.diskGUID = mainHeader.diskGUID;
1905 for (i = 0; i < numParts; i++)
1906 if (partitions[i].IsUsed())
1907 partitions[i].RandomizeUniqueGUID();
1908} // GPTData::RandomizeGUIDs()
1909
srs5694ba00fed2010-01-12 18:18:36 -05001910// Change partition type code non-interactively. Returns 1 if
1911// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001912int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1913 int retval = 1;
1914
1915 if (!IsFreePartNum(partNum)) {
1916 partitions[partNum].SetType(theGUID);
1917 } else retval = 0;
1918 return retval;
1919} // GPTData::ChangePartType()
1920
srs56949ba54212010-05-18 23:24:02 -04001921// Recompute the CHS values of all the MBR partitions. Used to reset
1922// CHS values that some BIOSes require, despite the fact that the
1923// resulting CHS values violate the GPT standard.
1924void GPTData::RecomputeCHS(void) {
1925 int i;
1926
1927 for (i = 0; i < 4; i++)
1928 protectiveMBR.RecomputeCHS(i);
1929} // GPTData::RecomputeCHS()
1930
srs56941d1448a2009-12-31 21:20:19 -05001931// Adjust sector number so that it falls on a sector boundary that's a
1932// multiple of sectorAlignment. This is done to improve the performance
1933// of Western Digital Advanced Format disks and disks with similar
1934// technology from other companies, which use 4096-byte sectors
1935// internally although they translate to 512-byte sectors for the
1936// benefit of the OS. If partitions aren't properly aligned on these
1937// disks, some filesystem data structures can span multiple physical
1938// sectors, degrading performance. This function should be called
1939// only on the FIRST sector of the partition, not the last!
1940// This function returns 1 if the alignment was altered, 0 if it
1941// was unchanged.
1942int GPTData::Align(uint64_t* sector) {
1943 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001944 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001945
1946 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001947 earlier = (*sector / sectorAlignment) * sectorAlignment;
1948 later = earlier + (uint64_t) sectorAlignment;
1949
1950 // Check to see that every sector between the earlier one and the
1951 // requested one is clear, and that it's not too early....
1952 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001953 sectorOK = 1;
1954 testSector = earlier;
1955 do {
1956 sectorOK = IsFree(testSector++);
1957 } while ((sectorOK == 1) && (testSector < *sector));
1958 if (sectorOK == 1) {
1959 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001960 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001961 } // if
1962 } // if firstUsableLBA check
1963
1964 // If couldn't move the sector earlier, try to move it later instead....
1965 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1966 sectorOK = 1;
1967 testSector = later;
1968 do {
1969 sectorOK = IsFree(testSector--);
1970 } while ((sectorOK == 1) && (testSector > *sector));
1971 if (sectorOK == 1) {
1972 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001973 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001974 } // if
1975 } // if
srs56941d1448a2009-12-31 21:20:19 -05001976 } // if
1977 return retval;
1978} // GPTData::Align()
1979
srs5694e4ac11e2009-08-31 10:13:04 -04001980/********************************************************
1981 * *
1982 * Functions that return data about GPT data structures *
1983 * (most of these are inline in gpt.h) *
1984 * *
1985 ********************************************************/
1986
1987// Find the low and high used partition numbers (numbered from 0).
1988// Return value is the number of partitions found. Note that the
1989// *low and *high values are both set to 0 when no partitions
1990// are found, as well as when a single partition in the first
1991// position exists. Thus, the return value is the only way to
1992// tell when no partitions exist.
1993int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1994 uint32_t i;
1995 int numFound = 0;
1996
srs56940283dae2010-04-28 16:44:34 -04001997 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001998 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001999 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002000 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04002001 *high = i; // since we're counting up, set the high value
2002 // Set the low value only if it's not yet found...
2003 if (*low == (numParts + 1)) *low = i;
2004 numFound++;
2005 } // if
2006 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04002007
2008 // Above will leave *low pointing to its "not found" value if no partitions
2009 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002010 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002011 *low = 0;
2012 return numFound;
2013} // GPTData::GetPartRange()
2014
srs569408bb0da2010-02-19 17:19:55 -05002015// Returns the value of the first free partition, or -1 if none is
2016// unused.
2017int GPTData::FindFirstFreePart(void) {
2018 int i = 0;
2019
2020 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002021 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002022 i++;
srs56940283dae2010-04-28 16:44:34 -04002023 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002024 i = -1;
2025 } else i = -1;
2026 return i;
2027} // GPTData::FindFirstFreePart()
2028
srs5694978041c2009-09-21 20:51:47 -04002029// Returns the number of defined partitions.
2030uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002031 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002032
srs56940283dae2010-04-28 16:44:34 -04002033 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002034 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002035 counted++;
2036 } // for
2037 return counted;
2038} // GPTData::CountParts()
2039
srs5694e4ac11e2009-08-31 10:13:04 -04002040/****************************************************
2041 * *
2042 * Functions that return data about disk free space *
2043 * *
2044 ****************************************************/
2045
2046// Find the first available block after the starting point; returns 0 if
2047// there are no available blocks left
2048uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2049 uint64_t first;
2050 uint32_t i;
2051 int firstMoved = 0;
2052
2053 // Begin from the specified starting point or from the first usable
2054 // LBA, whichever is greater...
2055 if (start < mainHeader.firstUsableLBA)
2056 first = mainHeader.firstUsableLBA;
2057 else
2058 first = start;
2059
2060 // ...now search through all partitions; if first is within an
2061 // existing partition, move it to the next sector after that
2062 // partition and repeat. If first was moved, set firstMoved
2063 // flag; repeat until firstMoved is not set, so as to catch
2064 // cases where partitions are out of sequential order....
2065 do {
2066 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002067 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002068 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002069 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002070 first = partitions[i].GetLastLBA() + 1;
2071 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002072 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002073 } // for
2074 } while (firstMoved == 1);
2075 if (first > mainHeader.lastUsableLBA)
2076 first = 0;
2077 return (first);
2078} // GPTData::FindFirstAvailable()
2079
2080// Finds the first available sector in the largest block of unallocated
2081// space on the disk. Returns 0 if there are no available blocks left
2082uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002083 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002084
2085 start = 0;
2086 do {
2087 firstBlock = FindFirstAvailable(start);
2088 if (firstBlock != UINT32_C(0)) { // something's free...
2089 lastBlock = FindLastInFree(firstBlock);
2090 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2091 if (segmentSize > selectedSize) {
2092 selectedSize = segmentSize;
2093 selectedSegment = firstBlock;
2094 } // if
2095 start = lastBlock + 1;
2096 } // if
2097 } while (firstBlock != 0);
2098 return selectedSegment;
2099} // GPTData::FindFirstInLargest()
2100
srs5694cb76c672010-02-11 22:22:22 -05002101// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002102// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002103uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002104 uint64_t last;
2105 uint32_t i;
2106 int lastMoved = 0;
2107
2108 // Start by assuming the last usable LBA is available....
2109 last = mainHeader.lastUsableLBA;
2110
2111 // ...now, similar to algorithm in FindFirstAvailable(), search
2112 // through all partitions, moving last when it's in an existing
2113 // partition. Set the lastMoved flag so we repeat to catch cases
2114 // where partitions are out of logical order.
2115 do {
2116 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002117 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002118 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002119 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002120 last = partitions[i].GetFirstLBA() - 1;
2121 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002122 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002123 } // for
2124 } while (lastMoved == 1);
2125 if (last < mainHeader.firstUsableLBA)
2126 last = 0;
2127 return (last);
2128} // GPTData::FindLastAvailable()
2129
2130// Find the last available block in the free space pointed to by start.
2131uint64_t GPTData::FindLastInFree(uint64_t start) {
2132 uint64_t nearestStart;
2133 uint32_t i;
2134
2135 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002136 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002137 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002138 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002139 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002140 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002141 } // for
2142 return (nearestStart);
2143} // GPTData::FindLastInFree()
2144
2145// Finds the total number of free blocks, the number of segments in which
2146// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002147uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002148 uint64_t start = UINT64_C(0); // starting point for each search
2149 uint64_t totalFound = UINT64_C(0); // running total
2150 uint64_t firstBlock; // first block in a segment
2151 uint64_t lastBlock; // last block in a segment
2152 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002153 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002154
2155 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002156 if (diskSize > 0) {
2157 do {
2158 firstBlock = FindFirstAvailable(start);
2159 if (firstBlock != UINT64_C(0)) { // something's free...
2160 lastBlock = FindLastInFree(firstBlock);
2161 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2162 if (segmentSize > *largestSegment) {
2163 *largestSegment = segmentSize;
2164 } // if
2165 totalFound += segmentSize;
2166 num++;
2167 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002168 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002169 } while (firstBlock != 0);
2170 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002171 *numSegments = num;
2172 return totalFound;
2173} // GPTData::FindFreeBlocks()
2174
srs569455d92612010-03-07 22:16:07 -05002175// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2176// If it's allocated, return the partition number to which it's allocated
2177// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2178// returned in partNum if the sector is in use by basic GPT data structures.)
2179int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002180 int isFree = 1;
2181 uint32_t i;
2182
srs56940283dae2010-04-28 16:44:34 -04002183 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002184 if ((sector >= partitions[i].GetFirstLBA()) &&
2185 (sector <= partitions[i].GetLastLBA())) {
2186 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002187 if (partNum != NULL)
2188 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002189 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002190 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002191 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002192 (sector > mainHeader.lastUsableLBA)) {
2193 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002194 if (partNum != NULL)
2195 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002196 } // if
2197 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002198} // GPTData::IsFree()
2199
srs5694815fb652011-03-18 12:35:56 -04002200// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002201int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002202 return ((partNum < numParts) && (partitions != NULL) &&
2203 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002204} // GPTData::IsFreePartNum()
2205
srs5694815fb652011-03-18 12:35:56 -04002206// Returns 1 if partNum is in use.
2207int GPTData::IsUsedPartNum(uint32_t partNum) {
2208 return ((partNum < numParts) && (partitions != NULL) &&
2209 (partitions[partNum].IsUsed()));
2210} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002211
2212/***********************************************************
2213 * *
2214 * Change how functions work or return information on them *
2215 * *
2216 ***********************************************************/
2217
2218// Set partition alignment value; partitions will begin on multiples of
2219// the specified value
2220void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002221 if (n > 0)
2222 sectorAlignment = n;
2223 else
2224 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002225} // GPTData::SetAlignment()
2226
2227// Compute sector alignment based on the current partitions (if any). Each
2228// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002229// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2230// sector size), but not by the previously-located alignment value, then the
2231// alignment value is adjusted down. If the computed alignment is less than 8
2232// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002233// is a safety measure for Advanced Format drives. If no partitions are
2234// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002235// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002236// drives are aligned to 2048-sector multiples but the program won't complain
2237// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002238// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002239// Returns the computed alignment value.
2240uint32_t GPTData::ComputeAlignment(void) {
2241 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002242 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002243
srs56940873e9d2010-10-07 13:00:45 -04002244 if (blockSize > 0)
2245 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2246 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002247 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002248 if (partitions[i].IsUsed()) {
2249 found = 0;
2250 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002251 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002252 if ((partitions[i].GetFirstLBA() % align) == 0) {
2253 found = 1;
2254 } else {
2255 exponent--;
2256 } // if/else
2257 } // while
2258 } // if
2259 } // for
srs56940873e9d2010-10-07 13:00:45 -04002260 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2261 align = MIN_AF_ALIGNMENT;
2262 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002263 return align;
2264} // GPTData::ComputeAlignment()
2265
srs5694e4ac11e2009-08-31 10:13:04 -04002266/********************************
2267 * *
2268 * Endianness support functions *
2269 * *
2270 ********************************/
2271
srs56942a9f5da2009-08-26 00:48:01 -04002272void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002273 ReverseBytes(&header->signature, 8);
2274 ReverseBytes(&header->revision, 4);
2275 ReverseBytes(&header->headerSize, 4);
2276 ReverseBytes(&header->headerCRC, 4);
2277 ReverseBytes(&header->reserved, 4);
2278 ReverseBytes(&header->currentLBA, 8);
2279 ReverseBytes(&header->backupLBA, 8);
2280 ReverseBytes(&header->firstUsableLBA, 8);
2281 ReverseBytes(&header->lastUsableLBA, 8);
2282 ReverseBytes(&header->partitionEntriesLBA, 8);
2283 ReverseBytes(&header->numParts, 4);
2284 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2285 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002286 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002287} // GPTData::ReverseHeaderBytes()
2288
srs56940283dae2010-04-28 16:44:34 -04002289// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002290void GPTData::ReversePartitionBytes() {
2291 uint32_t i;
2292
srs56940283dae2010-04-28 16:44:34 -04002293 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002294 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002295 } // for
2296} // GPTData::ReversePartitionBytes()
2297
srs56949ddc14b2010-08-22 22:44:42 -04002298// Validate partition number
2299bool GPTData::ValidPartNum (const uint32_t partNum) {
2300 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002301 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002302 return false;
2303 } // if
2304 return true;
2305} // GPTData::ValidPartNum
2306
srs56945a081752010-09-24 20:39:41 -04002307// Return a single partition for inspection (not modification!) by other
2308// functions.
2309const GPTPart & GPTData::operator[](uint32_t partNum) const {
2310 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002311 cerr << "Partition number out of range (" << partNum << " requested, but only "
2312 << numParts << " available)\n";
2313 exit(1);
2314 } // if
2315 if (partitions == NULL) {
2316 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2317 exit(1);
srs56945a081752010-09-24 20:39:41 -04002318 } // if
2319 return partitions[partNum];
2320} // operator[]
2321
2322// Return (not for modification!) the disk's GUID value
2323const GUIDData & GPTData::GetDiskGUID(void) const {
2324 return mainHeader.diskGUID;
2325} // GPTData::GetDiskGUID()
2326
srs56949ddc14b2010-08-22 22:44:42 -04002327// Manage attributes for a partition, based on commands passed to this function.
2328// (Function is non-interactive.)
2329// Returns 1 if a modification command succeeded, 0 if the command should not have
2330// modified data, and -1 if a modification command failed.
2331int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2332 int retval = 0;
2333 Attributes theAttr;
2334
2335 if (command == "show") {
2336 ShowAttributes(partNum);
2337 } else if (command == "get") {
2338 GetAttribute(partNum, bits);
2339 } else {
2340 theAttr = partitions[partNum].GetAttributes();
2341 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2342 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2343 retval = 1;
2344 } else {
2345 retval = -1;
2346 } // if/else
2347 } // if/elseif/else
2348
2349 return retval;
2350} // GPTData::ManageAttributes()
2351
2352// Show all attributes for a specified partition....
2353void GPTData::ShowAttributes(const uint32_t partNum) {
srs5694e69e6802012-01-20 22:37:12 -05002354 if (partitions[partNum].IsUsed())
2355 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002356} // GPTData::ShowAttributes
2357
2358// Show whether a single attribute bit is set (terse output)...
2359void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002360 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002361} // GPTData::GetAttribute
2362
2363
srs56942a9f5da2009-08-26 00:48:01 -04002364/******************************************
2365 * *
2366 * Additional non-class support functions *
2367 * *
2368 ******************************************/
2369
srs5694e7b4ff92009-08-18 13:16:10 -04002370// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2371// never fail these tests, but the struct types may fail depending on compile options.
2372// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2373// sizes.
2374int SizesOK(void) {
2375 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002376
2377 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002378 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002379 allOK = 0;
2380 } // if
2381 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002382 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002383 allOK = 0;
2384 } // if
2385 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002386 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002387 allOK = 0;
2388 } // if
2389 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002390 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002391 allOK = 0;
2392 } // if
2393 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002394 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002395 allOK = 0;
2396 } // if
srs5694978041c2009-09-21 20:51:47 -04002397 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002398 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002399 allOK = 0;
2400 } // if
2401 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002402 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002403 allOK = 0;
2404 } // if
srs5694221e0872009-08-29 15:00:31 -04002405 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002406 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002407 allOK = 0;
2408 } // if
srs56946699b012010-02-04 00:55:30 -05002409 if (sizeof(GUIDData) != 16) {
2410 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2411 allOK = 0;
2412 } // if
2413 if (sizeof(PartType) != 16) {
2414 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2415 allOK = 0;
2416 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002417 return (allOK);
2418} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002419