blob: 9960d8fb56f8d85d5b2c999d6999318d3af281ad [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2 data. */
3
srs5694e4ac11e2009-08-31 10:13:04 -04004/* By Rod Smith, initial coding January to February, 2009 */
srs5694e7b4ff92009-08-18 13:16:10 -04005
srs569464cbd172011-03-01 22:03:54 -05006/* This program is copyright (c) 2009-2011 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040022#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "crc32.h"
24#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040025#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040026#include "support.h"
27#include "parttypes.h"
28#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050029#include "diskio.h"
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
262 // Check for overlapping partitions....
263 problems += FindOverlaps();
264
srs569455d92612010-03-07 22:16:07 -0500265 // Check for insane partitions (start after end, hugely big, etc.)
266 problems += FindInsanePartitions();
267
srs5694e4ac11e2009-08-31 10:13:04 -0400268 // Check for mismatched MBR and GPT partitions...
269 problems += FindHybridMismatches();
270
srs5694327129e2010-09-22 01:07:31 -0400271 // Check for MBR-specific problems....
272 problems += VerifyMBR();
273
srs5694e4ac11e2009-08-31 10:13:04 -0400274 // Verify that partitions don't run into GPT data areas....
275 problems += CheckGPTSize();
276
srs56941d1448a2009-12-31 21:20:19 -0500277 // Check that partitions are aligned on proper boundaries (for WD Advanced
278 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400279 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500280 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500281 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
282 << sectorAlignment << "-sector boundary. This may\nresult "
283 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500284 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500285 } // if
286 } // for
srs569464cbd172011-03-01 22:03:54 -0500287 if (alignProbs > 0)
288 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
289 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500290
srs5694e4ac11e2009-08-31 10:13:04 -0400291 // Now compute available space, but only if no problems found, since
292 // problems could affect the results
293 if (problems == 0) {
294 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500295 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400296 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500297 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400298 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400299 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400300 } else {
srs56940a697312010-01-28 21:10:52 -0500301 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400302 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400303
304 return (problems);
305} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400306
307// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400308// do, issues a warning but takes no action. Returns number of problems
309// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400310int GPTData::CheckGPTSize(void) {
311 uint64_t overlap, firstUsedBlock, lastUsedBlock;
312 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400313 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400314
315 // first, locate the first & last used blocks
316 firstUsedBlock = UINT64_MAX;
317 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400318 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500319 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500320 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500321 firstUsedBlock = partitions[i].GetFirstLBA();
322 if (partitions[i].GetLastLBA() > lastUsedBlock) {
323 lastUsedBlock = partitions[i].GetLastLBA();
324 } // if
325 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400326 } // for
327
328 // If the disk size is 0 (the default), then it means that various
329 // variables aren't yet set, so the below tests will be useless;
330 // therefore we should skip everything
331 if (diskSize != 0) {
332 if (mainHeader.firstUsableLBA > firstUsedBlock) {
333 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500334 cout << "Warning! Main partition table overlaps the first partition by "
335 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400336 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500337 cout << "Try reducing the partition table size by " << overlap * 4
338 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400339 } else {
srs5694fed16d02010-01-27 23:03:40 -0500340 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400341 } // if/else
342 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400343 } // Problem at start of disk
344 if (mainHeader.lastUsableLBA < lastUsedBlock) {
345 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500346 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500347 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400348 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500349 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400350 } else {
srs5694fed16d02010-01-27 23:03:40 -0500351 cout << "Try reducing the partition table size by " << overlap * 4
352 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400353 } // if/else
354 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400355 } // Problem at end of disk
356 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400357 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400358} // GPTData::CheckGPTSize()
359
srs5694e7b4ff92009-08-18 13:16:10 -0400360// Check the validity of the GPT header. Returns 1 if the main header
361// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400362// 0 if neither is valid. Note that this function checks the GPT signature,
363// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400364int GPTData::CheckHeaderValidity(void) {
365 int valid = 3;
366
srs5694fed16d02010-01-27 23:03:40 -0500367 cout.setf(ios::uppercase);
368 cout.fill('0');
369
370 // Note: failed GPT signature checks produce no error message because
371 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400372 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400373 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400374 } else if ((mainHeader.revision != 0x00010000) && valid) {
375 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500376 cout << "Unsupported GPT version in main header; read 0x";
377 cout.width(8);
378 cout << hex << mainHeader.revision << ", should be\n0x";
379 cout.width(8);
380 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400381 } // if/else/if
382
srs5694d1b11e82011-09-18 21:12:28 -0400383 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400384 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400385 } else if ((secondHeader.revision != 0x00010000) && valid) {
386 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500387 cout << "Unsupported GPT version in backup header; read 0x";
388 cout.width(8);
389 cout << hex << secondHeader.revision << ", should be\n0x";
390 cout.width(8);
391 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400392 } // if/else/if
393
srs5694df9d3632011-01-08 18:33:24 -0500394 // Check for an Apple disk signature
395 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
396 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400397 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500398 } // if
srs5694fed16d02010-01-27 23:03:40 -0500399 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400400
srs5694fed16d02010-01-27 23:03:40 -0500401 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400402} // GPTData::CheckHeaderValidity()
403
404// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400405// Note: Must be called with header in platform-ordered byte order.
406// Returns 1 if header's computed CRC matches the stored value, 0 if the
407// computed and stored values don't match
408int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400409 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400410 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400411
srs56942a9f5da2009-08-26 00:48:01 -0400412 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400413 // computation to be valid
414 oldCRC = header->headerCRC;
415 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400416
srs5694978041c2009-09-21 20:51:47 -0400417 hSize = header->headerSize;
418
srs5694d1b11e82011-09-18 21:12:28 -0400419 if (IsLittleEndian() == 0)
420 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400421
srs5694d1b11e82011-09-18 21:12:28 -0400422 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
423 if (warn) {
424 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
425 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
426 } // if
427 hSize = HEADER_SIZE;
428 } else if ((hSize > sizeof(GPTHeader)) && warn) {
429 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
430 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
431 << "which may result in a CRC false alarm.\n";
432 } // if/elseif
433 temp = new uint8_t[hSize];
434 if (temp != NULL) {
435 memset(temp, 0, hSize);
436 if (hSize < sizeof(GPTHeader))
437 memcpy(temp, header, hSize);
438 else
439 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400440
srs5694d1b11e82011-09-18 21:12:28 -0400441 newCRC = chksum_crc32((unsigned char*) temp, hSize);
442 delete[] temp;
443 } else {
444 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
445 exit(1);
446 }
447 if (IsLittleEndian() == 0)
448 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400449 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400450 return (oldCRC == newCRC);
451} // GPTData::CheckHeaderCRC()
452
srs56946699b012010-02-04 00:55:30 -0500453// Recompute all the CRCs. Must be called before saving if any changes have
454// been made. Must be called on platform-ordered data (this function reverses
455// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400456void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400457 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400458 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400459
srs5694d1b11e82011-09-18 21:12:28 -0400460 // If the header size is bigger than the GPT header data structure, reset it;
461 // otherwise, set both header sizes to whatever the main one is....
462 if (mainHeader.headerSize > sizeof(GPTHeader))
463 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
464 else
465 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500466
467 if ((littleEndian = IsLittleEndian()) == 0) {
468 ReversePartitionBytes();
469 ReverseHeaderBytes(&mainHeader);
470 ReverseHeaderBytes(&secondHeader);
471 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400472
srs5694e7b4ff92009-08-18 13:16:10 -0400473 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400474 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400475 mainHeader.partitionEntriesCRC = crc;
476 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400477 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400478 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
479 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400480 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400481
srs5694d1b11e82011-09-18 21:12:28 -0400482 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400483 mainHeader.headerCRC = 0;
484 secondHeader.headerCRC = 0;
485
srs5694978041c2009-09-21 20:51:47 -0400486 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400487 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400488 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400489 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400490 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400491 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400492 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400493 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500494
srs5694d1b11e82011-09-18 21:12:28 -0400495 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500496 ReverseHeaderBytes(&mainHeader);
497 ReverseHeaderBytes(&secondHeader);
498 ReversePartitionBytes();
499 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400500} // GPTData::RecomputeCRCs()
501
srs5694e7b4ff92009-08-18 13:16:10 -0400502// Rebuild the main GPT header, using the secondary header as a model.
503// Typically called when the main header has been found to be corrupt.
504void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400505 mainHeader.signature = GPT_SIGNATURE;
506 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400507 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400508 mainHeader.headerCRC = UINT32_C(0);
509 mainHeader.reserved = secondHeader.reserved;
510 mainHeader.currentLBA = secondHeader.backupLBA;
511 mainHeader.backupLBA = secondHeader.currentLBA;
512 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
513 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500514 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400515 mainHeader.partitionEntriesLBA = UINT64_C(2);
516 mainHeader.numParts = secondHeader.numParts;
517 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
518 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400519 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500520 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500521 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400522} // GPTData::RebuildMainHeader()
523
524// Rebuild the secondary GPT header, using the main header as a model.
525void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400526 secondHeader.signature = GPT_SIGNATURE;
527 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400528 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400529 secondHeader.headerCRC = UINT32_C(0);
530 secondHeader.reserved = mainHeader.reserved;
531 secondHeader.currentLBA = mainHeader.backupLBA;
532 secondHeader.backupLBA = mainHeader.currentLBA;
533 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
534 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500535 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400536 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
537 secondHeader.numParts = mainHeader.numParts;
538 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
539 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400540 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500541 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500542 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400543} // GPTData::RebuildSecondHeader()
544
545// Search for hybrid MBR entries that have no corresponding GPT partition.
546// Returns number of such mismatches found
547int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500548 int i, found, numFound = 0;
549 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400550 uint64_t mbrFirst, mbrLast;
551
552 for (i = 0; i < 4; i++) {
553 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
554 j = 0;
555 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400556 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
557 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400558 do {
srs5694e4ac11e2009-08-31 10:13:04 -0400559 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500560 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400561 found = 1;
562 j++;
srs56940283dae2010-04-28 16:44:34 -0400563 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400564 if (!found) {
565 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500566 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
567 << i + 1 << ", of type 0x";
568 cout.fill('0');
569 cout.setf(ios::uppercase);
570 cout.width(2);
571 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
572 << "has no corresponding GPT partition! You may continue, but this condition\n"
573 << "might cause data loss in the future!\a\n" << dec;
574 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400575 } // if
576 } // if
577 } // for
578 return numFound;
579} // GPTData::FindHybridMismatches
580
581// Find overlapping partitions and warn user about them. Returns number of
582// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400583// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400584int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500585 int problems = 0;
586 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400587
srs56940283dae2010-04-28 16:44:34 -0400588 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400589 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500590 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
591 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400592 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500593 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
594 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
595 << " to " << partitions[i].GetLastLBA() << "\n";
596 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
597 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400598 } // if
599 } // for j...
600 } // for i...
601 return problems;
602} // GPTData::FindOverlaps()
603
srs569455d92612010-03-07 22:16:07 -0500604// Find partitions that are insane -- they start after they end or are too
605// big for the disk. (The latter should duplicate detection of overlaps
606// with GPT backup data structures, but better to err on the side of
607// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400608// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500609int GPTData::FindInsanePartitions(void) {
610 uint32_t i;
611 int problems = 0;
612
srs56940283dae2010-04-28 16:44:34 -0400613 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500614 if (partitions[i].IsUsed()) {
615 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
616 problems++;
617 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
618 } // if
619 if (partitions[i].GetLastLBA() >= diskSize) {
620 problems++;
621 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
622 } // if
srs569455d92612010-03-07 22:16:07 -0500623 } // if
624 } // for
625 return problems;
626} // GPTData::FindInsanePartitions(void)
627
628
srs5694e4ac11e2009-08-31 10:13:04 -0400629/******************************************************************
630 * *
631 * Begin functions that load data from disk or save data to disk. *
632 * *
633 ******************************************************************/
634
srs569464cbd172011-03-01 22:03:54 -0500635// Change the filename associated with the GPT. Used for duplicating
636// the partition table to a new disk and saving backups.
637// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500638int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500639 int err, allOK = 1;
640
641 device = deviceFilename;
642 if (allOK && myDisk.OpenForRead(deviceFilename)) {
643 // store disk information....
644 diskSize = myDisk.DiskSize(&err);
645 blockSize = (uint32_t) myDisk.GetBlockSize();
646 } // if
647 protectiveMBR.SetDisk(&myDisk);
648 protectiveMBR.SetDiskSize(diskSize);
649 protectiveMBR.SetBlockSize(blockSize);
650 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500651} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500652
srs5694e4ac11e2009-08-31 10:13:04 -0400653// Scan for partition data. This function loads the MBR data (regular MBR or
654// protective MBR) and loads BSD disklabel data (which is probably invalid).
655// It also looks for APM data, forces a load of GPT data, and summarizes
656// the results.
srs5694546a9c72010-01-26 16:00:26 -0500657void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400658 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400659
660 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500661 protectiveMBR.ReadMBRData(&myDisk);
662 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400663
664 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500665 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500666
667 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500668 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500669 protectiveMBR.ShowState();
670 bsdDisklabel.ShowState();
671 ShowAPMState(); // Show whether there's an Apple Partition Map present
672 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500673 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500674 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400675
676 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500677 cout << "\n*******************************************************************\n"
678 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500679 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500680 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500681 } // if
srs5694fed16d02010-01-27 23:03:40 -0500682 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400683 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400684} // GPTData::PartitionScan()
685
686// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500687int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500688 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500689 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500690 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400691
srs5694546a9c72010-01-26 16:00:26 -0500692 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500693 err = myDisk.OpenForWrite(deviceFilename);
694 if ((err == 0) && (!justLooking)) {
695 cout << "\aNOTE: Write test failed with error number " << errno
696 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
697#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
698 cout << "You may be able to enable writes by exiting this program, typing\n"
699 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
700 << "program.\n";
701#endif
702 cout << "\n";
703 } // if
704 myDisk.Close(); // Close and re-open read-only in case of bugs
705 } else allOK = 0; // if
706
707 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400708 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500709 diskSize = myDisk.DiskSize(&err);
710 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500711 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500712 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400713
srs5694ba00fed2010-01-12 18:18:36 -0500714 whichWasUsed = UseWhichPartitions();
715 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400716 case use_mbr:
717 XFormPartitions();
718 break;
719 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500720 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400721// bsdDisklabel.DisplayBSDData();
722 ClearGPTData();
723 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500724 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400725 break;
726 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500727 mbrState = protectiveMBR.GetValidity();
728 if ((mbrState == invalid) || (mbrState == mbr))
729 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400730 break;
731 case use_new:
732 ClearGPTData();
733 protectiveMBR.MakeProtectiveMBR();
734 break;
srs56943c0af382010-01-15 19:19:18 -0500735 case use_abort:
736 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400737 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500738 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400739 } // switch
740
srs569455d92612010-03-07 22:16:07 -0500741 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500742 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500743 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400744 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400745 } else {
746 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400747 } // if/else
748 return (allOK);
749} // GPTData::LoadPartitions()
750
751// Loads the GPT, as much as possible. Returns 1 if this seems to have
752// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500753int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500754 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400755
srs5694cb76c672010-02-11 22:22:22 -0500756 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400757
srs5694cb76c672010-02-11 22:22:22 -0500758 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
759 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
760 } else {
srs569408bb0da2010-02-19 17:19:55 -0500761 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
762 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500763 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
764 << "secondary header from the last sector of the disk! You should use 'v' to\n"
765 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
766 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500767 } // if/else
768 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400769 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400770
771 // Return valid headers code: 0 = both headers bad; 1 = main header
772 // good, backup bad; 2 = backup header good, main header bad;
773 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400774 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400775 validHeaders = CheckHeaderValidity();
776
777 // Read partitions (from primary array)
778 if (validHeaders > 0) { // if at least one header is OK....
779 // GPT appears to be valid....
780 state = gpt_valid;
781
782 // We're calling the GPT valid, but there's a possibility that one
783 // of the two headers is corrupt. If so, use the one that seems to
784 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500785 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500786 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
787 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400788 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500789 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400790 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500791 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500792 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
793 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500794 RebuildMainHeader();
795 state = gpt_corrupt;
796 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400797 } // if/else/if
798
srs5694546a9c72010-01-26 16:00:26 -0500799 // Figure out which partition table to load....
800 // Load the main partition table, since either its header's CRC is OK or the
801 // backup header's CRC is not OK....
802 if (mainCrcOk || !secondCrcOk) {
803 if (LoadMainTable() == 0)
804 allOK = 0;
805 } else { // bad main header CRC and backup header CRC is OK
806 state = gpt_corrupt;
807 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500808 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500809 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500810 } else { // backup table bad, bad main header CRC, but try main table in desperation....
811 if (LoadMainTable() == 0) {
812 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500813 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500814 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500815 } // if
816 } // if/else (LoadSecondTableAsMain())
817 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400818
srs5694cb76c672010-02-11 22:22:22 -0500819 if (loadedTable == 1)
820 secondPartsCrcOk = CheckTable(&secondHeader);
821 else if (loadedTable == 2)
822 mainPartsCrcOk = CheckTable(&mainHeader);
823 else
824 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400825
srs5694546a9c72010-01-26 16:00:26 -0500826 // Problem with main partition table; if backup is OK, use it instead....
827 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
828 state = gpt_corrupt;
829 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500830 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500831 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
832 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500833 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500834
srs5694e4ac11e2009-08-31 10:13:04 -0400835 // Check for valid CRCs and warn if there are problems
836 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
837 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500838 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400839 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500840 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400841 } else {
842 state = gpt_invalid;
843 } // if/else
844 return allOK;
845} // GPTData::ForceLoadGPTData()
846
srs5694247657a2009-11-26 18:36:12 -0500847// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400848// main GPT header in memory MUST be valid for this call to do anything
849// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500850// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400851int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500852 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400853} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400854
855// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500856// table. Used in repair functions, and when starting up if the main
857// partition table is damaged.
858// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
859int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500860 return LoadPartitionTable(secondHeader, myDisk);
861} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400862
srs5694cb76c672010-02-11 22:22:22 -0500863// Load a single GPT header (main or backup) from the specified disk device and
864// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
865// value appropriately.
866// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
867// failure.
868int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
869 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500870 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500871
872 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500873 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500874 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
875 allOK = 0;
876 } // if
srs5694cb76c672010-02-11 22:22:22 -0500877
srs56941c6f8b02010-02-21 11:09:20 -0500878 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500879 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500880 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500881 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400882 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500883
srs56940283dae2010-04-28 16:44:34 -0400884 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500885 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500886 }
srs56941c6f8b02010-02-21 11:09:20 -0500887
888 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500889 return allOK;
890} // GPTData::LoadHeader
891
892// Load a partition table (either main or secondary) from the specified disk,
893// using header as a reference for what to load. If sector != 0 (the default
894// is 0), loads from the specified sector; otherwise loads from the sector
895// indicated in header.
896// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
897int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
898 uint32_t sizeOfParts, newCRC;
899 int retval;
900
901 if (disk.OpenForRead()) {
902 if (sector == 0) {
903 retval = disk.Seek(header.partitionEntriesLBA);
904 } else {
905 retval = disk.Seek(sector);
906 } // if/else
srs569455d92612010-03-07 22:16:07 -0500907 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500908 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500909 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500910 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
911 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500912 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500913 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500914 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400915 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500916 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400917 if (IsLittleEndian() == 0)
918 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500919 if (!mainPartsCrcOk) {
920 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400921 } // if
922 } else {
srs5694cb76c672010-02-11 22:22:22 -0500923 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400924 } // if/else
925 } else {
srs5694fed16d02010-01-27 23:03:40 -0500926 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500927 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500928 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400929 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500930 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500931} // GPTData::LoadPartitionsTable()
932
933// Check the partition table pointed to by header, but don't keep it
934// around.
srs5694a17fe692011-09-10 20:30:20 -0400935// Returns 1 if the CRC is OK & this table matches the one already in memory,
936// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500937int GPTData::CheckTable(struct GPTHeader *header) {
938 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400939 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400940 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400941 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500942
srs56940283dae2010-04-28 16:44:34 -0400943 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500944 // its CRC and store the results, then discard this temporary
945 // storage, since we don't use it in any but recovery operations
946 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400947 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400948 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -0400949 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -0400950 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
951 exit(1);
952 } // if
srs5694a17fe692011-09-10 20:30:20 -0400953 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400954 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500955 } else {
srs5694d1b11e82011-09-18 21:12:28 -0400956 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -0400957 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -0400958 if (header == &mainHeader)
959 otherHeader = &secondHeader;
960 else
961 otherHeader = &mainHeader;
962 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -0400963 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
964 << "on the recovery & transformation menu to examine the two tables.\n\n";
965 allOK = 0;
966 } // if
srs5694cb76c672010-02-11 22:22:22 -0500967 } // if/else
srs5694a17fe692011-09-10 20:30:20 -0400968 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -0500969 } // if
srs5694a17fe692011-09-10 20:30:20 -0400970 return allOK;
srs5694cb76c672010-02-11 22:22:22 -0500971} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400972
srs56944307ef22012-05-30 12:30:48 -0400973// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
974// header later on the disk without asking for permission, if necessary, and
975// doesn't confirm the operation before writing. If quiet==0, asks permission
976// before moving the second header and asks for final confirmation of any
977// write.
srs5694a17fe692011-09-10 20:30:20 -0400978// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500979int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -0400980 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -0500981 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400982
srs5694e7b4ff92009-08-18 13:16:10 -0400983 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500984
985 // This test should only fail on read-only disks....
986 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500987 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500988 allOK = 0;
989 } // if
990
srs569464cbd172011-03-01 22:03:54 -0500991 // Check that disk is really big enough to handle the second header...
992 if (mainHeader.backupLBA >= diskSize) {
993 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
994 << "header, but other problems may occur!\n";
995 MoveSecondHeaderToEnd();
996 } // if
997
srs5694e7b4ff92009-08-18 13:16:10 -0400998 // Is there enough space to hold the GPT headers and partition tables,
999 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001000 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001001 allOK = 0;
1002 } // if
1003
srs5694247657a2009-11-26 18:36:12 -05001004 // Check that second header is properly placed. Warn and ask if this should
1005 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001006 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1007 if (quiet == 0) {
1008 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1009 << "correct this problem? ";
1010 if (GetYN() == 'Y') {
1011 MoveSecondHeaderToEnd();
1012 cout << "Have moved second header and partition table to correct location.\n";
1013 } else {
1014 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1015 } // if correction requested
1016 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001017 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001018 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001019 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001020
srs569455d92612010-03-07 22:16:07 -05001021 // Check for overlapping or insane partitions....
1022 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001023 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001024 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001025 } // if
1026
1027 // Check for mismatched MBR and GPT data, but let it pass if found
1028 // (function displays warning message)
1029 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001030
1031 RecomputeCRCs();
1032
srs5694ba00fed2010-01-12 18:18:36 -05001033 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001034 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001035 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001036 answer = GetYN();
1037 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001038 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001039 } else {
1040 allOK = 0;
1041 } // if/else
1042 } // if
1043
1044 // Do it!
1045 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001046 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001047 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001048 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001049 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001050 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1051 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001052 syncIt = 0;
1053 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001054
1055 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001056 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1057
1058 // Now write the main partition tables...
1059 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1060
1061 // Now write the main GPT header...
1062 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1063
1064 // To top it off, write the protective MBR...
1065 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001066
1067 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001068 // Note: Done even if some write operations failed, but not if all of them failed.
1069 // Done this way because I've received one problem report from a user one whose
1070 // system the MBR write failed but everything else was OK (on a GPT disk under
1071 // Windows), and the failure to sync therefore caused Windows to restore the
1072 // original partition table from its cache. OTOH, such restoration might be
1073 // desirable if the error occurs later; but that seems unlikely unless the initial
1074 // write fails....
1075 if (syncIt)
srs5694546a9c72010-01-26 16:00:26 -05001076 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001077
1078 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001079 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001080 } else {
srs5694fed16d02010-01-27 23:03:40 -05001081 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001082 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001083 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001084
srs5694546a9c72010-01-26 16:00:26 -05001085 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001086 } else {
srs56945a608532011-03-17 13:53:01 -04001087 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001088 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001089 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001090 } // if/else
1091 } else {
srs5694fed16d02010-01-27 23:03:40 -05001092 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001093 } // if
1094
1095 return (allOK);
1096} // GPTData::SaveGPTData()
1097
1098// Save GPT data to a backup file. This function does much less error
1099// checking than SaveGPTData(). It can therefore preserve many types of
1100// corruption for later analysis; however, it preserves only the MBR,
1101// the main GPT header, the backup GPT header, and the main partition
1102// table; it discards the backup partition table, since it should be
1103// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001104int GPTData::SaveGPTBackup(const string & filename) {
1105 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001106 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001107
srs5694546a9c72010-01-26 16:00:26 -05001108 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001109 // Recomputing the CRCs is likely to alter them, which could be bad
1110 // if the intent is to save a potentially bad GPT for later analysis;
1111 // but if we don't do this, we get bogus errors when we load the
1112 // backup. I'm favoring misses over false alarms....
1113 RecomputeCRCs();
1114
srs5694546a9c72010-01-26 16:00:26 -05001115 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001116 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001117
srs5694cb76c672010-02-11 22:22:22 -05001118 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001119 // MBR write closed disk, so re-open and seek to end....
1120 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001121 allOK = SaveHeader(&mainHeader, backupFile, 1);
1122 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001123
srs5694e7b4ff92009-08-18 13:16:10 -04001124 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001125 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001126
srs5694cb76c672010-02-11 22:22:22 -05001127 if (allOK)
1128 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001129
1130 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001131 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001132 } else {
srs5694fed16d02010-01-27 23:03:40 -05001133 cerr << "Warning! An error was reported when writing the backup file.\n"
1134 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001135 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001136 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001137 } else {
srs56945a608532011-03-17 13:53:01 -04001138 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001139 allOK = 0;
1140 } // if/else
1141 return allOK;
1142} // GPTData::SaveGPTBackup()
1143
srs5694cb76c672010-02-11 22:22:22 -05001144// Write a GPT header (main or backup) to the specified sector. Used by both
1145// the SaveGPTData() and SaveGPTBackup() functions.
1146// Should be passed an architecture-appropriate header (DO NOT call
1147// ReverseHeaderBytes() on the header before calling this function)
1148// Returns 1 on success, 0 on failure
1149int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1150 int littleEndian, allOK = 1;
1151
1152 littleEndian = IsLittleEndian();
1153 if (!littleEndian)
1154 ReverseHeaderBytes(header);
1155 if (disk.Seek(sector)) {
1156 if (disk.Write(header, 512) == -1)
1157 allOK = 0;
1158 } else allOK = 0; // if (disk.Seek()...)
1159 if (!littleEndian)
1160 ReverseHeaderBytes(header);
1161 return allOK;
1162} // GPTData::SaveHeader()
1163
1164// Save the partitions to the specified sector. Used by both the SaveGPTData()
1165// and SaveGPTBackup() functions.
1166// Should be passed an architecture-appropriate header (DO NOT call
1167// ReverseHeaderBytes() on the header before calling this function)
1168// Returns 1 on success, 0 on failure
1169int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1170 int littleEndian, allOK = 1;
1171
1172 littleEndian = IsLittleEndian();
1173 if (disk.Seek(sector)) {
1174 if (!littleEndian)
1175 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001176 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001177 allOK = 0;
1178 if (!littleEndian)
1179 ReversePartitionBytes();
1180 } else allOK = 0; // if (myDisk.Seek()...)
1181 return allOK;
1182} // GPTData::SavePartitionTable()
1183
srs5694e7b4ff92009-08-18 13:16:10 -04001184// Load GPT data from a backup file created by SaveGPTBackup(). This function
1185// does minimal error checking. It returns 1 if it completed successfully,
1186// 0 if there was a problem. In the latter case, it creates a new empty
1187// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001188int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001189 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001190 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001191 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001192
srs5694546a9c72010-01-26 16:00:26 -05001193 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001194 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001195 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001196 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001197
srs5694cb76c672010-02-11 22:22:22 -05001198 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001199
srs5694cb76c672010-02-11 22:22:22 -05001200 // Check backup file size and rebuild second header if file is right
1201 // size to be direct dd copy of MBR, main header, and main partition
1202 // table; if other size, treat it like a GPT fdisk-generated backup
1203 // file
1204 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1205 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1206 if (shortBackup) {
1207 RebuildSecondHeader();
1208 secondCrcOk = mainCrcOk;
1209 } else {
1210 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1211 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001212
srs5694e7b4ff92009-08-18 13:16:10 -04001213 // Return valid headers code: 0 = both headers bad; 1 = main header
1214 // good, backup bad; 2 = backup header good, main header bad;
1215 // 3 = both headers good. Note these codes refer to valid GPT
1216 // signatures and version numbers; more subtle problems will elude
1217 // this check!
1218 if ((val = CheckHeaderValidity()) > 0) {
1219 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001220 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001221 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001222 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001223 } // if/else
1224
srs5694e7b4ff92009-08-18 13:16:10 -04001225 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1227 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001228 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001229 } // if
1230
srs5694cb76c672010-02-11 22:22:22 -05001231 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1232 cerr << "Warning! Read error " << errno
1233 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001234 } else {
1235 allOK = 0;
1236 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001237 // Something went badly wrong, so blank out partitions
1238 if (allOK == 0) {
1239 cerr << "Improper backup file! Clearing all partition data!\n";
1240 ClearGPTData();
1241 protectiveMBR.MakeProtectiveMBR();
1242 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001243 } else {
1244 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001245 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001246 } // if/else
1247
srs5694e7b4ff92009-08-18 13:16:10 -04001248 return allOK;
1249} // GPTData::LoadGPTBackup()
1250
srs569408bb0da2010-02-19 17:19:55 -05001251int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001252 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001253} // GPTData::SaveMBR()
1254
1255// This function destroys the on-disk GPT structures, but NOT the on-disk
1256// MBR.
1257// Returns 1 if the operation succeeds, 0 if not.
1258int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001259 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001260 uint8_t blankSector[512];
1261 uint8_t* emptyTable;
1262
srs569401f7f082011-03-15 23:53:31 -04001263 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001264
1265 if (myDisk.OpenForWrite()) {
1266 if (!myDisk.Seek(mainHeader.currentLBA))
1267 allOK = 0;
1268 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1269 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1270 allOK = 0;
1271 } // if
1272 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1273 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001274 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001275 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001276 if (emptyTable == NULL) {
srs5694a17fe692011-09-10 20:30:20 -04001277 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
srs56946aae2a92011-06-10 01:16:51 -04001278 exit(1);
1279 } // if
srs569401f7f082011-03-15 23:53:31 -04001280 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001281 if (allOK) {
1282 sum = myDisk.Write(emptyTable, tableSize);
1283 if (sum != tableSize) {
1284 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1285 allOK = 0;
1286 } // if write failed
1287 } // if
1288 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1289 allOK = 0;
1290 if (allOK) {
1291 sum = myDisk.Write(emptyTable, tableSize);
1292 if (sum != tableSize) {
1293 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1294 << errno << "\n";
1295 allOK = 0;
1296 } // if wrong size written
1297 } // if
1298 if (!myDisk.Seek(secondHeader.currentLBA))
1299 allOK = 0;
1300 if (allOK) {
1301 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1302 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1303 allOK = 0;
1304 } // if
1305 } // if
1306 myDisk.DiskSync();
1307 myDisk.Close();
1308 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1309 << "other utilities.\n";
1310 delete[] emptyTable;
1311 } else {
srs56945a608532011-03-17 13:53:01 -04001312 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001313 } // if/else (fd != -1)
1314 return (allOK);
1315} // GPTDataTextUI::DestroyGPT()
1316
1317// Wipe MBR data from the disk (zero it out completely)
1318// Returns 1 on success, 0 on failure.
1319int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001320 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001321 uint8_t blankSector[512];
1322
srs569401f7f082011-03-15 23:53:31 -04001323 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001324
srs569401f7f082011-03-15 23:53:31 -04001325 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1326
srs569408bb0da2010-02-19 17:19:55 -05001327 if (!allOK)
1328 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1329 return allOK;
1330} // GPTData::DestroyMBR(void)
1331
srs5694e4ac11e2009-08-31 10:13:04 -04001332// Tell user whether Apple Partition Map (APM) was discovered....
1333void GPTData::ShowAPMState(void) {
1334 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001335 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001336 else
srs5694fed16d02010-01-27 23:03:40 -05001337 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001338} // GPTData::ShowAPMState()
1339
1340// Tell user about the state of the GPT data....
1341void GPTData::ShowGPTState(void) {
1342 switch (state) {
1343 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001344 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001345 break;
1346 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001347 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001348 break;
1349 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001350 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001351 break;
1352 default:
srs5694fed16d02010-01-27 23:03:40 -05001353 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001354 break;
1355 } // switch
1356} // GPTData::ShowGPTState()
1357
1358// Display the basic GPT data
1359void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001360 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001361 uint64_t temp, totalFree;
1362
srs5694fed16d02010-01-27 23:03:40 -05001363 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001364 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001365 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001366 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001367 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001368 cout << "First usable sector is " << mainHeader.firstUsableLBA
1369 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001370 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001371 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001372 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001373 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001374 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001375 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001376 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001377 } // for
1378} // GPTData::DisplayGPTData()
1379
srs5694e4ac11e2009-08-31 10:13:04 -04001380// Show detailed information on the specified partition
1381void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001382 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001383 partitions[partNum].ShowDetails(blockSize);
1384 } else {
srs5694fed16d02010-01-27 23:03:40 -05001385 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001386 } // if
1387} // GPTData::ShowPartDetails()
1388
srs5694e4ac11e2009-08-31 10:13:04 -04001389/**************************************************************************
1390 * *
1391 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1392 * (some of these functions may require user interaction) *
1393 * *
1394 **************************************************************************/
1395
srs569408bb0da2010-02-19 17:19:55 -05001396// Examines the MBR & GPT data to determine which set of data to use: the
1397// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1398// a new set of partitions (use_new). A return value of use_abort indicates
1399// that this function couldn't determine what to do. Overriding functions
1400// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001401WhichToUse GPTData::UseWhichPartitions(void) {
1402 WhichToUse which = use_new;
1403 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001404
1405 mbrState = protectiveMBR.GetValidity();
1406
1407 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001408 cout << "\n***************************************************************\n"
1409 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001410 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001411 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001412 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001413 } // if
srs5694fed16d02010-01-27 23:03:40 -05001414 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001415 which = use_mbr;
1416 } // if
1417
1418 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001419 cout << "\n**********************************************************************\n"
1420 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1421 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001422 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001423 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001424 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1425 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001426 } // if
srs5694fed16d02010-01-27 23:03:40 -05001427 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001428 which = use_bsd;
1429 } // if
1430
1431 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001432 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001433 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001434 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001435 } // if
1436 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001437 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001438 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001439 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001440 } // if
1441 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001442 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001443 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001444 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001445 } // if
1446 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001447 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001448 } // if
1449
srs5694e4ac11e2009-08-31 10:13:04 -04001450 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001451 if (mbrState == gpt) {
1452 cout << "\a\a****************************************************************************\n"
1453 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1454 << "verification and recovery are STRONGLY recommended.\n"
1455 << "****************************************************************************\n";
1456 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001457 } else {
srs569408bb0da2010-02-19 17:19:55 -05001458 which = use_abort;
1459 } // if/else MBR says disk is GPT
1460 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001461
1462 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001463 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001464
1465 return which;
1466} // UseWhichPartitions()
1467
srs569408bb0da2010-02-19 17:19:55 -05001468// Convert MBR partition table into GPT form.
1469void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001470 int i, numToConvert;
1471 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001472
1473 // Clear out old data & prepare basics....
1474 ClearGPTData();
1475
1476 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001477 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001478 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001479 else
srs56940283dae2010-04-28 16:44:34 -04001480 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001481
1482 for (i = 0; i < numToConvert; i++) {
1483 origType = protectiveMBR.GetType(i);
1484 // don't waste CPU time trying to convert extended, hybrid protective, or
1485 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001486 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001487 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001488 partitions[i] = protectiveMBR.AsGPT(i);
1489 } // for
1490
1491 // Convert MBR into protective MBR
1492 protectiveMBR.MakeProtectiveMBR();
1493
1494 // Record that all original CRCs were OK so as not to raise flags
1495 // when doing a disk verification
1496 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001497} // GPTData::XFormPartitions()
1498
1499// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001500// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001501// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001502int GPTData::XFormDisklabel(uint32_t partNum) {
1503 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001504 int goOn = 1, numDone = 0;
1505 BSDData disklabel;
1506
srs569408bb0da2010-02-19 17:19:55 -05001507 if (GetPartRange(&low, &high) == 0) {
1508 goOn = 0;
1509 cout << "No partitions!\n";
1510 } // if
1511 if (partNum > high) {
1512 goOn = 0;
1513 cout << "Specified partition is invalid!\n";
1514 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001515
srs569408bb0da2010-02-19 17:19:55 -05001516 // If all is OK, read the disklabel and convert it.
1517 if (goOn) {
1518 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1519 partitions[partNum].GetLastLBA());
1520 if ((goOn) && (disklabel.IsDisklabel())) {
1521 numDone = XFormDisklabel(&disklabel);
1522 if (numDone == 1)
1523 cout << "Converted 1 BSD partition.\n";
1524 else
1525 cout << "Converted " << numDone << " BSD partitions.\n";
1526 } else {
1527 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1528 } // if/else
1529 } // if
1530 if (numDone > 0) { // converted partitions; delete carrier
1531 partitions[partNum].BlankPartition();
1532 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001533 return numDone;
srs569455d92612010-03-07 22:16:07 -05001534} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001535
1536// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001537int GPTData::XFormDisklabel(BSDData* disklabel) {
1538 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001539
srs569408bb0da2010-02-19 17:19:55 -05001540 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001541 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001542 partNum = FindFirstFreePart();
1543 if (partNum >= 0) {
1544 partitions[partNum] = disklabel->AsGPT(i);
1545 if (partitions[partNum].IsUsed())
1546 numDone++;
1547 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001548 } // for
srs569408bb0da2010-02-19 17:19:55 -05001549 if (partNum == -1)
1550 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001551 } // if
1552
1553 // Record that all original CRCs were OK so as not to raise flags
1554 // when doing a disk verification
1555 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1556
1557 return numDone;
1558} // GPTData::XFormDisklabel(BSDData* disklabel)
1559
srs569408bb0da2010-02-19 17:19:55 -05001560// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1561// partition has the active/bootable flag UNset and uses the GPT fdisk
1562// type code divided by 0x0100 as the MBR type code.
1563// Returns 1 if operation was 100% successful, 0 if there were ANY
1564// problems.
srs5694978041c2009-09-21 20:51:47 -04001565int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001566 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001567
srs5694978041c2009-09-21 20:51:47 -04001568 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001569 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001570 allOK = 0;
1571 } // if
srs56940283dae2010-04-28 16:44:34 -04001572 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001573 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001574 allOK = 0;
1575 } // if
1576 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001577 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001578 allOK = 0;
1579 } // if
1580 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1581 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1582 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001583 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1584 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001585 } // if
srs5694978041c2009-09-21 20:51:47 -04001586 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001587 (uint32_t) partitions[gptPart].GetLengthLBA(),
1588 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001589 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001590 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1591 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1592 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001593 allOK = 0;
1594 } // if/else
1595 return allOK;
1596} // GPTData::OnePartToMBR()
1597
srs5694e4ac11e2009-08-31 10:13:04 -04001598
1599/**********************************************************************
1600 * *
1601 * Functions that adjust GPT data structures WITHOUT user interaction *
1602 * (they may display information for the user's benefit, though) *
1603 * *
1604 **********************************************************************/
1605
1606// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001607// necessary, copies data if it already exists. If fillGPTSectors is 1
1608// (the default), rounds numEntries to fill all the sectors necessary to
1609// hold the GPT.
1610// Returns 1 if all goes well, 0 if an error is encountered.
1611int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001612 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001613 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001614 int allOK = 1;
1615
1616 // First, adjust numEntries upward, if necessary, to get a number
1617 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001618 entriesPerSector = blockSize / GPT_SIZE;
1619 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001620 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001621 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001622 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001623 } // if
1624
srs5694247657a2009-11-26 18:36:12 -05001625 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001626 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001627 // partition table, which causes problems when loading data from a RAID
1628 // array that's been expanded because this function is called when loading
1629 // data.
srs56940283dae2010-04-28 16:44:34 -04001630 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001631 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001632 if (newParts != NULL) {
1633 if (partitions != NULL) { // existing partitions; copy them over
1634 GetPartRange(&i, &high);
1635 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001636 cout << "The highest-numbered partition is " << high + 1
1637 << ", which is greater than the requested\n"
1638 << "partition table size of " << numEntries
1639 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001640 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001641 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001642 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001643 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001644 copyNum = numEntries;
1645 else
srs56940283dae2010-04-28 16:44:34 -04001646 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001647 for (i = 0; i < copyNum; i++) {
1648 newParts[i] = partitions[i];
1649 } // for
srs569401f7f082011-03-15 23:53:31 -04001650 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001651 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001652 } // if
1653 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001654 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001655 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001656 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001657 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001658 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1659 MoveSecondHeaderToEnd();
1660 if (diskSize > 0)
1661 CheckGPTSize();
1662 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001663 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001664 allOK = 0;
1665 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001666 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001667 mainHeader.numParts = numParts;
1668 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001669 return (allOK);
1670} // GPTData::SetGPTSize()
1671
1672// Blank the partition array
1673void GPTData::BlankPartitions(void) {
1674 uint32_t i;
1675
srs56940283dae2010-04-28 16:44:34 -04001676 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001677 partitions[i].BlankPartition();
1678 } // for
1679} // GPTData::BlankPartitions()
1680
srs5694ba00fed2010-01-12 18:18:36 -05001681// Delete a partition by number. Returns 1 if successful,
1682// 0 if there was a problem. Returns 1 if partition was in
1683// range, 0 if it was out of range.
1684int GPTData::DeletePartition(uint32_t partNum) {
1685 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001686 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001687
srs56940283dae2010-04-28 16:44:34 -04001688 numUsedParts = GetPartRange(&low, &high);
1689 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001690 // In case there's a protective MBR, look for & delete matching
1691 // MBR partition....
1692 startSector = partitions[partNum].GetFirstLBA();
1693 length = partitions[partNum].GetLengthLBA();
1694 protectiveMBR.DeleteByLocation(startSector, length);
1695
1696 // Now delete the GPT partition
1697 partitions[partNum].BlankPartition();
1698 } else {
srs5694fed16d02010-01-27 23:03:40 -05001699 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001700 retval = 0;
1701 } // if/else
1702 return retval;
1703} // GPTData::DeletePartition(uint32_t partNum)
1704
srs569408bb0da2010-02-19 17:19:55 -05001705// Non-interactively create a partition.
1706// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001707uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001708 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001709 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001710
1711 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001712 if (Align(&startSector)) {
1713 cout << "Information: Moved requested sector from " << origSector << " to "
1714 << startSector << " in\norder to align on " << sectorAlignment
1715 << "-sector boundaries.\n";
1716 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001717 if (IsFree(startSector) && (startSector <= endSector)) {
1718 if (FindLastInFree(startSector) >= endSector) {
1719 partitions[partNum].SetFirstLBA(startSector);
1720 partitions[partNum].SetLastLBA(endSector);
srs569400b6d7a2011-06-26 22:40:06 -04001721 partitions[partNum].SetType(DEFAULT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001722 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001723 } else retval = 0; // if free space until endSector
1724 } else retval = 0; // if startSector is free
1725 } else retval = 0; // if legal partition number
1726 return retval;
1727} // GPTData::CreatePartition(partNum, startSector, endSector)
1728
srs5694e4ac11e2009-08-31 10:13:04 -04001729// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001730// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001731void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001732 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001733 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001734} // GPTData::SortGPT()
1735
srs569408bb0da2010-02-19 17:19:55 -05001736// Swap the contents of two partitions.
1737// Returns 1 if successful, 0 if either partition is out of range
1738// (that is, not a legal number; either or both can be empty).
1739// Note that if partNum1 = partNum2 and this number is in range,
1740// it will be considered successful.
1741int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1742 GPTPart temp;
1743 int allOK = 1;
1744
srs56940283dae2010-04-28 16:44:34 -04001745 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001746 if (partNum1 != partNum2) {
1747 temp = partitions[partNum1];
1748 partitions[partNum1] = partitions[partNum2];
1749 partitions[partNum2] = temp;
1750 } // if
1751 } else allOK = 0; // partition numbers are valid
1752 return allOK;
1753} // GPTData::SwapPartitions()
1754
srs5694e4ac11e2009-08-31 10:13:04 -04001755// Set up data structures for entirely new set of partitions on the
1756// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001757// Note that this function does NOT clear the protectiveMBR data
1758// structure, since it may hold the original MBR partitions if the
1759// program was launched on an MBR disk, and those may need to be
1760// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001761int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001762 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001763
1764 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001765 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001766 partitions = NULL;
1767 SetGPTSize(NUM_GPT_ENTRIES);
1768
1769 // Now initialize a bunch of stuff that's static....
1770 mainHeader.signature = GPT_SIGNATURE;
1771 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001772 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001773 mainHeader.reserved = 0;
1774 mainHeader.currentLBA = UINT64_C(1);
1775 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1776 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1777 for (i = 0; i < GPT_RESERVED; i++) {
1778 mainHeader.reserved2[i] = '\0';
1779 } // for
srs56940873e9d2010-10-07 13:00:45 -04001780 if (blockSize > 0)
1781 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1782 else
1783 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001784
1785 // Now some semi-static items (computed based on end of disk)
1786 mainHeader.backupLBA = diskSize - UINT64_C(1);
1787 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1788
1789 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001790 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001791
1792 // Copy main header to backup header
1793 RebuildSecondHeader();
1794
1795 // Blank out the partitions array....
1796 BlankPartitions();
1797
1798 // Flag all CRCs as being OK....
1799 mainCrcOk = 1;
1800 secondCrcOk = 1;
1801 mainPartsCrcOk = 1;
1802 secondPartsCrcOk = 1;
1803
1804 return (goOn);
1805} // GPTData::ClearGPTData()
1806
srs5694247657a2009-11-26 18:36:12 -05001807// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001808// If the disk size has actually changed, this also adjusts the protective
1809// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001810// Used internally and called by the 'e' option on the recovery &
1811// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001812// to their arrays or to adjust data structures in restore operations
1813// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001814void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001815 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001816 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1817 if (protectiveMBR.GetValidity() == hybrid) {
1818 protectiveMBR.OptimizeEESize();
1819 RecomputeCHS();
1820 } // if
1821 if (protectiveMBR.GetValidity() == gpt)
1822 MakeProtectiveMBR();
1823 } // if
srs56948bb78762009-11-24 15:43:49 -05001824 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1825 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1826} // GPTData::FixSecondHeaderLocation()
1827
srs5694699941e2011-03-21 21:33:57 -04001828// Sets the partition's name to the specified UnicodeString without
1829// user interaction.
1830// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001831int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001832 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001833
srs5694699941e2011-03-21 21:33:57 -04001834 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001835 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001836 else
1837 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001838
1839 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001840} // GPTData::SetName
1841
1842// Set the disk GUID to the specified value. Note that the header CRCs must
1843// be recomputed after calling this function.
1844void GPTData::SetDiskGUID(GUIDData newGUID) {
1845 mainHeader.diskGUID = newGUID;
1846 secondHeader.diskGUID = newGUID;
1847} // SetDiskGUID()
1848
1849// Set the unique GUID of the specified partition. Returns 1 on
1850// successful completion, 0 if there were problems (invalid
1851// partition number).
1852int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1853 int retval = 0;
1854
srs56940283dae2010-04-28 16:44:34 -04001855 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001856 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001857 partitions[pn].SetUniqueGUID(theGUID);
1858 retval = 1;
1859 } // if
1860 } // if
1861 return retval;
1862} // GPTData::SetPartitionGUID()
1863
srs56949ba54212010-05-18 23:24:02 -04001864// Set new random GUIDs for the disk and all partitions. Intended to be used
1865// after disk cloning or similar operations that don't randomize the GUIDs.
1866void GPTData::RandomizeGUIDs(void) {
1867 uint32_t i;
1868
1869 mainHeader.diskGUID.Randomize();
1870 secondHeader.diskGUID = mainHeader.diskGUID;
1871 for (i = 0; i < numParts; i++)
1872 if (partitions[i].IsUsed())
1873 partitions[i].RandomizeUniqueGUID();
1874} // GPTData::RandomizeGUIDs()
1875
srs5694ba00fed2010-01-12 18:18:36 -05001876// Change partition type code non-interactively. Returns 1 if
1877// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001878int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1879 int retval = 1;
1880
1881 if (!IsFreePartNum(partNum)) {
1882 partitions[partNum].SetType(theGUID);
1883 } else retval = 0;
1884 return retval;
1885} // GPTData::ChangePartType()
1886
srs56949ba54212010-05-18 23:24:02 -04001887// Recompute the CHS values of all the MBR partitions. Used to reset
1888// CHS values that some BIOSes require, despite the fact that the
1889// resulting CHS values violate the GPT standard.
1890void GPTData::RecomputeCHS(void) {
1891 int i;
1892
1893 for (i = 0; i < 4; i++)
1894 protectiveMBR.RecomputeCHS(i);
1895} // GPTData::RecomputeCHS()
1896
srs56941d1448a2009-12-31 21:20:19 -05001897// Adjust sector number so that it falls on a sector boundary that's a
1898// multiple of sectorAlignment. This is done to improve the performance
1899// of Western Digital Advanced Format disks and disks with similar
1900// technology from other companies, which use 4096-byte sectors
1901// internally although they translate to 512-byte sectors for the
1902// benefit of the OS. If partitions aren't properly aligned on these
1903// disks, some filesystem data structures can span multiple physical
1904// sectors, degrading performance. This function should be called
1905// only on the FIRST sector of the partition, not the last!
1906// This function returns 1 if the alignment was altered, 0 if it
1907// was unchanged.
1908int GPTData::Align(uint64_t* sector) {
1909 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001910 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001911
1912 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001913 earlier = (*sector / sectorAlignment) * sectorAlignment;
1914 later = earlier + (uint64_t) sectorAlignment;
1915
1916 // Check to see that every sector between the earlier one and the
1917 // requested one is clear, and that it's not too early....
1918 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001919 sectorOK = 1;
1920 testSector = earlier;
1921 do {
1922 sectorOK = IsFree(testSector++);
1923 } while ((sectorOK == 1) && (testSector < *sector));
1924 if (sectorOK == 1) {
1925 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001926 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001927 } // if
1928 } // if firstUsableLBA check
1929
1930 // If couldn't move the sector earlier, try to move it later instead....
1931 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1932 sectorOK = 1;
1933 testSector = later;
1934 do {
1935 sectorOK = IsFree(testSector--);
1936 } while ((sectorOK == 1) && (testSector > *sector));
1937 if (sectorOK == 1) {
1938 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001939 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001940 } // if
1941 } // if
srs56941d1448a2009-12-31 21:20:19 -05001942 } // if
1943 return retval;
1944} // GPTData::Align()
1945
srs5694e4ac11e2009-08-31 10:13:04 -04001946/********************************************************
1947 * *
1948 * Functions that return data about GPT data structures *
1949 * (most of these are inline in gpt.h) *
1950 * *
1951 ********************************************************/
1952
1953// Find the low and high used partition numbers (numbered from 0).
1954// Return value is the number of partitions found. Note that the
1955// *low and *high values are both set to 0 when no partitions
1956// are found, as well as when a single partition in the first
1957// position exists. Thus, the return value is the only way to
1958// tell when no partitions exist.
1959int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1960 uint32_t i;
1961 int numFound = 0;
1962
srs56940283dae2010-04-28 16:44:34 -04001963 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001964 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001965 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05001966 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04001967 *high = i; // since we're counting up, set the high value
1968 // Set the low value only if it's not yet found...
1969 if (*low == (numParts + 1)) *low = i;
1970 numFound++;
1971 } // if
1972 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04001973
1974 // Above will leave *low pointing to its "not found" value if no partitions
1975 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001976 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001977 *low = 0;
1978 return numFound;
1979} // GPTData::GetPartRange()
1980
srs569408bb0da2010-02-19 17:19:55 -05001981// Returns the value of the first free partition, or -1 if none is
1982// unused.
1983int GPTData::FindFirstFreePart(void) {
1984 int i = 0;
1985
1986 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04001987 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05001988 i++;
srs56940283dae2010-04-28 16:44:34 -04001989 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001990 i = -1;
1991 } else i = -1;
1992 return i;
1993} // GPTData::FindFirstFreePart()
1994
srs5694978041c2009-09-21 20:51:47 -04001995// Returns the number of defined partitions.
1996uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001997 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001998
srs56940283dae2010-04-28 16:44:34 -04001999 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002000 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002001 counted++;
2002 } // for
2003 return counted;
2004} // GPTData::CountParts()
2005
srs5694e4ac11e2009-08-31 10:13:04 -04002006/****************************************************
2007 * *
2008 * Functions that return data about disk free space *
2009 * *
2010 ****************************************************/
2011
2012// Find the first available block after the starting point; returns 0 if
2013// there are no available blocks left
2014uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2015 uint64_t first;
2016 uint32_t i;
2017 int firstMoved = 0;
2018
2019 // Begin from the specified starting point or from the first usable
2020 // LBA, whichever is greater...
2021 if (start < mainHeader.firstUsableLBA)
2022 first = mainHeader.firstUsableLBA;
2023 else
2024 first = start;
2025
2026 // ...now search through all partitions; if first is within an
2027 // existing partition, move it to the next sector after that
2028 // partition and repeat. If first was moved, set firstMoved
2029 // flag; repeat until firstMoved is not set, so as to catch
2030 // cases where partitions are out of sequential order....
2031 do {
2032 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002033 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002034 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002035 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002036 first = partitions[i].GetLastLBA() + 1;
2037 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002038 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002039 } // for
2040 } while (firstMoved == 1);
2041 if (first > mainHeader.lastUsableLBA)
2042 first = 0;
2043 return (first);
2044} // GPTData::FindFirstAvailable()
2045
2046// Finds the first available sector in the largest block of unallocated
2047// space on the disk. Returns 0 if there are no available blocks left
2048uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002049 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002050
2051 start = 0;
2052 do {
2053 firstBlock = FindFirstAvailable(start);
2054 if (firstBlock != UINT32_C(0)) { // something's free...
2055 lastBlock = FindLastInFree(firstBlock);
2056 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2057 if (segmentSize > selectedSize) {
2058 selectedSize = segmentSize;
2059 selectedSegment = firstBlock;
2060 } // if
2061 start = lastBlock + 1;
2062 } // if
2063 } while (firstBlock != 0);
2064 return selectedSegment;
2065} // GPTData::FindFirstInLargest()
2066
srs5694cb76c672010-02-11 22:22:22 -05002067// Find the last available block on the disk.
2068// Returns 0 if there are no available partitions
2069uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002070 uint64_t last;
2071 uint32_t i;
2072 int lastMoved = 0;
2073
2074 // Start by assuming the last usable LBA is available....
2075 last = mainHeader.lastUsableLBA;
2076
2077 // ...now, similar to algorithm in FindFirstAvailable(), search
2078 // through all partitions, moving last when it's in an existing
2079 // partition. Set the lastMoved flag so we repeat to catch cases
2080 // where partitions are out of logical order.
2081 do {
2082 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002083 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002084 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002085 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002086 last = partitions[i].GetFirstLBA() - 1;
2087 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002088 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002089 } // for
2090 } while (lastMoved == 1);
2091 if (last < mainHeader.firstUsableLBA)
2092 last = 0;
2093 return (last);
2094} // GPTData::FindLastAvailable()
2095
2096// Find the last available block in the free space pointed to by start.
2097uint64_t GPTData::FindLastInFree(uint64_t start) {
2098 uint64_t nearestStart;
2099 uint32_t i;
2100
2101 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002102 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002103 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002104 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002105 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002106 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002107 } // for
2108 return (nearestStart);
2109} // GPTData::FindLastInFree()
2110
2111// Finds the total number of free blocks, the number of segments in which
2112// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002113uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002114 uint64_t start = UINT64_C(0); // starting point for each search
2115 uint64_t totalFound = UINT64_C(0); // running total
2116 uint64_t firstBlock; // first block in a segment
2117 uint64_t lastBlock; // last block in a segment
2118 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002119 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002120
2121 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002122 if (diskSize > 0) {
2123 do {
2124 firstBlock = FindFirstAvailable(start);
2125 if (firstBlock != UINT64_C(0)) { // something's free...
2126 lastBlock = FindLastInFree(firstBlock);
2127 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2128 if (segmentSize > *largestSegment) {
2129 *largestSegment = segmentSize;
2130 } // if
2131 totalFound += segmentSize;
2132 num++;
2133 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002134 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002135 } while (firstBlock != 0);
2136 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002137 *numSegments = num;
2138 return totalFound;
2139} // GPTData::FindFreeBlocks()
2140
srs569455d92612010-03-07 22:16:07 -05002141// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2142// If it's allocated, return the partition number to which it's allocated
2143// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2144// returned in partNum if the sector is in use by basic GPT data structures.)
2145int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002146 int isFree = 1;
2147 uint32_t i;
2148
srs56940283dae2010-04-28 16:44:34 -04002149 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002150 if ((sector >= partitions[i].GetFirstLBA()) &&
2151 (sector <= partitions[i].GetLastLBA())) {
2152 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002153 if (partNum != NULL)
2154 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002155 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002156 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002157 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002158 (sector > mainHeader.lastUsableLBA)) {
2159 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002160 if (partNum != NULL)
2161 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002162 } // if
2163 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002164} // GPTData::IsFree()
2165
srs5694815fb652011-03-18 12:35:56 -04002166// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002167int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002168 return ((partNum < numParts) && (partitions != NULL) &&
2169 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002170} // GPTData::IsFreePartNum()
2171
srs5694815fb652011-03-18 12:35:56 -04002172// Returns 1 if partNum is in use.
2173int GPTData::IsUsedPartNum(uint32_t partNum) {
2174 return ((partNum < numParts) && (partitions != NULL) &&
2175 (partitions[partNum].IsUsed()));
2176} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002177
2178/***********************************************************
2179 * *
2180 * Change how functions work or return information on them *
2181 * *
2182 ***********************************************************/
2183
2184// Set partition alignment value; partitions will begin on multiples of
2185// the specified value
2186void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002187 if (n > 0)
2188 sectorAlignment = n;
2189 else
2190 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002191} // GPTData::SetAlignment()
2192
2193// Compute sector alignment based on the current partitions (if any). Each
2194// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002195// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2196// sector size), but not by the previously-located alignment value, then the
2197// alignment value is adjusted down. If the computed alignment is less than 8
2198// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2199// is a safety measure for WD Advanced Format and similar drives. If no partitions
2200// are defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2201// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002202// drives are aligned to 2048-sector multiples but the program won't complain
2203// about other alignments on existing disks unless a smaller-than-8 alignment
srs56940873e9d2010-10-07 13:00:45 -04002204// is used on big disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002205// Returns the computed alignment value.
2206uint32_t GPTData::ComputeAlignment(void) {
2207 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002208 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002209
srs56940873e9d2010-10-07 13:00:45 -04002210 if (blockSize > 0)
2211 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2212 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002213 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002214 if (partitions[i].IsUsed()) {
2215 found = 0;
2216 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002217 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002218 if ((partitions[i].GetFirstLBA() % align) == 0) {
2219 found = 1;
2220 } else {
2221 exponent--;
2222 } // if/else
2223 } // while
2224 } // if
2225 } // for
srs56940873e9d2010-10-07 13:00:45 -04002226 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2227 align = MIN_AF_ALIGNMENT;
2228 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002229 return align;
2230} // GPTData::ComputeAlignment()
2231
srs5694e4ac11e2009-08-31 10:13:04 -04002232/********************************
2233 * *
2234 * Endianness support functions *
2235 * *
2236 ********************************/
2237
srs56942a9f5da2009-08-26 00:48:01 -04002238void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002239 ReverseBytes(&header->signature, 8);
2240 ReverseBytes(&header->revision, 4);
2241 ReverseBytes(&header->headerSize, 4);
2242 ReverseBytes(&header->headerCRC, 4);
2243 ReverseBytes(&header->reserved, 4);
2244 ReverseBytes(&header->currentLBA, 8);
2245 ReverseBytes(&header->backupLBA, 8);
2246 ReverseBytes(&header->firstUsableLBA, 8);
2247 ReverseBytes(&header->lastUsableLBA, 8);
2248 ReverseBytes(&header->partitionEntriesLBA, 8);
2249 ReverseBytes(&header->numParts, 4);
2250 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2251 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002252 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002253} // GPTData::ReverseHeaderBytes()
2254
srs56940283dae2010-04-28 16:44:34 -04002255// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002256void GPTData::ReversePartitionBytes() {
2257 uint32_t i;
2258
srs56940283dae2010-04-28 16:44:34 -04002259 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002260 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002261 } // for
2262} // GPTData::ReversePartitionBytes()
2263
srs56949ddc14b2010-08-22 22:44:42 -04002264// Validate partition number
2265bool GPTData::ValidPartNum (const uint32_t partNum) {
2266 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002267 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002268 return false;
2269 } // if
2270 return true;
2271} // GPTData::ValidPartNum
2272
srs56945a081752010-09-24 20:39:41 -04002273// Return a single partition for inspection (not modification!) by other
2274// functions.
2275const GPTPart & GPTData::operator[](uint32_t partNum) const {
2276 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002277 cerr << "Partition number out of range (" << partNum << " requested, but only "
2278 << numParts << " available)\n";
2279 exit(1);
2280 } // if
2281 if (partitions == NULL) {
2282 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2283 exit(1);
srs56945a081752010-09-24 20:39:41 -04002284 } // if
2285 return partitions[partNum];
2286} // operator[]
2287
2288// Return (not for modification!) the disk's GUID value
2289const GUIDData & GPTData::GetDiskGUID(void) const {
2290 return mainHeader.diskGUID;
2291} // GPTData::GetDiskGUID()
2292
srs56949ddc14b2010-08-22 22:44:42 -04002293// Manage attributes for a partition, based on commands passed to this function.
2294// (Function is non-interactive.)
2295// Returns 1 if a modification command succeeded, 0 if the command should not have
2296// modified data, and -1 if a modification command failed.
2297int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2298 int retval = 0;
2299 Attributes theAttr;
2300
2301 if (command == "show") {
2302 ShowAttributes(partNum);
2303 } else if (command == "get") {
2304 GetAttribute(partNum, bits);
2305 } else {
2306 theAttr = partitions[partNum].GetAttributes();
2307 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2308 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2309 retval = 1;
2310 } else {
2311 retval = -1;
2312 } // if/else
2313 } // if/elseif/else
2314
2315 return retval;
2316} // GPTData::ManageAttributes()
2317
2318// Show all attributes for a specified partition....
2319void GPTData::ShowAttributes(const uint32_t partNum) {
srs5694e69e6802012-01-20 22:37:12 -05002320 if (partitions[partNum].IsUsed())
2321 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002322} // GPTData::ShowAttributes
2323
2324// Show whether a single attribute bit is set (terse output)...
2325void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002326 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002327} // GPTData::GetAttribute
2328
2329
srs56942a9f5da2009-08-26 00:48:01 -04002330/******************************************
2331 * *
2332 * Additional non-class support functions *
2333 * *
2334 ******************************************/
2335
srs5694e7b4ff92009-08-18 13:16:10 -04002336// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2337// never fail these tests, but the struct types may fail depending on compile options.
2338// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2339// sizes.
2340int SizesOK(void) {
2341 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002342
2343 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002344 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002345 allOK = 0;
2346 } // if
2347 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002348 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002349 allOK = 0;
2350 } // if
2351 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002352 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002353 allOK = 0;
2354 } // if
2355 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002356 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002357 allOK = 0;
2358 } // if
2359 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002360 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002361 allOK = 0;
2362 } // if
srs5694978041c2009-09-21 20:51:47 -04002363 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002364 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002365 allOK = 0;
2366 } // if
2367 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002368 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002369 allOK = 0;
2370 } // if
srs5694221e0872009-08-29 15:00:31 -04002371 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002372 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002373 allOK = 0;
2374 } // if
srs56946699b012010-02-04 00:55:30 -05002375 if (sizeof(GUIDData) != 16) {
2376 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2377 allOK = 0;
2378 } // if
2379 if (sizeof(PartType) != 16) {
2380 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2381 allOK = 0;
2382 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002383 return (allOK);
2384} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002385