blob: d584397d46683ce87c50716ad915faa10f9023c1 [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
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500294 if (!protectiveMBR.DoTheyFit()) {
295 cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
296 << "fresh protective or hybrid MBR is recommended.\n";
297 problems++;
298 }
299
srs56941d1448a2009-12-31 21:20:19 -0500300 // Check that partitions are aligned on proper boundaries (for WD Advanced
301 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400302 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500303 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500304 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
305 << sectorAlignment << "-sector boundary. This may\nresult "
306 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500307 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500308 } // if
309 } // for
srs569464cbd172011-03-01 22:03:54 -0500310 if (alignProbs > 0)
311 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
312 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500313
srs5694e4ac11e2009-08-31 10:13:04 -0400314 // Now compute available space, but only if no problems found, since
315 // problems could affect the results
316 if (problems == 0) {
317 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500318 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400319 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500320 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400321 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400322 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400323 } else {
srs56940a697312010-01-28 21:10:52 -0500324 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400325 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400326
327 return (problems);
328} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400329
330// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400331// do, issues a warning but takes no action. Returns number of problems
332// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400333int GPTData::CheckGPTSize(void) {
334 uint64_t overlap, firstUsedBlock, lastUsedBlock;
335 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400336 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400337
338 // first, locate the first & last used blocks
339 firstUsedBlock = UINT64_MAX;
340 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400341 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500342 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500343 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500344 firstUsedBlock = partitions[i].GetFirstLBA();
345 if (partitions[i].GetLastLBA() > lastUsedBlock) {
346 lastUsedBlock = partitions[i].GetLastLBA();
347 } // if
348 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400349 } // for
350
351 // If the disk size is 0 (the default), then it means that various
352 // variables aren't yet set, so the below tests will be useless;
353 // therefore we should skip everything
354 if (diskSize != 0) {
355 if (mainHeader.firstUsableLBA > firstUsedBlock) {
356 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500357 cout << "Warning! Main partition table overlaps the first partition by "
358 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400359 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500360 cout << "Try reducing the partition table size by " << overlap * 4
361 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400362 } else {
srs5694fed16d02010-01-27 23:03:40 -0500363 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400364 } // if/else
365 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400366 } // Problem at start of disk
367 if (mainHeader.lastUsableLBA < lastUsedBlock) {
368 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500369 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500370 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400371 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500372 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400373 } else {
srs5694fed16d02010-01-27 23:03:40 -0500374 cout << "Try reducing the partition table size by " << overlap * 4
375 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400376 } // if/else
377 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400378 } // Problem at end of disk
379 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400380 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400381} // GPTData::CheckGPTSize()
382
srs5694e7b4ff92009-08-18 13:16:10 -0400383// Check the validity of the GPT header. Returns 1 if the main header
384// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400385// 0 if neither is valid. Note that this function checks the GPT signature,
386// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400387int GPTData::CheckHeaderValidity(void) {
388 int valid = 3;
389
srs5694fed16d02010-01-27 23:03:40 -0500390 cout.setf(ios::uppercase);
391 cout.fill('0');
392
393 // Note: failed GPT signature checks produce no error message because
394 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400395 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400396 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400397 } else if ((mainHeader.revision != 0x00010000) && valid) {
398 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500399 cout << "Unsupported GPT version in main header; read 0x";
400 cout.width(8);
401 cout << hex << mainHeader.revision << ", should be\n0x";
402 cout.width(8);
403 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400404 } // if/else/if
405
srs5694d1b11e82011-09-18 21:12:28 -0400406 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400407 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400408 } else if ((secondHeader.revision != 0x00010000) && valid) {
409 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500410 cout << "Unsupported GPT version in backup header; read 0x";
411 cout.width(8);
412 cout << hex << secondHeader.revision << ", should be\n0x";
413 cout.width(8);
414 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400415 } // if/else/if
416
srs5694df9d3632011-01-08 18:33:24 -0500417 // Check for an Apple disk signature
418 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
419 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400420 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500421 } // if
srs5694fed16d02010-01-27 23:03:40 -0500422 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400423
srs5694fed16d02010-01-27 23:03:40 -0500424 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400425} // GPTData::CheckHeaderValidity()
426
427// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400428// Note: Must be called with header in platform-ordered byte order.
429// Returns 1 if header's computed CRC matches the stored value, 0 if the
430// computed and stored values don't match
431int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400432 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400433 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400434
srs56942a9f5da2009-08-26 00:48:01 -0400435 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400436 // computation to be valid
437 oldCRC = header->headerCRC;
438 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400439
srs5694978041c2009-09-21 20:51:47 -0400440 hSize = header->headerSize;
441
srs5694d1b11e82011-09-18 21:12:28 -0400442 if (IsLittleEndian() == 0)
443 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400444
srs5694d1b11e82011-09-18 21:12:28 -0400445 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
446 if (warn) {
447 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
448 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
449 } // if
450 hSize = HEADER_SIZE;
451 } else if ((hSize > sizeof(GPTHeader)) && warn) {
452 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
453 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
454 << "which may result in a CRC false alarm.\n";
455 } // if/elseif
456 temp = new uint8_t[hSize];
457 if (temp != NULL) {
458 memset(temp, 0, hSize);
459 if (hSize < sizeof(GPTHeader))
460 memcpy(temp, header, hSize);
461 else
462 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400463
srs5694d1b11e82011-09-18 21:12:28 -0400464 newCRC = chksum_crc32((unsigned char*) temp, hSize);
465 delete[] temp;
466 } else {
467 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
468 exit(1);
469 }
470 if (IsLittleEndian() == 0)
471 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400472 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400473 return (oldCRC == newCRC);
474} // GPTData::CheckHeaderCRC()
475
srs56946699b012010-02-04 00:55:30 -0500476// Recompute all the CRCs. Must be called before saving if any changes have
477// been made. Must be called on platform-ordered data (this function reverses
478// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400479void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400480 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400481 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400482
srs5694d1b11e82011-09-18 21:12:28 -0400483 // If the header size is bigger than the GPT header data structure, reset it;
484 // otherwise, set both header sizes to whatever the main one is....
485 if (mainHeader.headerSize > sizeof(GPTHeader))
486 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
487 else
488 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500489
490 if ((littleEndian = IsLittleEndian()) == 0) {
491 ReversePartitionBytes();
492 ReverseHeaderBytes(&mainHeader);
493 ReverseHeaderBytes(&secondHeader);
494 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400495
srs5694e7b4ff92009-08-18 13:16:10 -0400496 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400497 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400498 mainHeader.partitionEntriesCRC = crc;
499 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400500 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400501 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
502 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400503 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400504
srs5694d1b11e82011-09-18 21:12:28 -0400505 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400506 mainHeader.headerCRC = 0;
507 secondHeader.headerCRC = 0;
508
srs5694978041c2009-09-21 20:51:47 -0400509 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400510 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400511 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400512 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400513 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400514 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400515 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400516 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500517
srs5694d1b11e82011-09-18 21:12:28 -0400518 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500519 ReverseHeaderBytes(&mainHeader);
520 ReverseHeaderBytes(&secondHeader);
521 ReversePartitionBytes();
522 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400523} // GPTData::RecomputeCRCs()
524
srs5694e7b4ff92009-08-18 13:16:10 -0400525// Rebuild the main GPT header, using the secondary header as a model.
526// Typically called when the main header has been found to be corrupt.
527void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400528 mainHeader.signature = GPT_SIGNATURE;
529 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400530 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400531 mainHeader.headerCRC = UINT32_C(0);
532 mainHeader.reserved = secondHeader.reserved;
533 mainHeader.currentLBA = secondHeader.backupLBA;
534 mainHeader.backupLBA = secondHeader.currentLBA;
535 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
536 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500537 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400538 mainHeader.partitionEntriesLBA = UINT64_C(2);
539 mainHeader.numParts = secondHeader.numParts;
540 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
541 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400542 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500543 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500544 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400545} // GPTData::RebuildMainHeader()
546
547// Rebuild the secondary GPT header, using the main header as a model.
548void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400549 secondHeader.signature = GPT_SIGNATURE;
550 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400551 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400552 secondHeader.headerCRC = UINT32_C(0);
553 secondHeader.reserved = mainHeader.reserved;
554 secondHeader.currentLBA = mainHeader.backupLBA;
555 secondHeader.backupLBA = mainHeader.currentLBA;
556 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
557 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500558 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400559 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
560 secondHeader.numParts = mainHeader.numParts;
561 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
562 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400563 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500564 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500565 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400566} // GPTData::RebuildSecondHeader()
567
568// Search for hybrid MBR entries that have no corresponding GPT partition.
569// Returns number of such mismatches found
570int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500571 int i, found, numFound = 0;
572 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400573 uint64_t mbrFirst, mbrLast;
574
575 for (i = 0; i < 4; i++) {
576 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
577 j = 0;
578 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400579 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
580 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400581 do {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -0400582 if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500583 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400584 found = 1;
585 j++;
srs56940283dae2010-04-28 16:44:34 -0400586 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400587 if (!found) {
588 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500589 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
590 << i + 1 << ", of type 0x";
591 cout.fill('0');
592 cout.setf(ios::uppercase);
593 cout.width(2);
594 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
595 << "has no corresponding GPT partition! You may continue, but this condition\n"
596 << "might cause data loss in the future!\a\n" << dec;
597 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400598 } // if
599 } // if
600 } // for
601 return numFound;
602} // GPTData::FindHybridMismatches
603
604// Find overlapping partitions and warn user about them. Returns number of
605// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400606// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400607int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500608 int problems = 0;
609 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400610
srs56940283dae2010-04-28 16:44:34 -0400611 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400612 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500613 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
614 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400615 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500616 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
617 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
618 << " to " << partitions[i].GetLastLBA() << "\n";
619 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
620 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400621 } // if
622 } // for j...
623 } // for i...
624 return problems;
625} // GPTData::FindOverlaps()
626
srs569455d92612010-03-07 22:16:07 -0500627// Find partitions that are insane -- they start after they end or are too
628// big for the disk. (The latter should duplicate detection of overlaps
629// with GPT backup data structures, but better to err on the side of
630// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400631// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500632int GPTData::FindInsanePartitions(void) {
633 uint32_t i;
634 int problems = 0;
635
srs56940283dae2010-04-28 16:44:34 -0400636 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500637 if (partitions[i].IsUsed()) {
638 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
639 problems++;
640 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
641 } // if
642 if (partitions[i].GetLastLBA() >= diskSize) {
643 problems++;
644 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
645 } // if
srs569455d92612010-03-07 22:16:07 -0500646 } // if
647 } // for
648 return problems;
649} // GPTData::FindInsanePartitions(void)
650
651
srs5694e4ac11e2009-08-31 10:13:04 -0400652/******************************************************************
653 * *
654 * Begin functions that load data from disk or save data to disk. *
655 * *
656 ******************************************************************/
657
srs569464cbd172011-03-01 22:03:54 -0500658// Change the filename associated with the GPT. Used for duplicating
659// the partition table to a new disk and saving backups.
660// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500661int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500662 int err, allOK = 1;
663
664 device = deviceFilename;
665 if (allOK && myDisk.OpenForRead(deviceFilename)) {
666 // store disk information....
667 diskSize = myDisk.DiskSize(&err);
668 blockSize = (uint32_t) myDisk.GetBlockSize();
669 } // if
670 protectiveMBR.SetDisk(&myDisk);
671 protectiveMBR.SetDiskSize(diskSize);
672 protectiveMBR.SetBlockSize(blockSize);
673 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500674} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500675
srs5694e4ac11e2009-08-31 10:13:04 -0400676// Scan for partition data. This function loads the MBR data (regular MBR or
677// protective MBR) and loads BSD disklabel data (which is probably invalid).
678// It also looks for APM data, forces a load of GPT data, and summarizes
679// the results.
srs5694546a9c72010-01-26 16:00:26 -0500680void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400681 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400682
683 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500684 protectiveMBR.ReadMBRData(&myDisk);
685 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400686
687 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500688 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500689
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500690 // Some tools create a 0xEE partition that's too big. If this is detected,
691 // normalize it....
692 if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
693 if (!beQuiet) {
694 cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
695 } // if
696 protectiveMBR.MakeProtectiveMBR();
697 } // if
698
srs5694ba00fed2010-01-12 18:18:36 -0500699 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500700 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500701 protectiveMBR.ShowState();
702 bsdDisklabel.ShowState();
703 ShowAPMState(); // Show whether there's an Apple Partition Map present
704 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500705 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500706 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400707
708 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500709 cout << "\n*******************************************************************\n"
710 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500711 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500712 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500713 } // if
srs5694fed16d02010-01-27 23:03:40 -0500714 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400715 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400716} // GPTData::PartitionScan()
717
718// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500719int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500720 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500721 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500722 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400723
srs5694546a9c72010-01-26 16:00:26 -0500724 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500725 err = myDisk.OpenForWrite(deviceFilename);
726 if ((err == 0) && (!justLooking)) {
727 cout << "\aNOTE: Write test failed with error number " << errno
728 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
729#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
730 cout << "You may be able to enable writes by exiting this program, typing\n"
731 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
732 << "program.\n";
733#endif
734 cout << "\n";
735 } // if
736 myDisk.Close(); // Close and re-open read-only in case of bugs
737 } else allOK = 0; // if
738
739 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400740 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500741 diskSize = myDisk.DiskSize(&err);
742 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500743 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500744 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400745
srs5694ba00fed2010-01-12 18:18:36 -0500746 whichWasUsed = UseWhichPartitions();
747 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400748 case use_mbr:
749 XFormPartitions();
750 break;
751 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500752 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400753// bsdDisklabel.DisplayBSDData();
754 ClearGPTData();
755 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500756 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400757 break;
758 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500759 mbrState = protectiveMBR.GetValidity();
760 if ((mbrState == invalid) || (mbrState == mbr))
761 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400762 break;
763 case use_new:
764 ClearGPTData();
765 protectiveMBR.MakeProtectiveMBR();
766 break;
srs56943c0af382010-01-15 19:19:18 -0500767 case use_abort:
768 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400769 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500770 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400771 } // switch
772
srs569455d92612010-03-07 22:16:07 -0500773 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500774 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500775 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400776 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400777 } else {
778 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400779 } // if/else
780 return (allOK);
781} // GPTData::LoadPartitions()
782
783// Loads the GPT, as much as possible. Returns 1 if this seems to have
784// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500785int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500786 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400787
srs5694cb76c672010-02-11 22:22:22 -0500788 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400789
srs5694cb76c672010-02-11 22:22:22 -0500790 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
791 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
792 } else {
srs569408bb0da2010-02-19 17:19:55 -0500793 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
794 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500795 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
796 << "secondary header from the last sector of the disk! You should use 'v' to\n"
797 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
798 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500799 } // if/else
800 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400801 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400802
803 // Return valid headers code: 0 = both headers bad; 1 = main header
804 // good, backup bad; 2 = backup header good, main header bad;
805 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400806 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400807 validHeaders = CheckHeaderValidity();
808
809 // Read partitions (from primary array)
810 if (validHeaders > 0) { // if at least one header is OK....
811 // GPT appears to be valid....
812 state = gpt_valid;
813
814 // We're calling the GPT valid, but there's a possibility that one
815 // of the two headers is corrupt. If so, use the one that seems to
816 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500817 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500818 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
819 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400820 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500821 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400822 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500823 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500824 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
825 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500826 RebuildMainHeader();
827 state = gpt_corrupt;
828 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400829 } // if/else/if
830
srs5694546a9c72010-01-26 16:00:26 -0500831 // Figure out which partition table to load....
832 // Load the main partition table, since either its header's CRC is OK or the
833 // backup header's CRC is not OK....
834 if (mainCrcOk || !secondCrcOk) {
835 if (LoadMainTable() == 0)
836 allOK = 0;
837 } else { // bad main header CRC and backup header CRC is OK
838 state = gpt_corrupt;
839 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500840 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500841 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500842 } else { // backup table bad, bad main header CRC, but try main table in desperation....
843 if (LoadMainTable() == 0) {
844 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500845 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500846 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500847 } // if
848 } // if/else (LoadSecondTableAsMain())
849 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400850
srs5694cb76c672010-02-11 22:22:22 -0500851 if (loadedTable == 1)
852 secondPartsCrcOk = CheckTable(&secondHeader);
853 else if (loadedTable == 2)
854 mainPartsCrcOk = CheckTable(&mainHeader);
855 else
856 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400857
srs5694546a9c72010-01-26 16:00:26 -0500858 // Problem with main partition table; if backup is OK, use it instead....
859 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
860 state = gpt_corrupt;
861 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500862 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500863 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
864 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500865 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500866
srs5694e4ac11e2009-08-31 10:13:04 -0400867 // Check for valid CRCs and warn if there are problems
868 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
869 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500870 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400871 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500872 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400873 } else {
874 state = gpt_invalid;
875 } // if/else
876 return allOK;
877} // GPTData::ForceLoadGPTData()
878
srs5694247657a2009-11-26 18:36:12 -0500879// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400880// main GPT header in memory MUST be valid for this call to do anything
881// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500882// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400883int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500884 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400885} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400886
887// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500888// table. Used in repair functions, and when starting up if the main
889// partition table is damaged.
890// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
891int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500892 return LoadPartitionTable(secondHeader, myDisk);
893} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400894
srs5694cb76c672010-02-11 22:22:22 -0500895// Load a single GPT header (main or backup) from the specified disk device and
896// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
897// value appropriately.
898// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
899// failure.
900int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
901 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500902 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500903
904 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500905 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500906 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
907 allOK = 0;
908 } // if
srs5694cb76c672010-02-11 22:22:22 -0500909
srs56941c6f8b02010-02-21 11:09:20 -0500910 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500911 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500912 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500913 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400914 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500915
srs56940283dae2010-04-28 16:44:34 -0400916 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500917 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500918 }
srs56941c6f8b02010-02-21 11:09:20 -0500919
920 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500921 return allOK;
922} // GPTData::LoadHeader
923
924// Load a partition table (either main or secondary) from the specified disk,
925// using header as a reference for what to load. If sector != 0 (the default
926// is 0), loads from the specified sector; otherwise loads from the sector
927// indicated in header.
928// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
929int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
930 uint32_t sizeOfParts, newCRC;
931 int retval;
932
933 if (disk.OpenForRead()) {
934 if (sector == 0) {
935 retval = disk.Seek(header.partitionEntriesLBA);
936 } else {
937 retval = disk.Seek(sector);
938 } // if/else
srs569455d92612010-03-07 22:16:07 -0500939 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500940 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500941 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500942 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
943 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500944 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500945 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500946 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400947 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500948 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400949 if (IsLittleEndian() == 0)
950 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500951 if (!mainPartsCrcOk) {
952 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400953 } // if
954 } else {
srs5694cb76c672010-02-11 22:22:22 -0500955 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400956 } // if/else
957 } else {
srs5694fed16d02010-01-27 23:03:40 -0500958 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500959 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500960 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400961 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500962 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500963} // GPTData::LoadPartitionsTable()
964
965// Check the partition table pointed to by header, but don't keep it
966// around.
srs5694a17fe692011-09-10 20:30:20 -0400967// Returns 1 if the CRC is OK & this table matches the one already in memory,
968// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500969int GPTData::CheckTable(struct GPTHeader *header) {
970 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400971 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400972 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400973 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500974
srs56940283dae2010-04-28 16:44:34 -0400975 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500976 // its CRC and store the results, then discard this temporary
977 // storage, since we don't use it in any but recovery operations
978 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400979 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400980 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -0400981 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -0400982 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
983 exit(1);
984 } // if
srs5694a17fe692011-09-10 20:30:20 -0400985 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400986 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500987 } else {
srs5694d1b11e82011-09-18 21:12:28 -0400988 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -0400989 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -0400990 if (header == &mainHeader)
991 otherHeader = &secondHeader;
992 else
993 otherHeader = &mainHeader;
994 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -0400995 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
996 << "on the recovery & transformation menu to examine the two tables.\n\n";
997 allOK = 0;
998 } // if
srs5694cb76c672010-02-11 22:22:22 -0500999 } // if/else
srs5694a17fe692011-09-10 20:30:20 -04001000 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -05001001 } // if
srs5694a17fe692011-09-10 20:30:20 -04001002 return allOK;
srs5694cb76c672010-02-11 22:22:22 -05001003} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -04001004
srs56944307ef22012-05-30 12:30:48 -04001005// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1006// header later on the disk without asking for permission, if necessary, and
1007// doesn't confirm the operation before writing. If quiet==0, asks permission
1008// before moving the second header and asks for final confirmation of any
1009// write.
srs5694a17fe692011-09-10 20:30:20 -04001010// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -05001011int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -04001012 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -05001013 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -04001014
srs5694e7b4ff92009-08-18 13:16:10 -04001015 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -05001016
1017 // This test should only fail on read-only disks....
1018 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001019 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -05001020 allOK = 0;
1021 } // if
1022
srs569464cbd172011-03-01 22:03:54 -05001023 // Check that disk is really big enough to handle the second header...
1024 if (mainHeader.backupLBA >= diskSize) {
1025 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1026 << "header, but other problems may occur!\n";
1027 MoveSecondHeaderToEnd();
1028 } // if
1029
srs5694e7b4ff92009-08-18 13:16:10 -04001030 // Is there enough space to hold the GPT headers and partition tables,
1031 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001032 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001033 allOK = 0;
1034 } // if
1035
srs5694247657a2009-11-26 18:36:12 -05001036 // Check that second header is properly placed. Warn and ask if this should
1037 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001038 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1039 if (quiet == 0) {
1040 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1041 << "correct this problem? ";
1042 if (GetYN() == 'Y') {
1043 MoveSecondHeaderToEnd();
1044 cout << "Have moved second header and partition table to correct location.\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
srs5694247657a2009-11-26 18:36:12 -05001049 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001050 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001051 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001052
srs5694d8eed462012-12-15 01:55:21 -05001053 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1054 if (quiet == 0) {
1055 cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1056 << "this problem? ";
1057 if (GetYN() == 'Y') {
1058 MoveSecondHeaderToEnd();
1059 cout << "Have adjusted the second header and last usable sector value.\n";
1060 } else {
1061 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1062 } // if correction requested
1063 } else { // go ahead and do correction automatically
1064 MoveSecondHeaderToEnd();
1065 } // if/else quiet
1066 } // if
1067
srs569455d92612010-03-07 22:16:07 -05001068 // Check for overlapping or insane partitions....
1069 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001070 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001071 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001072 } // if
1073
Roderick W. Smith4a702a22014-01-25 23:46:42 -05001074 // Check that protective MBR fits, and warn if it doesn't....
1075 if (!protectiveMBR.DoTheyFit()) {
1076 cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1077 << "fresh protective or hybrid MBR is recommended.\n";
1078 }
1079
srs5694e4ac11e2009-08-31 10:13:04 -04001080 // Check for mismatched MBR and GPT data, but let it pass if found
1081 // (function displays warning message)
1082 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001083
1084 RecomputeCRCs();
1085
srs5694ba00fed2010-01-12 18:18:36 -05001086 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001087 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001088 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001089 answer = GetYN();
1090 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001091 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001092 } else {
1093 allOK = 0;
1094 } // if/else
1095 } // if
1096
1097 // Do it!
1098 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001099 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001100 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001101 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001102 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001103 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1104 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001105 syncIt = 0;
1106 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001107
1108 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001109 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1110
1111 // Now write the main partition tables...
1112 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1113
1114 // Now write the main GPT header...
1115 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1116
1117 // To top it off, write the protective MBR...
1118 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001119
1120 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001121 // Note: Done even if some write operations failed, but not if all of them failed.
1122 // Done this way because I've received one problem report from a user one whose
1123 // system the MBR write failed but everything else was OK (on a GPT disk under
1124 // Windows), and the failure to sync therefore caused Windows to restore the
1125 // original partition table from its cache. OTOH, such restoration might be
1126 // desirable if the error occurs later; but that seems unlikely unless the initial
1127 // write fails....
1128 if (syncIt)
srs5694546a9c72010-01-26 16:00:26 -05001129 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001130
1131 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001132 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001133 } else {
srs5694fed16d02010-01-27 23:03:40 -05001134 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001135 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001136 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001137
srs5694546a9c72010-01-26 16:00:26 -05001138 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001139 } else {
srs56945a608532011-03-17 13:53:01 -04001140 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001141 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001142 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001143 } // if/else
1144 } else {
srs5694fed16d02010-01-27 23:03:40 -05001145 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001146 } // if
1147
1148 return (allOK);
1149} // GPTData::SaveGPTData()
1150
1151// Save GPT data to a backup file. This function does much less error
1152// checking than SaveGPTData(). It can therefore preserve many types of
1153// corruption for later analysis; however, it preserves only the MBR,
1154// the main GPT header, the backup GPT header, and the main partition
1155// table; it discards the backup partition table, since it should be
1156// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001157int GPTData::SaveGPTBackup(const string & filename) {
1158 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001159 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001160
srs5694546a9c72010-01-26 16:00:26 -05001161 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001162 // Recomputing the CRCs is likely to alter them, which could be bad
1163 // if the intent is to save a potentially bad GPT for later analysis;
1164 // but if we don't do this, we get bogus errors when we load the
1165 // backup. I'm favoring misses over false alarms....
1166 RecomputeCRCs();
1167
srs5694546a9c72010-01-26 16:00:26 -05001168 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001169 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001170
srs5694cb76c672010-02-11 22:22:22 -05001171 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001172 // MBR write closed disk, so re-open and seek to end....
1173 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001174 allOK = SaveHeader(&mainHeader, backupFile, 1);
1175 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001176
srs5694e7b4ff92009-08-18 13:16:10 -04001177 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001178 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001179
srs5694cb76c672010-02-11 22:22:22 -05001180 if (allOK)
1181 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001182
1183 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001184 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001185 } else {
srs5694fed16d02010-01-27 23:03:40 -05001186 cerr << "Warning! An error was reported when writing the backup file.\n"
1187 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001188 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001189 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001190 } else {
srs56945a608532011-03-17 13:53:01 -04001191 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001192 allOK = 0;
1193 } // if/else
1194 return allOK;
1195} // GPTData::SaveGPTBackup()
1196
srs5694cb76c672010-02-11 22:22:22 -05001197// Write a GPT header (main or backup) to the specified sector. Used by both
1198// the SaveGPTData() and SaveGPTBackup() functions.
1199// Should be passed an architecture-appropriate header (DO NOT call
1200// ReverseHeaderBytes() on the header before calling this function)
1201// Returns 1 on success, 0 on failure
1202int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1203 int littleEndian, allOK = 1;
1204
1205 littleEndian = IsLittleEndian();
1206 if (!littleEndian)
1207 ReverseHeaderBytes(header);
1208 if (disk.Seek(sector)) {
1209 if (disk.Write(header, 512) == -1)
1210 allOK = 0;
1211 } else allOK = 0; // if (disk.Seek()...)
1212 if (!littleEndian)
1213 ReverseHeaderBytes(header);
1214 return allOK;
1215} // GPTData::SaveHeader()
1216
1217// Save the partitions to the specified sector. Used by both the SaveGPTData()
1218// and SaveGPTBackup() functions.
1219// Should be passed an architecture-appropriate header (DO NOT call
1220// ReverseHeaderBytes() on the header before calling this function)
1221// Returns 1 on success, 0 on failure
1222int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1223 int littleEndian, allOK = 1;
1224
1225 littleEndian = IsLittleEndian();
1226 if (disk.Seek(sector)) {
1227 if (!littleEndian)
1228 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001229 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001230 allOK = 0;
1231 if (!littleEndian)
1232 ReversePartitionBytes();
1233 } else allOK = 0; // if (myDisk.Seek()...)
1234 return allOK;
1235} // GPTData::SavePartitionTable()
1236
srs5694e7b4ff92009-08-18 13:16:10 -04001237// Load GPT data from a backup file created by SaveGPTBackup(). This function
1238// does minimal error checking. It returns 1 if it completed successfully,
1239// 0 if there was a problem. In the latter case, it creates a new empty
1240// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001241int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001242 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001243 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001244 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001245
srs5694546a9c72010-01-26 16:00:26 -05001246 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001247 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001248 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001249 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001250
srs5694cb76c672010-02-11 22:22:22 -05001251 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001252
srs5694cb76c672010-02-11 22:22:22 -05001253 // Check backup file size and rebuild second header if file is right
1254 // size to be direct dd copy of MBR, main header, and main partition
1255 // table; if other size, treat it like a GPT fdisk-generated backup
1256 // file
1257 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1258 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1259 if (shortBackup) {
1260 RebuildSecondHeader();
1261 secondCrcOk = mainCrcOk;
1262 } else {
1263 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1264 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001265
srs5694e7b4ff92009-08-18 13:16:10 -04001266 // Return valid headers code: 0 = both headers bad; 1 = main header
1267 // good, backup bad; 2 = backup header good, main header bad;
1268 // 3 = both headers good. Note these codes refer to valid GPT
1269 // signatures and version numbers; more subtle problems will elude
1270 // this check!
1271 if ((val = CheckHeaderValidity()) > 0) {
1272 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001273 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001274 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001275 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001276 } // if/else
1277
srs5694e7b4ff92009-08-18 13:16:10 -04001278 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001279 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1280 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001281 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001282 } // if
1283
srs5694cb76c672010-02-11 22:22:22 -05001284 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1285 cerr << "Warning! Read error " << errno
1286 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001287 } else {
1288 allOK = 0;
1289 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001290 // Something went badly wrong, so blank out partitions
1291 if (allOK == 0) {
1292 cerr << "Improper backup file! Clearing all partition data!\n";
1293 ClearGPTData();
1294 protectiveMBR.MakeProtectiveMBR();
1295 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001296 } else {
1297 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001298 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001299 } // if/else
1300
srs5694e7b4ff92009-08-18 13:16:10 -04001301 return allOK;
1302} // GPTData::LoadGPTBackup()
1303
srs569408bb0da2010-02-19 17:19:55 -05001304int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001305 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001306} // GPTData::SaveMBR()
1307
1308// This function destroys the on-disk GPT structures, but NOT the on-disk
1309// MBR.
1310// Returns 1 if the operation succeeds, 0 if not.
1311int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001312 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001313 uint8_t blankSector[512];
1314 uint8_t* emptyTable;
1315
srs569401f7f082011-03-15 23:53:31 -04001316 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001317
1318 if (myDisk.OpenForWrite()) {
1319 if (!myDisk.Seek(mainHeader.currentLBA))
1320 allOK = 0;
1321 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1322 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1323 allOK = 0;
1324 } // if
1325 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1326 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001327 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001328 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001329 if (emptyTable == NULL) {
Roderick W. Smith5435fcf2014-02-17 12:01:51 -05001330 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Aborting operation!\n";
1331 return(0);
srs56946aae2a92011-06-10 01:16:51 -04001332 } // if
srs569401f7f082011-03-15 23:53:31 -04001333 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001334 if (allOK) {
1335 sum = myDisk.Write(emptyTable, tableSize);
1336 if (sum != tableSize) {
1337 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1338 allOK = 0;
1339 } // if write failed
srs569408bb0da2010-02-19 17:19:55 -05001340 } // if
Roderick W. Smith5435fcf2014-02-17 12:01:51 -05001341
1342 if (secondHeader.currentLBA == (diskSize - UINT64_C(1))) {
1343 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
srs569408bb0da2010-02-19 17:19:55 -05001344 allOK = 0;
Roderick W. Smith5435fcf2014-02-17 12:01:51 -05001345 if (allOK) {
1346 sum = myDisk.Write(emptyTable, tableSize);
1347 if (sum != tableSize) {
1348 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1349 << errno << "\n";
1350 allOK = 0;
1351 } // if wrong size written
srs569408bb0da2010-02-19 17:19:55 -05001352 } // if
Roderick W. Smith5435fcf2014-02-17 12:01:51 -05001353 if (!myDisk.Seek(secondHeader.currentLBA))
1354 allOK = 0;
1355 if (allOK) {
1356 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1357 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1358 allOK = 0;
1359 } // if
1360 } // if
1361 } else {
1362 cout << "Note: The GPT second header is not at the end of the disk end; therefore,\n"
1363 << "it's not being erased.\n";
1364 }
srs569408bb0da2010-02-19 17:19:55 -05001365 myDisk.DiskSync();
1366 myDisk.Close();
1367 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1368 << "other utilities.\n";
1369 delete[] emptyTable;
1370 } else {
srs56945a608532011-03-17 13:53:01 -04001371 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001372 } // if/else (fd != -1)
1373 return (allOK);
1374} // GPTDataTextUI::DestroyGPT()
1375
1376// Wipe MBR data from the disk (zero it out completely)
1377// Returns 1 on success, 0 on failure.
1378int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001379 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001380 uint8_t blankSector[512];
1381
srs569401f7f082011-03-15 23:53:31 -04001382 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001383
srs569401f7f082011-03-15 23:53:31 -04001384 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1385
srs569408bb0da2010-02-19 17:19:55 -05001386 if (!allOK)
1387 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1388 return allOK;
1389} // GPTData::DestroyMBR(void)
1390
srs5694e4ac11e2009-08-31 10:13:04 -04001391// Tell user whether Apple Partition Map (APM) was discovered....
1392void GPTData::ShowAPMState(void) {
1393 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001394 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001395 else
srs5694fed16d02010-01-27 23:03:40 -05001396 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001397} // GPTData::ShowAPMState()
1398
1399// Tell user about the state of the GPT data....
1400void GPTData::ShowGPTState(void) {
1401 switch (state) {
1402 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001403 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001404 break;
1405 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001406 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001407 break;
1408 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001409 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001410 break;
1411 default:
srs5694fed16d02010-01-27 23:03:40 -05001412 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001413 break;
1414 } // switch
1415} // GPTData::ShowGPTState()
1416
1417// Display the basic GPT data
1418void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001419 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001420 uint64_t temp, totalFree;
1421
srs5694fed16d02010-01-27 23:03:40 -05001422 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001423 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001424 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001425 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001426 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001427 cout << "First usable sector is " << mainHeader.firstUsableLBA
1428 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001429 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001430 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001431 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001432 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001433 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001434 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001435 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001436 } // for
1437} // GPTData::DisplayGPTData()
1438
srs5694e4ac11e2009-08-31 10:13:04 -04001439// Show detailed information on the specified partition
1440void GPTData::ShowPartDetails(uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001441 if ((partNum < numParts) && !IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001442 partitions[partNum].ShowDetails(blockSize);
1443 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001444 cout << "Partition #" << partNum + 1 << " does not exist.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001445 } // if
1446} // GPTData::ShowPartDetails()
1447
srs5694e4ac11e2009-08-31 10:13:04 -04001448/**************************************************************************
1449 * *
1450 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1451 * (some of these functions may require user interaction) *
1452 * *
1453 **************************************************************************/
1454
srs569408bb0da2010-02-19 17:19:55 -05001455// Examines the MBR & GPT data to determine which set of data to use: the
1456// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1457// a new set of partitions (use_new). A return value of use_abort indicates
1458// that this function couldn't determine what to do. Overriding functions
1459// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001460WhichToUse GPTData::UseWhichPartitions(void) {
1461 WhichToUse which = use_new;
1462 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001463
1464 mbrState = protectiveMBR.GetValidity();
1465
1466 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001467 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001468 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1469 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001470 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001471 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1472 << "typing 'q' if you don't want to convert your MBR partitions\n"
1473 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001474 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001475 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001476 which = use_mbr;
1477 } // if
1478
1479 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001480 cout << "\n**********************************************************************\n"
1481 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1482 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001483 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001484 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001485 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1486 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001487 } // if
srs5694fed16d02010-01-27 23:03:40 -05001488 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001489 which = use_bsd;
1490 } // if
1491
1492 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001493 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001494 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001495 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001496 } // if
1497 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001498 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001499 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001500 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001501 } // if
1502 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001503 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001504 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001505 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001506 } // if
1507 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001508 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001509 } // if
1510
srs5694e4ac11e2009-08-31 10:13:04 -04001511 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001512 if (mbrState == gpt) {
1513 cout << "\a\a****************************************************************************\n"
1514 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1515 << "verification and recovery are STRONGLY recommended.\n"
1516 << "****************************************************************************\n";
1517 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001518 } else {
srs569408bb0da2010-02-19 17:19:55 -05001519 which = use_abort;
1520 } // if/else MBR says disk is GPT
1521 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001522
1523 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001524 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001525
1526 return which;
1527} // UseWhichPartitions()
1528
srs569408bb0da2010-02-19 17:19:55 -05001529// Convert MBR partition table into GPT form.
1530void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001531 int i, numToConvert;
1532 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001533
1534 // Clear out old data & prepare basics....
1535 ClearGPTData();
1536
1537 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001538 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001539 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001540 else
srs56940283dae2010-04-28 16:44:34 -04001541 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001542
1543 for (i = 0; i < numToConvert; i++) {
1544 origType = protectiveMBR.GetType(i);
1545 // don't waste CPU time trying to convert extended, hybrid protective, or
1546 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001547 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001548 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001549 partitions[i] = protectiveMBR.AsGPT(i);
1550 } // for
1551
1552 // Convert MBR into protective MBR
1553 protectiveMBR.MakeProtectiveMBR();
1554
1555 // Record that all original CRCs were OK so as not to raise flags
1556 // when doing a disk verification
1557 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001558} // GPTData::XFormPartitions()
1559
1560// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001561// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001562// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001563int GPTData::XFormDisklabel(uint32_t partNum) {
1564 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001565 int goOn = 1, numDone = 0;
1566 BSDData disklabel;
1567
srs569408bb0da2010-02-19 17:19:55 -05001568 if (GetPartRange(&low, &high) == 0) {
1569 goOn = 0;
1570 cout << "No partitions!\n";
1571 } // if
1572 if (partNum > high) {
1573 goOn = 0;
1574 cout << "Specified partition is invalid!\n";
1575 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001576
srs569408bb0da2010-02-19 17:19:55 -05001577 // If all is OK, read the disklabel and convert it.
1578 if (goOn) {
1579 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1580 partitions[partNum].GetLastLBA());
1581 if ((goOn) && (disklabel.IsDisklabel())) {
1582 numDone = XFormDisklabel(&disklabel);
1583 if (numDone == 1)
1584 cout << "Converted 1 BSD partition.\n";
1585 else
1586 cout << "Converted " << numDone << " BSD partitions.\n";
1587 } else {
1588 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1589 } // if/else
1590 } // if
1591 if (numDone > 0) { // converted partitions; delete carrier
1592 partitions[partNum].BlankPartition();
1593 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001594 return numDone;
srs569455d92612010-03-07 22:16:07 -05001595} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001596
1597// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001598int GPTData::XFormDisklabel(BSDData* disklabel) {
1599 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001600
srs569408bb0da2010-02-19 17:19:55 -05001601 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001602 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001603 partNum = FindFirstFreePart();
1604 if (partNum >= 0) {
1605 partitions[partNum] = disklabel->AsGPT(i);
1606 if (partitions[partNum].IsUsed())
1607 numDone++;
1608 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001609 } // for
srs569408bb0da2010-02-19 17:19:55 -05001610 if (partNum == -1)
1611 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001612 } // if
1613
1614 // Record that all original CRCs were OK so as not to raise flags
1615 // when doing a disk verification
1616 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1617
1618 return numDone;
1619} // GPTData::XFormDisklabel(BSDData* disklabel)
1620
srs569408bb0da2010-02-19 17:19:55 -05001621// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1622// partition has the active/bootable flag UNset and uses the GPT fdisk
1623// type code divided by 0x0100 as the MBR type code.
1624// Returns 1 if operation was 100% successful, 0 if there were ANY
1625// problems.
srs5694978041c2009-09-21 20:51:47 -04001626int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001627 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001628
srs5694978041c2009-09-21 20:51:47 -04001629 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001630 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001631 allOK = 0;
1632 } // if
srs56940283dae2010-04-28 16:44:34 -04001633 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001634 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001635 allOK = 0;
1636 } // if
1637 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001638 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001639 allOK = 0;
1640 } // if
1641 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1642 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1643 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001644 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1645 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001646 } // if
srs5694978041c2009-09-21 20:51:47 -04001647 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001648 (uint32_t) partitions[gptPart].GetLengthLBA(),
1649 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001650 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001651 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1652 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1653 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001654 allOK = 0;
1655 } // if/else
1656 return allOK;
1657} // GPTData::OnePartToMBR()
1658
srs5694e4ac11e2009-08-31 10:13:04 -04001659
1660/**********************************************************************
1661 * *
1662 * Functions that adjust GPT data structures WITHOUT user interaction *
1663 * (they may display information for the user's benefit, though) *
1664 * *
1665 **********************************************************************/
1666
1667// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001668// necessary, copies data if it already exists. If fillGPTSectors is 1
1669// (the default), rounds numEntries to fill all the sectors necessary to
1670// hold the GPT.
1671// Returns 1 if all goes well, 0 if an error is encountered.
1672int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001673 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001674 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001675 int allOK = 1;
1676
1677 // First, adjust numEntries upward, if necessary, to get a number
1678 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001679 entriesPerSector = blockSize / GPT_SIZE;
1680 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001681 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001682 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001683 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001684 } // if
1685
srs5694247657a2009-11-26 18:36:12 -05001686 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001687 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001688 // partition table, which causes problems when loading data from a RAID
1689 // array that's been expanded because this function is called when loading
1690 // data.
srs56940283dae2010-04-28 16:44:34 -04001691 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001692 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001693 if (newParts != NULL) {
1694 if (partitions != NULL) { // existing partitions; copy them over
1695 GetPartRange(&i, &high);
1696 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001697 cout << "The highest-numbered partition is " << high + 1
1698 << ", which is greater than the requested\n"
1699 << "partition table size of " << numEntries
1700 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001701 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001702 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001703 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001704 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001705 copyNum = numEntries;
1706 else
srs56940283dae2010-04-28 16:44:34 -04001707 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001708 for (i = 0; i < copyNum; i++) {
1709 newParts[i] = partitions[i];
1710 } // for
srs569401f7f082011-03-15 23:53:31 -04001711 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001712 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001713 } // if
1714 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001715 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001716 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001717 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001718 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001719 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1720 MoveSecondHeaderToEnd();
1721 if (diskSize > 0)
1722 CheckGPTSize();
1723 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001724 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001725 allOK = 0;
1726 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001727 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001728 mainHeader.numParts = numParts;
1729 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001730 return (allOK);
1731} // GPTData::SetGPTSize()
1732
1733// Blank the partition array
1734void GPTData::BlankPartitions(void) {
1735 uint32_t i;
1736
srs56940283dae2010-04-28 16:44:34 -04001737 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001738 partitions[i].BlankPartition();
1739 } // for
1740} // GPTData::BlankPartitions()
1741
srs5694ba00fed2010-01-12 18:18:36 -05001742// Delete a partition by number. Returns 1 if successful,
1743// 0 if there was a problem. Returns 1 if partition was in
1744// range, 0 if it was out of range.
1745int GPTData::DeletePartition(uint32_t partNum) {
1746 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001747 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001748
srs56940283dae2010-04-28 16:44:34 -04001749 numUsedParts = GetPartRange(&low, &high);
1750 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001751 // In case there's a protective MBR, look for & delete matching
1752 // MBR partition....
1753 startSector = partitions[partNum].GetFirstLBA();
1754 length = partitions[partNum].GetLengthLBA();
1755 protectiveMBR.DeleteByLocation(startSector, length);
1756
1757 // Now delete the GPT partition
1758 partitions[partNum].BlankPartition();
1759 } else {
srs5694fed16d02010-01-27 23:03:40 -05001760 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001761 retval = 0;
1762 } // if/else
1763 return retval;
1764} // GPTData::DeletePartition(uint32_t partNum)
1765
srs569408bb0da2010-02-19 17:19:55 -05001766// Non-interactively create a partition.
1767// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001768uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001769 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001770 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001771
1772 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001773 if (Align(&startSector)) {
1774 cout << "Information: Moved requested sector from " << origSector << " to "
1775 << startSector << " in\norder to align on " << sectorAlignment
1776 << "-sector boundaries.\n";
1777 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001778 if (IsFree(startSector) && (startSector <= endSector)) {
1779 if (FindLastInFree(startSector) >= endSector) {
1780 partitions[partNum].SetFirstLBA(startSector);
1781 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001782 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001783 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001784 } else retval = 0; // if free space until endSector
1785 } else retval = 0; // if startSector is free
1786 } else retval = 0; // if legal partition number
1787 return retval;
1788} // GPTData::CreatePartition(partNum, startSector, endSector)
1789
srs5694e4ac11e2009-08-31 10:13:04 -04001790// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001791// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001792void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001793 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001794 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001795} // GPTData::SortGPT()
1796
srs569408bb0da2010-02-19 17:19:55 -05001797// Swap the contents of two partitions.
1798// Returns 1 if successful, 0 if either partition is out of range
1799// (that is, not a legal number; either or both can be empty).
1800// Note that if partNum1 = partNum2 and this number is in range,
1801// it will be considered successful.
1802int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1803 GPTPart temp;
1804 int allOK = 1;
1805
srs56940283dae2010-04-28 16:44:34 -04001806 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001807 if (partNum1 != partNum2) {
1808 temp = partitions[partNum1];
1809 partitions[partNum1] = partitions[partNum2];
1810 partitions[partNum2] = temp;
1811 } // if
1812 } else allOK = 0; // partition numbers are valid
1813 return allOK;
1814} // GPTData::SwapPartitions()
1815
srs5694e4ac11e2009-08-31 10:13:04 -04001816// Set up data structures for entirely new set of partitions on the
1817// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001818// Note that this function does NOT clear the protectiveMBR data
1819// structure, since it may hold the original MBR partitions if the
1820// program was launched on an MBR disk, and those may need to be
1821// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001822int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001823 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001824
1825 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001826 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001827 partitions = NULL;
1828 SetGPTSize(NUM_GPT_ENTRIES);
1829
1830 // Now initialize a bunch of stuff that's static....
1831 mainHeader.signature = GPT_SIGNATURE;
1832 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001833 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001834 mainHeader.reserved = 0;
1835 mainHeader.currentLBA = UINT64_C(1);
1836 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1837 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1838 for (i = 0; i < GPT_RESERVED; i++) {
1839 mainHeader.reserved2[i] = '\0';
1840 } // for
srs56940873e9d2010-10-07 13:00:45 -04001841 if (blockSize > 0)
1842 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1843 else
1844 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001845
1846 // Now some semi-static items (computed based on end of disk)
1847 mainHeader.backupLBA = diskSize - UINT64_C(1);
1848 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1849
1850 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001851 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001852
1853 // Copy main header to backup header
1854 RebuildSecondHeader();
1855
1856 // Blank out the partitions array....
1857 BlankPartitions();
1858
1859 // Flag all CRCs as being OK....
1860 mainCrcOk = 1;
1861 secondCrcOk = 1;
1862 mainPartsCrcOk = 1;
1863 secondPartsCrcOk = 1;
1864
1865 return (goOn);
1866} // GPTData::ClearGPTData()
1867
srs5694247657a2009-11-26 18:36:12 -05001868// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001869// If the disk size has actually changed, this also adjusts the protective
1870// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001871// Used internally and called by the 'e' option on the recovery &
1872// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001873// to their arrays or to adjust data structures in restore operations
1874// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001875void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001876 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001877 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1878 if (protectiveMBR.GetValidity() == hybrid) {
1879 protectiveMBR.OptimizeEESize();
1880 RecomputeCHS();
1881 } // if
1882 if (protectiveMBR.GetValidity() == gpt)
1883 MakeProtectiveMBR();
1884 } // if
srs56948bb78762009-11-24 15:43:49 -05001885 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1886 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1887} // GPTData::FixSecondHeaderLocation()
1888
srs5694699941e2011-03-21 21:33:57 -04001889// Sets the partition's name to the specified UnicodeString without
1890// user interaction.
1891// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001892int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001893 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001894
srs5694699941e2011-03-21 21:33:57 -04001895 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001896 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001897 else
1898 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001899
1900 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001901} // GPTData::SetName
1902
1903// Set the disk GUID to the specified value. Note that the header CRCs must
1904// be recomputed after calling this function.
1905void GPTData::SetDiskGUID(GUIDData newGUID) {
1906 mainHeader.diskGUID = newGUID;
1907 secondHeader.diskGUID = newGUID;
1908} // SetDiskGUID()
1909
1910// Set the unique GUID of the specified partition. Returns 1 on
1911// successful completion, 0 if there were problems (invalid
1912// partition number).
1913int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1914 int retval = 0;
1915
srs56940283dae2010-04-28 16:44:34 -04001916 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001917 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001918 partitions[pn].SetUniqueGUID(theGUID);
1919 retval = 1;
1920 } // if
1921 } // if
1922 return retval;
1923} // GPTData::SetPartitionGUID()
1924
srs56949ba54212010-05-18 23:24:02 -04001925// Set new random GUIDs for the disk and all partitions. Intended to be used
1926// after disk cloning or similar operations that don't randomize the GUIDs.
1927void GPTData::RandomizeGUIDs(void) {
1928 uint32_t i;
1929
1930 mainHeader.diskGUID.Randomize();
1931 secondHeader.diskGUID = mainHeader.diskGUID;
1932 for (i = 0; i < numParts; i++)
1933 if (partitions[i].IsUsed())
1934 partitions[i].RandomizeUniqueGUID();
1935} // GPTData::RandomizeGUIDs()
1936
srs5694ba00fed2010-01-12 18:18:36 -05001937// Change partition type code non-interactively. Returns 1 if
1938// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001939int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1940 int retval = 1;
1941
1942 if (!IsFreePartNum(partNum)) {
1943 partitions[partNum].SetType(theGUID);
1944 } else retval = 0;
1945 return retval;
1946} // GPTData::ChangePartType()
1947
srs56949ba54212010-05-18 23:24:02 -04001948// Recompute the CHS values of all the MBR partitions. Used to reset
1949// CHS values that some BIOSes require, despite the fact that the
1950// resulting CHS values violate the GPT standard.
1951void GPTData::RecomputeCHS(void) {
1952 int i;
1953
1954 for (i = 0; i < 4; i++)
1955 protectiveMBR.RecomputeCHS(i);
1956} // GPTData::RecomputeCHS()
1957
srs56941d1448a2009-12-31 21:20:19 -05001958// Adjust sector number so that it falls on a sector boundary that's a
1959// multiple of sectorAlignment. This is done to improve the performance
1960// of Western Digital Advanced Format disks and disks with similar
1961// technology from other companies, which use 4096-byte sectors
1962// internally although they translate to 512-byte sectors for the
1963// benefit of the OS. If partitions aren't properly aligned on these
1964// disks, some filesystem data structures can span multiple physical
1965// sectors, degrading performance. This function should be called
1966// only on the FIRST sector of the partition, not the last!
1967// This function returns 1 if the alignment was altered, 0 if it
1968// was unchanged.
1969int GPTData::Align(uint64_t* sector) {
1970 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001971 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001972
1973 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001974 earlier = (*sector / sectorAlignment) * sectorAlignment;
1975 later = earlier + (uint64_t) sectorAlignment;
1976
1977 // Check to see that every sector between the earlier one and the
1978 // requested one is clear, and that it's not too early....
1979 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001980 sectorOK = 1;
1981 testSector = earlier;
1982 do {
1983 sectorOK = IsFree(testSector++);
1984 } while ((sectorOK == 1) && (testSector < *sector));
1985 if (sectorOK == 1) {
1986 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001987 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001988 } // if
1989 } // if firstUsableLBA check
1990
1991 // If couldn't move the sector earlier, try to move it later instead....
1992 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1993 sectorOK = 1;
1994 testSector = later;
1995 do {
1996 sectorOK = IsFree(testSector--);
1997 } while ((sectorOK == 1) && (testSector > *sector));
1998 if (sectorOK == 1) {
1999 *sector = later;
srs56945a081752010-09-24 20:39:41 -04002000 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05002001 } // if
2002 } // if
srs56941d1448a2009-12-31 21:20:19 -05002003 } // if
2004 return retval;
2005} // GPTData::Align()
2006
srs5694e4ac11e2009-08-31 10:13:04 -04002007/********************************************************
2008 * *
2009 * Functions that return data about GPT data structures *
2010 * (most of these are inline in gpt.h) *
2011 * *
2012 ********************************************************/
2013
2014// Find the low and high used partition numbers (numbered from 0).
2015// Return value is the number of partitions found. Note that the
2016// *low and *high values are both set to 0 when no partitions
2017// are found, as well as when a single partition in the first
2018// position exists. Thus, the return value is the only way to
2019// tell when no partitions exist.
2020int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2021 uint32_t i;
2022 int numFound = 0;
2023
srs56940283dae2010-04-28 16:44:34 -04002024 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04002025 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04002026 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002027 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04002028 *high = i; // since we're counting up, set the high value
2029 // Set the low value only if it's not yet found...
2030 if (*low == (numParts + 1)) *low = i;
2031 numFound++;
2032 } // if
2033 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04002034
2035 // Above will leave *low pointing to its "not found" value if no partitions
2036 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002037 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002038 *low = 0;
2039 return numFound;
2040} // GPTData::GetPartRange()
2041
srs569408bb0da2010-02-19 17:19:55 -05002042// Returns the value of the first free partition, or -1 if none is
2043// unused.
2044int GPTData::FindFirstFreePart(void) {
2045 int i = 0;
2046
2047 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002048 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002049 i++;
srs56940283dae2010-04-28 16:44:34 -04002050 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002051 i = -1;
2052 } else i = -1;
2053 return i;
2054} // GPTData::FindFirstFreePart()
2055
srs5694978041c2009-09-21 20:51:47 -04002056// Returns the number of defined partitions.
2057uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002058 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002059
srs56940283dae2010-04-28 16:44:34 -04002060 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002061 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002062 counted++;
2063 } // for
2064 return counted;
2065} // GPTData::CountParts()
2066
srs5694e4ac11e2009-08-31 10:13:04 -04002067/****************************************************
2068 * *
2069 * Functions that return data about disk free space *
2070 * *
2071 ****************************************************/
2072
2073// Find the first available block after the starting point; returns 0 if
2074// there are no available blocks left
2075uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2076 uint64_t first;
2077 uint32_t i;
2078 int firstMoved = 0;
2079
2080 // Begin from the specified starting point or from the first usable
2081 // LBA, whichever is greater...
2082 if (start < mainHeader.firstUsableLBA)
2083 first = mainHeader.firstUsableLBA;
2084 else
2085 first = start;
2086
2087 // ...now search through all partitions; if first is within an
2088 // existing partition, move it to the next sector after that
2089 // partition and repeat. If first was moved, set firstMoved
2090 // flag; repeat until firstMoved is not set, so as to catch
2091 // cases where partitions are out of sequential order....
2092 do {
2093 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002094 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002095 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002096 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002097 first = partitions[i].GetLastLBA() + 1;
2098 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002099 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002100 } // for
2101 } while (firstMoved == 1);
2102 if (first > mainHeader.lastUsableLBA)
2103 first = 0;
2104 return (first);
2105} // GPTData::FindFirstAvailable()
2106
2107// Finds the first available sector in the largest block of unallocated
2108// space on the disk. Returns 0 if there are no available blocks left
2109uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002110 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002111
2112 start = 0;
2113 do {
2114 firstBlock = FindFirstAvailable(start);
2115 if (firstBlock != UINT32_C(0)) { // something's free...
2116 lastBlock = FindLastInFree(firstBlock);
2117 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2118 if (segmentSize > selectedSize) {
2119 selectedSize = segmentSize;
2120 selectedSegment = firstBlock;
2121 } // if
2122 start = lastBlock + 1;
2123 } // if
2124 } while (firstBlock != 0);
2125 return selectedSegment;
2126} // GPTData::FindFirstInLargest()
2127
srs5694cb76c672010-02-11 22:22:22 -05002128// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002129// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002130uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002131 uint64_t last;
2132 uint32_t i;
2133 int lastMoved = 0;
2134
2135 // Start by assuming the last usable LBA is available....
2136 last = mainHeader.lastUsableLBA;
2137
2138 // ...now, similar to algorithm in FindFirstAvailable(), search
2139 // through all partitions, moving last when it's in an existing
2140 // partition. Set the lastMoved flag so we repeat to catch cases
2141 // where partitions are out of logical order.
2142 do {
2143 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002144 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002145 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002146 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002147 last = partitions[i].GetFirstLBA() - 1;
2148 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002149 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002150 } // for
2151 } while (lastMoved == 1);
2152 if (last < mainHeader.firstUsableLBA)
2153 last = 0;
2154 return (last);
2155} // GPTData::FindLastAvailable()
2156
2157// Find the last available block in the free space pointed to by start.
2158uint64_t GPTData::FindLastInFree(uint64_t start) {
2159 uint64_t nearestStart;
2160 uint32_t i;
2161
2162 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002163 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002164 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002165 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002166 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002167 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002168 } // for
2169 return (nearestStart);
2170} // GPTData::FindLastInFree()
2171
2172// Finds the total number of free blocks, the number of segments in which
2173// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002174uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002175 uint64_t start = UINT64_C(0); // starting point for each search
2176 uint64_t totalFound = UINT64_C(0); // running total
2177 uint64_t firstBlock; // first block in a segment
2178 uint64_t lastBlock; // last block in a segment
2179 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002180 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002181
2182 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002183 if (diskSize > 0) {
2184 do {
2185 firstBlock = FindFirstAvailable(start);
2186 if (firstBlock != UINT64_C(0)) { // something's free...
2187 lastBlock = FindLastInFree(firstBlock);
2188 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2189 if (segmentSize > *largestSegment) {
2190 *largestSegment = segmentSize;
2191 } // if
2192 totalFound += segmentSize;
2193 num++;
2194 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002195 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002196 } while (firstBlock != 0);
2197 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002198 *numSegments = num;
2199 return totalFound;
2200} // GPTData::FindFreeBlocks()
2201
srs569455d92612010-03-07 22:16:07 -05002202// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2203// If it's allocated, return the partition number to which it's allocated
2204// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2205// returned in partNum if the sector is in use by basic GPT data structures.)
2206int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002207 int isFree = 1;
2208 uint32_t i;
2209
srs56940283dae2010-04-28 16:44:34 -04002210 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002211 if ((sector >= partitions[i].GetFirstLBA()) &&
2212 (sector <= partitions[i].GetLastLBA())) {
2213 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002214 if (partNum != NULL)
2215 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002216 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002217 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002218 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002219 (sector > mainHeader.lastUsableLBA)) {
2220 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002221 if (partNum != NULL)
2222 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002223 } // if
2224 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002225} // GPTData::IsFree()
2226
srs5694815fb652011-03-18 12:35:56 -04002227// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002228int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002229 return ((partNum < numParts) && (partitions != NULL) &&
2230 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002231} // GPTData::IsFreePartNum()
2232
srs5694815fb652011-03-18 12:35:56 -04002233// Returns 1 if partNum is in use.
2234int GPTData::IsUsedPartNum(uint32_t partNum) {
2235 return ((partNum < numParts) && (partitions != NULL) &&
2236 (partitions[partNum].IsUsed()));
2237} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002238
2239/***********************************************************
2240 * *
2241 * Change how functions work or return information on them *
2242 * *
2243 ***********************************************************/
2244
2245// Set partition alignment value; partitions will begin on multiples of
2246// the specified value
2247void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002248 if (n > 0)
2249 sectorAlignment = n;
2250 else
2251 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002252} // GPTData::SetAlignment()
2253
2254// Compute sector alignment based on the current partitions (if any). Each
2255// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002256// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2257// sector size), but not by the previously-located alignment value, then the
2258// alignment value is adjusted down. If the computed alignment is less than 8
2259// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002260// is a safety measure for Advanced Format drives. If no partitions are
2261// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002262// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002263// drives are aligned to 2048-sector multiples but the program won't complain
2264// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002265// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002266// Returns the computed alignment value.
2267uint32_t GPTData::ComputeAlignment(void) {
2268 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002269 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002270
srs56940873e9d2010-10-07 13:00:45 -04002271 if (blockSize > 0)
2272 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2273 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002274 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002275 if (partitions[i].IsUsed()) {
2276 found = 0;
2277 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002278 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002279 if ((partitions[i].GetFirstLBA() % align) == 0) {
2280 found = 1;
2281 } else {
2282 exponent--;
2283 } // if/else
2284 } // while
2285 } // if
2286 } // for
srs56940873e9d2010-10-07 13:00:45 -04002287 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2288 align = MIN_AF_ALIGNMENT;
2289 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002290 return align;
2291} // GPTData::ComputeAlignment()
2292
srs5694e4ac11e2009-08-31 10:13:04 -04002293/********************************
2294 * *
2295 * Endianness support functions *
2296 * *
2297 ********************************/
2298
srs56942a9f5da2009-08-26 00:48:01 -04002299void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002300 ReverseBytes(&header->signature, 8);
2301 ReverseBytes(&header->revision, 4);
2302 ReverseBytes(&header->headerSize, 4);
2303 ReverseBytes(&header->headerCRC, 4);
2304 ReverseBytes(&header->reserved, 4);
2305 ReverseBytes(&header->currentLBA, 8);
2306 ReverseBytes(&header->backupLBA, 8);
2307 ReverseBytes(&header->firstUsableLBA, 8);
2308 ReverseBytes(&header->lastUsableLBA, 8);
2309 ReverseBytes(&header->partitionEntriesLBA, 8);
2310 ReverseBytes(&header->numParts, 4);
2311 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2312 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002313 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002314} // GPTData::ReverseHeaderBytes()
2315
srs56940283dae2010-04-28 16:44:34 -04002316// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002317void GPTData::ReversePartitionBytes() {
2318 uint32_t i;
2319
srs56940283dae2010-04-28 16:44:34 -04002320 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002321 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002322 } // for
2323} // GPTData::ReversePartitionBytes()
2324
srs56949ddc14b2010-08-22 22:44:42 -04002325// Validate partition number
2326bool GPTData::ValidPartNum (const uint32_t partNum) {
2327 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002328 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002329 return false;
2330 } // if
2331 return true;
2332} // GPTData::ValidPartNum
2333
srs56945a081752010-09-24 20:39:41 -04002334// Return a single partition for inspection (not modification!) by other
2335// functions.
2336const GPTPart & GPTData::operator[](uint32_t partNum) const {
2337 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002338 cerr << "Partition number out of range (" << partNum << " requested, but only "
2339 << numParts << " available)\n";
2340 exit(1);
2341 } // if
2342 if (partitions == NULL) {
2343 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2344 exit(1);
srs56945a081752010-09-24 20:39:41 -04002345 } // if
2346 return partitions[partNum];
2347} // operator[]
2348
2349// Return (not for modification!) the disk's GUID value
2350const GUIDData & GPTData::GetDiskGUID(void) const {
2351 return mainHeader.diskGUID;
2352} // GPTData::GetDiskGUID()
2353
srs56949ddc14b2010-08-22 22:44:42 -04002354// Manage attributes for a partition, based on commands passed to this function.
2355// (Function is non-interactive.)
2356// Returns 1 if a modification command succeeded, 0 if the command should not have
2357// modified data, and -1 if a modification command failed.
2358int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2359 int retval = 0;
2360 Attributes theAttr;
2361
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002362 if (partNum >= (int) numParts) {
2363 cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2364 retval = -1;
srs56949ddc14b2010-08-22 22:44:42 -04002365 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002366 if (command == "show") {
2367 ShowAttributes(partNum);
2368 } else if (command == "get") {
2369 GetAttribute(partNum, bits);
srs56949ddc14b2010-08-22 22:44:42 -04002370 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002371 theAttr = partitions[partNum].GetAttributes();
2372 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2373 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2374 retval = 1;
2375 } else {
2376 retval = -1;
2377 } // if/else
2378 } // if/elseif/else
2379 } // if/else invalid partition #
srs56949ddc14b2010-08-22 22:44:42 -04002380
2381 return retval;
2382} // GPTData::ManageAttributes()
2383
2384// Show all attributes for a specified partition....
2385void GPTData::ShowAttributes(const uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002386 if ((partNum < numParts) && partitions[partNum].IsUsed())
srs5694e69e6802012-01-20 22:37:12 -05002387 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002388} // GPTData::ShowAttributes
2389
2390// Show whether a single attribute bit is set (terse output)...
2391void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002392 if (partNum < numParts)
2393 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002394} // GPTData::GetAttribute
2395
2396
srs56942a9f5da2009-08-26 00:48:01 -04002397/******************************************
2398 * *
2399 * Additional non-class support functions *
2400 * *
2401 ******************************************/
2402
srs5694e7b4ff92009-08-18 13:16:10 -04002403// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2404// never fail these tests, but the struct types may fail depending on compile options.
2405// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2406// sizes.
2407int SizesOK(void) {
2408 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002409
2410 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002411 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002412 allOK = 0;
2413 } // if
2414 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002415 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002416 allOK = 0;
2417 } // if
2418 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002419 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002420 allOK = 0;
2421 } // if
2422 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002423 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002424 allOK = 0;
2425 } // if
2426 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002427 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002428 allOK = 0;
2429 } // if
srs5694978041c2009-09-21 20:51:47 -04002430 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002431 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002432 allOK = 0;
2433 } // if
2434 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002435 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002436 allOK = 0;
2437 } // if
srs5694221e0872009-08-29 15:00:31 -04002438 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002439 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002440 allOK = 0;
2441 } // if
srs56946699b012010-02-04 00:55:30 -05002442 if (sizeof(GUIDData) != 16) {
2443 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2444 allOK = 0;
2445 } // if
2446 if (sizeof(PartType) != 16) {
2447 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2448 allOK = 0;
2449 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002450 return (allOK);
2451} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002452