blob: fa7b661e71d31f98243f9a802de0aad99d510780 [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) {
srs5694a17fe692011-09-10 20:30:20 -04001330 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
srs56946aae2a92011-06-10 01:16:51 -04001331 exit(1);
1332 } // 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
1340 } // if
1341 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1342 allOK = 0;
1343 if (allOK) {
1344 sum = myDisk.Write(emptyTable, tableSize);
1345 if (sum != tableSize) {
1346 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1347 << errno << "\n";
1348 allOK = 0;
1349 } // if wrong size written
1350 } // if
1351 if (!myDisk.Seek(secondHeader.currentLBA))
1352 allOK = 0;
1353 if (allOK) {
1354 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1355 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1356 allOK = 0;
1357 } // if
1358 } // if
1359 myDisk.DiskSync();
1360 myDisk.Close();
1361 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1362 << "other utilities.\n";
1363 delete[] emptyTable;
1364 } else {
srs56945a608532011-03-17 13:53:01 -04001365 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001366 } // if/else (fd != -1)
1367 return (allOK);
1368} // GPTDataTextUI::DestroyGPT()
1369
1370// Wipe MBR data from the disk (zero it out completely)
1371// Returns 1 on success, 0 on failure.
1372int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001373 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001374 uint8_t blankSector[512];
1375
srs569401f7f082011-03-15 23:53:31 -04001376 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001377
srs569401f7f082011-03-15 23:53:31 -04001378 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1379
srs569408bb0da2010-02-19 17:19:55 -05001380 if (!allOK)
1381 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1382 return allOK;
1383} // GPTData::DestroyMBR(void)
1384
srs5694e4ac11e2009-08-31 10:13:04 -04001385// Tell user whether Apple Partition Map (APM) was discovered....
1386void GPTData::ShowAPMState(void) {
1387 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001388 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001389 else
srs5694fed16d02010-01-27 23:03:40 -05001390 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001391} // GPTData::ShowAPMState()
1392
1393// Tell user about the state of the GPT data....
1394void GPTData::ShowGPTState(void) {
1395 switch (state) {
1396 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001397 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001398 break;
1399 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001400 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001401 break;
1402 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001403 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001404 break;
1405 default:
srs5694fed16d02010-01-27 23:03:40 -05001406 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001407 break;
1408 } // switch
1409} // GPTData::ShowGPTState()
1410
1411// Display the basic GPT data
1412void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001413 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001414 uint64_t temp, totalFree;
1415
srs5694fed16d02010-01-27 23:03:40 -05001416 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001417 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001418 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001419 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001420 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001421 cout << "First usable sector is " << mainHeader.firstUsableLBA
1422 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001423 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001424 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001425 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001426 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001427 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001428 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001429 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001430 } // for
1431} // GPTData::DisplayGPTData()
1432
srs5694e4ac11e2009-08-31 10:13:04 -04001433// Show detailed information on the specified partition
1434void GPTData::ShowPartDetails(uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001435 if ((partNum < numParts) && !IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001436 partitions[partNum].ShowDetails(blockSize);
1437 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001438 cout << "Partition #" << partNum + 1 << " does not exist.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001439 } // if
1440} // GPTData::ShowPartDetails()
1441
srs5694e4ac11e2009-08-31 10:13:04 -04001442/**************************************************************************
1443 * *
1444 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1445 * (some of these functions may require user interaction) *
1446 * *
1447 **************************************************************************/
1448
srs569408bb0da2010-02-19 17:19:55 -05001449// Examines the MBR & GPT data to determine which set of data to use: the
1450// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1451// a new set of partitions (use_new). A return value of use_abort indicates
1452// that this function couldn't determine what to do. Overriding functions
1453// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001454WhichToUse GPTData::UseWhichPartitions(void) {
1455 WhichToUse which = use_new;
1456 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001457
1458 mbrState = protectiveMBR.GetValidity();
1459
1460 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001461 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001462 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1463 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001464 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001465 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1466 << "typing 'q' if you don't want to convert your MBR partitions\n"
1467 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001468 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001469 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001470 which = use_mbr;
1471 } // if
1472
1473 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001474 cout << "\n**********************************************************************\n"
1475 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1476 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001477 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001478 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001479 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1480 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001481 } // if
srs5694fed16d02010-01-27 23:03:40 -05001482 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001483 which = use_bsd;
1484 } // if
1485
1486 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001487 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001488 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001489 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001490 } // if
1491 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001492 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001493 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001494 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001495 } // if
1496 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001497 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001498 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001499 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001500 } // if
1501 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001502 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001503 } // if
1504
srs5694e4ac11e2009-08-31 10:13:04 -04001505 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001506 if (mbrState == gpt) {
1507 cout << "\a\a****************************************************************************\n"
1508 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1509 << "verification and recovery are STRONGLY recommended.\n"
1510 << "****************************************************************************\n";
1511 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001512 } else {
srs569408bb0da2010-02-19 17:19:55 -05001513 which = use_abort;
1514 } // if/else MBR says disk is GPT
1515 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001516
1517 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001518 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001519
1520 return which;
1521} // UseWhichPartitions()
1522
srs569408bb0da2010-02-19 17:19:55 -05001523// Convert MBR partition table into GPT form.
1524void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001525 int i, numToConvert;
1526 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001527
1528 // Clear out old data & prepare basics....
1529 ClearGPTData();
1530
1531 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001532 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001533 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001534 else
srs56940283dae2010-04-28 16:44:34 -04001535 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001536
1537 for (i = 0; i < numToConvert; i++) {
1538 origType = protectiveMBR.GetType(i);
1539 // don't waste CPU time trying to convert extended, hybrid protective, or
1540 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001541 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001542 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001543 partitions[i] = protectiveMBR.AsGPT(i);
1544 } // for
1545
1546 // Convert MBR into protective MBR
1547 protectiveMBR.MakeProtectiveMBR();
1548
1549 // Record that all original CRCs were OK so as not to raise flags
1550 // when doing a disk verification
1551 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001552} // GPTData::XFormPartitions()
1553
1554// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001555// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001556// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001557int GPTData::XFormDisklabel(uint32_t partNum) {
1558 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001559 int goOn = 1, numDone = 0;
1560 BSDData disklabel;
1561
srs569408bb0da2010-02-19 17:19:55 -05001562 if (GetPartRange(&low, &high) == 0) {
1563 goOn = 0;
1564 cout << "No partitions!\n";
1565 } // if
1566 if (partNum > high) {
1567 goOn = 0;
1568 cout << "Specified partition is invalid!\n";
1569 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001570
srs569408bb0da2010-02-19 17:19:55 -05001571 // If all is OK, read the disklabel and convert it.
1572 if (goOn) {
1573 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1574 partitions[partNum].GetLastLBA());
1575 if ((goOn) && (disklabel.IsDisklabel())) {
1576 numDone = XFormDisklabel(&disklabel);
1577 if (numDone == 1)
1578 cout << "Converted 1 BSD partition.\n";
1579 else
1580 cout << "Converted " << numDone << " BSD partitions.\n";
1581 } else {
1582 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1583 } // if/else
1584 } // if
1585 if (numDone > 0) { // converted partitions; delete carrier
1586 partitions[partNum].BlankPartition();
1587 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001588 return numDone;
srs569455d92612010-03-07 22:16:07 -05001589} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001590
1591// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001592int GPTData::XFormDisklabel(BSDData* disklabel) {
1593 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001594
srs569408bb0da2010-02-19 17:19:55 -05001595 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001596 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001597 partNum = FindFirstFreePart();
1598 if (partNum >= 0) {
1599 partitions[partNum] = disklabel->AsGPT(i);
1600 if (partitions[partNum].IsUsed())
1601 numDone++;
1602 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001603 } // for
srs569408bb0da2010-02-19 17:19:55 -05001604 if (partNum == -1)
1605 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001606 } // if
1607
1608 // Record that all original CRCs were OK so as not to raise flags
1609 // when doing a disk verification
1610 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1611
1612 return numDone;
1613} // GPTData::XFormDisklabel(BSDData* disklabel)
1614
srs569408bb0da2010-02-19 17:19:55 -05001615// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1616// partition has the active/bootable flag UNset and uses the GPT fdisk
1617// type code divided by 0x0100 as the MBR type code.
1618// Returns 1 if operation was 100% successful, 0 if there were ANY
1619// problems.
srs5694978041c2009-09-21 20:51:47 -04001620int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001621 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001622
srs5694978041c2009-09-21 20:51:47 -04001623 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001624 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001625 allOK = 0;
1626 } // if
srs56940283dae2010-04-28 16:44:34 -04001627 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001628 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001629 allOK = 0;
1630 } // if
1631 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001632 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001633 allOK = 0;
1634 } // if
1635 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1636 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1637 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001638 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1639 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001640 } // if
srs5694978041c2009-09-21 20:51:47 -04001641 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001642 (uint32_t) partitions[gptPart].GetLengthLBA(),
1643 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001644 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001645 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1646 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1647 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001648 allOK = 0;
1649 } // if/else
1650 return allOK;
1651} // GPTData::OnePartToMBR()
1652
srs5694e4ac11e2009-08-31 10:13:04 -04001653
1654/**********************************************************************
1655 * *
1656 * Functions that adjust GPT data structures WITHOUT user interaction *
1657 * (they may display information for the user's benefit, though) *
1658 * *
1659 **********************************************************************/
1660
1661// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001662// necessary, copies data if it already exists. If fillGPTSectors is 1
1663// (the default), rounds numEntries to fill all the sectors necessary to
1664// hold the GPT.
1665// Returns 1 if all goes well, 0 if an error is encountered.
1666int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001667 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001668 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001669 int allOK = 1;
1670
1671 // First, adjust numEntries upward, if necessary, to get a number
1672 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001673 entriesPerSector = blockSize / GPT_SIZE;
1674 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001675 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001676 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001677 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001678 } // if
1679
srs5694247657a2009-11-26 18:36:12 -05001680 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001681 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001682 // partition table, which causes problems when loading data from a RAID
1683 // array that's been expanded because this function is called when loading
1684 // data.
srs56940283dae2010-04-28 16:44:34 -04001685 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001686 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001687 if (newParts != NULL) {
1688 if (partitions != NULL) { // existing partitions; copy them over
1689 GetPartRange(&i, &high);
1690 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001691 cout << "The highest-numbered partition is " << high + 1
1692 << ", which is greater than the requested\n"
1693 << "partition table size of " << numEntries
1694 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001695 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001696 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001697 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001698 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001699 copyNum = numEntries;
1700 else
srs56940283dae2010-04-28 16:44:34 -04001701 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001702 for (i = 0; i < copyNum; i++) {
1703 newParts[i] = partitions[i];
1704 } // for
srs569401f7f082011-03-15 23:53:31 -04001705 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001706 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001707 } // if
1708 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001709 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001710 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001711 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001712 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001713 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1714 MoveSecondHeaderToEnd();
1715 if (diskSize > 0)
1716 CheckGPTSize();
1717 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001718 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001719 allOK = 0;
1720 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001721 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001722 mainHeader.numParts = numParts;
1723 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001724 return (allOK);
1725} // GPTData::SetGPTSize()
1726
1727// Blank the partition array
1728void GPTData::BlankPartitions(void) {
1729 uint32_t i;
1730
srs56940283dae2010-04-28 16:44:34 -04001731 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001732 partitions[i].BlankPartition();
1733 } // for
1734} // GPTData::BlankPartitions()
1735
srs5694ba00fed2010-01-12 18:18:36 -05001736// Delete a partition by number. Returns 1 if successful,
1737// 0 if there was a problem. Returns 1 if partition was in
1738// range, 0 if it was out of range.
1739int GPTData::DeletePartition(uint32_t partNum) {
1740 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001741 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001742
srs56940283dae2010-04-28 16:44:34 -04001743 numUsedParts = GetPartRange(&low, &high);
1744 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001745 // In case there's a protective MBR, look for & delete matching
1746 // MBR partition....
1747 startSector = partitions[partNum].GetFirstLBA();
1748 length = partitions[partNum].GetLengthLBA();
1749 protectiveMBR.DeleteByLocation(startSector, length);
1750
1751 // Now delete the GPT partition
1752 partitions[partNum].BlankPartition();
1753 } else {
srs5694fed16d02010-01-27 23:03:40 -05001754 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001755 retval = 0;
1756 } // if/else
1757 return retval;
1758} // GPTData::DeletePartition(uint32_t partNum)
1759
srs569408bb0da2010-02-19 17:19:55 -05001760// Non-interactively create a partition.
1761// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001762uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001763 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001764 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001765
1766 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001767 if (Align(&startSector)) {
1768 cout << "Information: Moved requested sector from " << origSector << " to "
1769 << startSector << " in\norder to align on " << sectorAlignment
1770 << "-sector boundaries.\n";
1771 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001772 if (IsFree(startSector) && (startSector <= endSector)) {
1773 if (FindLastInFree(startSector) >= endSector) {
1774 partitions[partNum].SetFirstLBA(startSector);
1775 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001776 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001777 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001778 } else retval = 0; // if free space until endSector
1779 } else retval = 0; // if startSector is free
1780 } else retval = 0; // if legal partition number
1781 return retval;
1782} // GPTData::CreatePartition(partNum, startSector, endSector)
1783
srs5694e4ac11e2009-08-31 10:13:04 -04001784// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001785// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001786void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001787 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001788 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001789} // GPTData::SortGPT()
1790
srs569408bb0da2010-02-19 17:19:55 -05001791// Swap the contents of two partitions.
1792// Returns 1 if successful, 0 if either partition is out of range
1793// (that is, not a legal number; either or both can be empty).
1794// Note that if partNum1 = partNum2 and this number is in range,
1795// it will be considered successful.
1796int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1797 GPTPart temp;
1798 int allOK = 1;
1799
srs56940283dae2010-04-28 16:44:34 -04001800 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001801 if (partNum1 != partNum2) {
1802 temp = partitions[partNum1];
1803 partitions[partNum1] = partitions[partNum2];
1804 partitions[partNum2] = temp;
1805 } // if
1806 } else allOK = 0; // partition numbers are valid
1807 return allOK;
1808} // GPTData::SwapPartitions()
1809
srs5694e4ac11e2009-08-31 10:13:04 -04001810// Set up data structures for entirely new set of partitions on the
1811// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001812// Note that this function does NOT clear the protectiveMBR data
1813// structure, since it may hold the original MBR partitions if the
1814// program was launched on an MBR disk, and those may need to be
1815// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001816int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001817 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001818
1819 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001820 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001821 partitions = NULL;
1822 SetGPTSize(NUM_GPT_ENTRIES);
1823
1824 // Now initialize a bunch of stuff that's static....
1825 mainHeader.signature = GPT_SIGNATURE;
1826 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001827 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001828 mainHeader.reserved = 0;
1829 mainHeader.currentLBA = UINT64_C(1);
1830 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1831 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1832 for (i = 0; i < GPT_RESERVED; i++) {
1833 mainHeader.reserved2[i] = '\0';
1834 } // for
srs56940873e9d2010-10-07 13:00:45 -04001835 if (blockSize > 0)
1836 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1837 else
1838 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001839
1840 // Now some semi-static items (computed based on end of disk)
1841 mainHeader.backupLBA = diskSize - UINT64_C(1);
1842 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1843
1844 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001845 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001846
1847 // Copy main header to backup header
1848 RebuildSecondHeader();
1849
1850 // Blank out the partitions array....
1851 BlankPartitions();
1852
1853 // Flag all CRCs as being OK....
1854 mainCrcOk = 1;
1855 secondCrcOk = 1;
1856 mainPartsCrcOk = 1;
1857 secondPartsCrcOk = 1;
1858
1859 return (goOn);
1860} // GPTData::ClearGPTData()
1861
srs5694247657a2009-11-26 18:36:12 -05001862// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001863// If the disk size has actually changed, this also adjusts the protective
1864// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001865// Used internally and called by the 'e' option on the recovery &
1866// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001867// to their arrays or to adjust data structures in restore operations
1868// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001869void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001870 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001871 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1872 if (protectiveMBR.GetValidity() == hybrid) {
1873 protectiveMBR.OptimizeEESize();
1874 RecomputeCHS();
1875 } // if
1876 if (protectiveMBR.GetValidity() == gpt)
1877 MakeProtectiveMBR();
1878 } // if
srs56948bb78762009-11-24 15:43:49 -05001879 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1880 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1881} // GPTData::FixSecondHeaderLocation()
1882
srs5694699941e2011-03-21 21:33:57 -04001883// Sets the partition's name to the specified UnicodeString without
1884// user interaction.
1885// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001886int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001887 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001888
srs5694699941e2011-03-21 21:33:57 -04001889 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001890 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001891 else
1892 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001893
1894 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001895} // GPTData::SetName
1896
1897// Set the disk GUID to the specified value. Note that the header CRCs must
1898// be recomputed after calling this function.
1899void GPTData::SetDiskGUID(GUIDData newGUID) {
1900 mainHeader.diskGUID = newGUID;
1901 secondHeader.diskGUID = newGUID;
1902} // SetDiskGUID()
1903
1904// Set the unique GUID of the specified partition. Returns 1 on
1905// successful completion, 0 if there were problems (invalid
1906// partition number).
1907int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1908 int retval = 0;
1909
srs56940283dae2010-04-28 16:44:34 -04001910 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001911 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001912 partitions[pn].SetUniqueGUID(theGUID);
1913 retval = 1;
1914 } // if
1915 } // if
1916 return retval;
1917} // GPTData::SetPartitionGUID()
1918
srs56949ba54212010-05-18 23:24:02 -04001919// Set new random GUIDs for the disk and all partitions. Intended to be used
1920// after disk cloning or similar operations that don't randomize the GUIDs.
1921void GPTData::RandomizeGUIDs(void) {
1922 uint32_t i;
1923
1924 mainHeader.diskGUID.Randomize();
1925 secondHeader.diskGUID = mainHeader.diskGUID;
1926 for (i = 0; i < numParts; i++)
1927 if (partitions[i].IsUsed())
1928 partitions[i].RandomizeUniqueGUID();
1929} // GPTData::RandomizeGUIDs()
1930
srs5694ba00fed2010-01-12 18:18:36 -05001931// Change partition type code non-interactively. Returns 1 if
1932// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001933int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1934 int retval = 1;
1935
1936 if (!IsFreePartNum(partNum)) {
1937 partitions[partNum].SetType(theGUID);
1938 } else retval = 0;
1939 return retval;
1940} // GPTData::ChangePartType()
1941
srs56949ba54212010-05-18 23:24:02 -04001942// Recompute the CHS values of all the MBR partitions. Used to reset
1943// CHS values that some BIOSes require, despite the fact that the
1944// resulting CHS values violate the GPT standard.
1945void GPTData::RecomputeCHS(void) {
1946 int i;
1947
1948 for (i = 0; i < 4; i++)
1949 protectiveMBR.RecomputeCHS(i);
1950} // GPTData::RecomputeCHS()
1951
srs56941d1448a2009-12-31 21:20:19 -05001952// Adjust sector number so that it falls on a sector boundary that's a
1953// multiple of sectorAlignment. This is done to improve the performance
1954// of Western Digital Advanced Format disks and disks with similar
1955// technology from other companies, which use 4096-byte sectors
1956// internally although they translate to 512-byte sectors for the
1957// benefit of the OS. If partitions aren't properly aligned on these
1958// disks, some filesystem data structures can span multiple physical
1959// sectors, degrading performance. This function should be called
1960// only on the FIRST sector of the partition, not the last!
1961// This function returns 1 if the alignment was altered, 0 if it
1962// was unchanged.
1963int GPTData::Align(uint64_t* sector) {
1964 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001965 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001966
1967 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001968 earlier = (*sector / sectorAlignment) * sectorAlignment;
1969 later = earlier + (uint64_t) sectorAlignment;
1970
1971 // Check to see that every sector between the earlier one and the
1972 // requested one is clear, and that it's not too early....
1973 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001974 sectorOK = 1;
1975 testSector = earlier;
1976 do {
1977 sectorOK = IsFree(testSector++);
1978 } while ((sectorOK == 1) && (testSector < *sector));
1979 if (sectorOK == 1) {
1980 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001981 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001982 } // if
1983 } // if firstUsableLBA check
1984
1985 // If couldn't move the sector earlier, try to move it later instead....
1986 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1987 sectorOK = 1;
1988 testSector = later;
1989 do {
1990 sectorOK = IsFree(testSector--);
1991 } while ((sectorOK == 1) && (testSector > *sector));
1992 if (sectorOK == 1) {
1993 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001994 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001995 } // if
1996 } // if
srs56941d1448a2009-12-31 21:20:19 -05001997 } // if
1998 return retval;
1999} // GPTData::Align()
2000
srs5694e4ac11e2009-08-31 10:13:04 -04002001/********************************************************
2002 * *
2003 * Functions that return data about GPT data structures *
2004 * (most of these are inline in gpt.h) *
2005 * *
2006 ********************************************************/
2007
2008// Find the low and high used partition numbers (numbered from 0).
2009// Return value is the number of partitions found. Note that the
2010// *low and *high values are both set to 0 when no partitions
2011// are found, as well as when a single partition in the first
2012// position exists. Thus, the return value is the only way to
2013// tell when no partitions exist.
2014int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2015 uint32_t i;
2016 int numFound = 0;
2017
srs56940283dae2010-04-28 16:44:34 -04002018 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04002019 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04002020 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002021 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04002022 *high = i; // since we're counting up, set the high value
2023 // Set the low value only if it's not yet found...
2024 if (*low == (numParts + 1)) *low = i;
2025 numFound++;
2026 } // if
2027 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04002028
2029 // Above will leave *low pointing to its "not found" value if no partitions
2030 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002031 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002032 *low = 0;
2033 return numFound;
2034} // GPTData::GetPartRange()
2035
srs569408bb0da2010-02-19 17:19:55 -05002036// Returns the value of the first free partition, or -1 if none is
2037// unused.
2038int GPTData::FindFirstFreePart(void) {
2039 int i = 0;
2040
2041 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002042 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002043 i++;
srs56940283dae2010-04-28 16:44:34 -04002044 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002045 i = -1;
2046 } else i = -1;
2047 return i;
2048} // GPTData::FindFirstFreePart()
2049
srs5694978041c2009-09-21 20:51:47 -04002050// Returns the number of defined partitions.
2051uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002052 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002053
srs56940283dae2010-04-28 16:44:34 -04002054 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002055 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002056 counted++;
2057 } // for
2058 return counted;
2059} // GPTData::CountParts()
2060
srs5694e4ac11e2009-08-31 10:13:04 -04002061/****************************************************
2062 * *
2063 * Functions that return data about disk free space *
2064 * *
2065 ****************************************************/
2066
2067// Find the first available block after the starting point; returns 0 if
2068// there are no available blocks left
2069uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2070 uint64_t first;
2071 uint32_t i;
2072 int firstMoved = 0;
2073
2074 // Begin from the specified starting point or from the first usable
2075 // LBA, whichever is greater...
2076 if (start < mainHeader.firstUsableLBA)
2077 first = mainHeader.firstUsableLBA;
2078 else
2079 first = start;
2080
2081 // ...now search through all partitions; if first is within an
2082 // existing partition, move it to the next sector after that
2083 // partition and repeat. If first was moved, set firstMoved
2084 // flag; repeat until firstMoved is not set, so as to catch
2085 // cases where partitions are out of sequential order....
2086 do {
2087 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002088 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002089 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002090 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002091 first = partitions[i].GetLastLBA() + 1;
2092 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002093 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002094 } // for
2095 } while (firstMoved == 1);
2096 if (first > mainHeader.lastUsableLBA)
2097 first = 0;
2098 return (first);
2099} // GPTData::FindFirstAvailable()
2100
2101// Finds the first available sector in the largest block of unallocated
2102// space on the disk. Returns 0 if there are no available blocks left
2103uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002104 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002105
2106 start = 0;
2107 do {
2108 firstBlock = FindFirstAvailable(start);
2109 if (firstBlock != UINT32_C(0)) { // something's free...
2110 lastBlock = FindLastInFree(firstBlock);
2111 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2112 if (segmentSize > selectedSize) {
2113 selectedSize = segmentSize;
2114 selectedSegment = firstBlock;
2115 } // if
2116 start = lastBlock + 1;
2117 } // if
2118 } while (firstBlock != 0);
2119 return selectedSegment;
2120} // GPTData::FindFirstInLargest()
2121
srs5694cb76c672010-02-11 22:22:22 -05002122// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002123// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002124uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002125 uint64_t last;
2126 uint32_t i;
2127 int lastMoved = 0;
2128
2129 // Start by assuming the last usable LBA is available....
2130 last = mainHeader.lastUsableLBA;
2131
2132 // ...now, similar to algorithm in FindFirstAvailable(), search
2133 // through all partitions, moving last when it's in an existing
2134 // partition. Set the lastMoved flag so we repeat to catch cases
2135 // where partitions are out of logical order.
2136 do {
2137 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002138 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002139 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002140 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002141 last = partitions[i].GetFirstLBA() - 1;
2142 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002143 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002144 } // for
2145 } while (lastMoved == 1);
2146 if (last < mainHeader.firstUsableLBA)
2147 last = 0;
2148 return (last);
2149} // GPTData::FindLastAvailable()
2150
2151// Find the last available block in the free space pointed to by start.
2152uint64_t GPTData::FindLastInFree(uint64_t start) {
2153 uint64_t nearestStart;
2154 uint32_t i;
2155
2156 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002157 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002158 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002159 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002160 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002161 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002162 } // for
2163 return (nearestStart);
2164} // GPTData::FindLastInFree()
2165
2166// Finds the total number of free blocks, the number of segments in which
2167// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002168uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002169 uint64_t start = UINT64_C(0); // starting point for each search
2170 uint64_t totalFound = UINT64_C(0); // running total
2171 uint64_t firstBlock; // first block in a segment
2172 uint64_t lastBlock; // last block in a segment
2173 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002174 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002175
2176 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002177 if (diskSize > 0) {
2178 do {
2179 firstBlock = FindFirstAvailable(start);
2180 if (firstBlock != UINT64_C(0)) { // something's free...
2181 lastBlock = FindLastInFree(firstBlock);
2182 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2183 if (segmentSize > *largestSegment) {
2184 *largestSegment = segmentSize;
2185 } // if
2186 totalFound += segmentSize;
2187 num++;
2188 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002189 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002190 } while (firstBlock != 0);
2191 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002192 *numSegments = num;
2193 return totalFound;
2194} // GPTData::FindFreeBlocks()
2195
srs569455d92612010-03-07 22:16:07 -05002196// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2197// If it's allocated, return the partition number to which it's allocated
2198// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2199// returned in partNum if the sector is in use by basic GPT data structures.)
2200int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002201 int isFree = 1;
2202 uint32_t i;
2203
srs56940283dae2010-04-28 16:44:34 -04002204 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002205 if ((sector >= partitions[i].GetFirstLBA()) &&
2206 (sector <= partitions[i].GetLastLBA())) {
2207 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002208 if (partNum != NULL)
2209 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002210 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002211 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002212 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002213 (sector > mainHeader.lastUsableLBA)) {
2214 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002215 if (partNum != NULL)
2216 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002217 } // if
2218 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002219} // GPTData::IsFree()
2220
srs5694815fb652011-03-18 12:35:56 -04002221// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002222int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002223 return ((partNum < numParts) && (partitions != NULL) &&
2224 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002225} // GPTData::IsFreePartNum()
2226
srs5694815fb652011-03-18 12:35:56 -04002227// Returns 1 if partNum is in use.
2228int GPTData::IsUsedPartNum(uint32_t partNum) {
2229 return ((partNum < numParts) && (partitions != NULL) &&
2230 (partitions[partNum].IsUsed()));
2231} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002232
2233/***********************************************************
2234 * *
2235 * Change how functions work or return information on them *
2236 * *
2237 ***********************************************************/
2238
2239// Set partition alignment value; partitions will begin on multiples of
2240// the specified value
2241void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002242 if (n > 0)
2243 sectorAlignment = n;
2244 else
2245 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002246} // GPTData::SetAlignment()
2247
2248// Compute sector alignment based on the current partitions (if any). Each
2249// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002250// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2251// sector size), but not by the previously-located alignment value, then the
2252// alignment value is adjusted down. If the computed alignment is less than 8
2253// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002254// is a safety measure for Advanced Format drives. If no partitions are
2255// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002256// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002257// drives are aligned to 2048-sector multiples but the program won't complain
2258// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002259// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002260// Returns the computed alignment value.
2261uint32_t GPTData::ComputeAlignment(void) {
2262 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002263 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002264
srs56940873e9d2010-10-07 13:00:45 -04002265 if (blockSize > 0)
2266 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2267 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002268 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002269 if (partitions[i].IsUsed()) {
2270 found = 0;
2271 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002272 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002273 if ((partitions[i].GetFirstLBA() % align) == 0) {
2274 found = 1;
2275 } else {
2276 exponent--;
2277 } // if/else
2278 } // while
2279 } // if
2280 } // for
srs56940873e9d2010-10-07 13:00:45 -04002281 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2282 align = MIN_AF_ALIGNMENT;
2283 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002284 return align;
2285} // GPTData::ComputeAlignment()
2286
srs5694e4ac11e2009-08-31 10:13:04 -04002287/********************************
2288 * *
2289 * Endianness support functions *
2290 * *
2291 ********************************/
2292
srs56942a9f5da2009-08-26 00:48:01 -04002293void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002294 ReverseBytes(&header->signature, 8);
2295 ReverseBytes(&header->revision, 4);
2296 ReverseBytes(&header->headerSize, 4);
2297 ReverseBytes(&header->headerCRC, 4);
2298 ReverseBytes(&header->reserved, 4);
2299 ReverseBytes(&header->currentLBA, 8);
2300 ReverseBytes(&header->backupLBA, 8);
2301 ReverseBytes(&header->firstUsableLBA, 8);
2302 ReverseBytes(&header->lastUsableLBA, 8);
2303 ReverseBytes(&header->partitionEntriesLBA, 8);
2304 ReverseBytes(&header->numParts, 4);
2305 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2306 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002307 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002308} // GPTData::ReverseHeaderBytes()
2309
srs56940283dae2010-04-28 16:44:34 -04002310// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002311void GPTData::ReversePartitionBytes() {
2312 uint32_t i;
2313
srs56940283dae2010-04-28 16:44:34 -04002314 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002315 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002316 } // for
2317} // GPTData::ReversePartitionBytes()
2318
srs56949ddc14b2010-08-22 22:44:42 -04002319// Validate partition number
2320bool GPTData::ValidPartNum (const uint32_t partNum) {
2321 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002322 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002323 return false;
2324 } // if
2325 return true;
2326} // GPTData::ValidPartNum
2327
srs56945a081752010-09-24 20:39:41 -04002328// Return a single partition for inspection (not modification!) by other
2329// functions.
2330const GPTPart & GPTData::operator[](uint32_t partNum) const {
2331 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002332 cerr << "Partition number out of range (" << partNum << " requested, but only "
2333 << numParts << " available)\n";
2334 exit(1);
2335 } // if
2336 if (partitions == NULL) {
2337 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2338 exit(1);
srs56945a081752010-09-24 20:39:41 -04002339 } // if
2340 return partitions[partNum];
2341} // operator[]
2342
2343// Return (not for modification!) the disk's GUID value
2344const GUIDData & GPTData::GetDiskGUID(void) const {
2345 return mainHeader.diskGUID;
2346} // GPTData::GetDiskGUID()
2347
srs56949ddc14b2010-08-22 22:44:42 -04002348// Manage attributes for a partition, based on commands passed to this function.
2349// (Function is non-interactive.)
2350// Returns 1 if a modification command succeeded, 0 if the command should not have
2351// modified data, and -1 if a modification command failed.
2352int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2353 int retval = 0;
2354 Attributes theAttr;
2355
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002356 if (partNum >= (int) numParts) {
2357 cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2358 retval = -1;
srs56949ddc14b2010-08-22 22:44:42 -04002359 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002360 if (command == "show") {
2361 ShowAttributes(partNum);
2362 } else if (command == "get") {
2363 GetAttribute(partNum, bits);
srs56949ddc14b2010-08-22 22:44:42 -04002364 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002365 theAttr = partitions[partNum].GetAttributes();
2366 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2367 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2368 retval = 1;
2369 } else {
2370 retval = -1;
2371 } // if/else
2372 } // if/elseif/else
2373 } // if/else invalid partition #
srs56949ddc14b2010-08-22 22:44:42 -04002374
2375 return retval;
2376} // GPTData::ManageAttributes()
2377
2378// Show all attributes for a specified partition....
2379void GPTData::ShowAttributes(const uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002380 if ((partNum < numParts) && partitions[partNum].IsUsed())
srs5694e69e6802012-01-20 22:37:12 -05002381 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002382} // GPTData::ShowAttributes
2383
2384// Show whether a single attribute bit is set (terse output)...
2385void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002386 if (partNum < numParts)
2387 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002388} // GPTData::GetAttribute
2389
2390
srs56942a9f5da2009-08-26 00:48:01 -04002391/******************************************
2392 * *
2393 * Additional non-class support functions *
2394 * *
2395 ******************************************/
2396
srs5694e7b4ff92009-08-18 13:16:10 -04002397// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2398// never fail these tests, but the struct types may fail depending on compile options.
2399// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2400// sizes.
2401int SizesOK(void) {
2402 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002403
2404 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002405 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002406 allOK = 0;
2407 } // if
2408 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002409 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002410 allOK = 0;
2411 } // if
2412 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002413 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002414 allOK = 0;
2415 } // if
2416 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002417 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002418 allOK = 0;
2419 } // if
2420 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002421 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002422 allOK = 0;
2423 } // if
srs5694978041c2009-09-21 20:51:47 -04002424 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002425 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002426 allOK = 0;
2427 } // if
2428 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002429 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002430 allOK = 0;
2431 } // if
srs5694221e0872009-08-29 15:00:31 -04002432 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002433 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002434 allOK = 0;
2435 } // if
srs56946699b012010-02-04 00:55:30 -05002436 if (sizeof(GUIDData) != 16) {
2437 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2438 allOK = 0;
2439 } // if
2440 if (sizeof(PartType) != 16) {
2441 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2442 allOK = 0;
2443 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002444 return (allOK);
2445} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002446