blob: 269e09b0ba03aad3cd37a6f6f2d409d05bd8b0cb [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++) {
srs56941d1448a2009-12-31 21:20:19 -0500280 if ((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++) {
srs5694221e0872009-08-29 15:00:31 -0400319 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400320 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400321 firstUsedBlock = partitions[i].GetFirstLBA();
322 if (partitions[i].GetLastLBA() > lastUsedBlock)
323 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400324 } // for
325
326 // If the disk size is 0 (the default), then it means that various
327 // variables aren't yet set, so the below tests will be useless;
328 // therefore we should skip everything
329 if (diskSize != 0) {
330 if (mainHeader.firstUsableLBA > firstUsedBlock) {
331 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500332 cout << "Warning! Main partition table overlaps the first partition by "
333 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400334 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500335 cout << "Try reducing the partition table size by " << overlap * 4
336 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400337 } else {
srs5694fed16d02010-01-27 23:03:40 -0500338 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400339 } // if/else
340 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400341 } // Problem at start of disk
342 if (mainHeader.lastUsableLBA < lastUsedBlock) {
343 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500344 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500345 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400346 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500347 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400348 } else {
srs5694fed16d02010-01-27 23:03:40 -0500349 cout << "Try reducing the partition table size by " << overlap * 4
350 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400351 } // if/else
352 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400353 } // Problem at end of disk
354 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400355 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400356} // GPTData::CheckGPTSize()
357
srs5694e7b4ff92009-08-18 13:16:10 -0400358// Check the validity of the GPT header. Returns 1 if the main header
359// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400360// 0 if neither is valid. Note that this function checks the GPT signature,
361// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400362int GPTData::CheckHeaderValidity(void) {
363 int valid = 3;
364
srs5694fed16d02010-01-27 23:03:40 -0500365 cout.setf(ios::uppercase);
366 cout.fill('0');
367
368 // Note: failed GPT signature checks produce no error message because
369 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400370 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400371 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400372 } else if ((mainHeader.revision != 0x00010000) && valid) {
373 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500374 cout << "Unsupported GPT version in main header; read 0x";
375 cout.width(8);
376 cout << hex << mainHeader.revision << ", should be\n0x";
377 cout.width(8);
378 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400379 } // if/else/if
380
srs5694d1b11e82011-09-18 21:12:28 -0400381 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400382 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400383 } else if ((secondHeader.revision != 0x00010000) && valid) {
384 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500385 cout << "Unsupported GPT version in backup header; read 0x";
386 cout.width(8);
387 cout << hex << secondHeader.revision << ", should be\n0x";
388 cout.width(8);
389 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400390 } // if/else/if
391
srs5694df9d3632011-01-08 18:33:24 -0500392 // Check for an Apple disk signature
393 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
394 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400395 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500396 } // if
srs5694fed16d02010-01-27 23:03:40 -0500397 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400398
srs5694fed16d02010-01-27 23:03:40 -0500399 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400400} // GPTData::CheckHeaderValidity()
401
402// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400403// Note: Must be called with header in platform-ordered byte order.
404// Returns 1 if header's computed CRC matches the stored value, 0 if the
405// computed and stored values don't match
406int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400407 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400408 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400409
srs56942a9f5da2009-08-26 00:48:01 -0400410 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400411 // computation to be valid
412 oldCRC = header->headerCRC;
413 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400414
srs5694978041c2009-09-21 20:51:47 -0400415 hSize = header->headerSize;
416
srs5694d1b11e82011-09-18 21:12:28 -0400417 if (IsLittleEndian() == 0)
418 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400419
srs5694d1b11e82011-09-18 21:12:28 -0400420 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
421 if (warn) {
422 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
423 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
424 } // if
425 hSize = HEADER_SIZE;
426 } else if ((hSize > sizeof(GPTHeader)) && warn) {
427 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
428 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
429 << "which may result in a CRC false alarm.\n";
430 } // if/elseif
431 temp = new uint8_t[hSize];
432 if (temp != NULL) {
433 memset(temp, 0, hSize);
434 if (hSize < sizeof(GPTHeader))
435 memcpy(temp, header, hSize);
436 else
437 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400438
srs5694d1b11e82011-09-18 21:12:28 -0400439 newCRC = chksum_crc32((unsigned char*) temp, hSize);
440 delete[] temp;
441 } else {
442 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
443 exit(1);
444 }
445 if (IsLittleEndian() == 0)
446 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400447 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400448 return (oldCRC == newCRC);
449} // GPTData::CheckHeaderCRC()
450
srs56946699b012010-02-04 00:55:30 -0500451// Recompute all the CRCs. Must be called before saving if any changes have
452// been made. Must be called on platform-ordered data (this function reverses
453// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400454void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400455 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400456 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400457
srs5694d1b11e82011-09-18 21:12:28 -0400458 // If the header size is bigger than the GPT header data structure, reset it;
459 // otherwise, set both header sizes to whatever the main one is....
460 if (mainHeader.headerSize > sizeof(GPTHeader))
461 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
462 else
463 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500464
465 if ((littleEndian = IsLittleEndian()) == 0) {
466 ReversePartitionBytes();
467 ReverseHeaderBytes(&mainHeader);
468 ReverseHeaderBytes(&secondHeader);
469 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400470
srs5694e7b4ff92009-08-18 13:16:10 -0400471 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400472 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400473 mainHeader.partitionEntriesCRC = crc;
474 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400475 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400476 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
477 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400478 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400479
srs5694d1b11e82011-09-18 21:12:28 -0400480 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400481 mainHeader.headerCRC = 0;
482 secondHeader.headerCRC = 0;
483
srs5694978041c2009-09-21 20:51:47 -0400484 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400485 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400486 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400487 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400488 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400489 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400490 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400491 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500492
srs5694d1b11e82011-09-18 21:12:28 -0400493 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500494 ReverseHeaderBytes(&mainHeader);
495 ReverseHeaderBytes(&secondHeader);
496 ReversePartitionBytes();
497 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400498} // GPTData::RecomputeCRCs()
499
srs5694e7b4ff92009-08-18 13:16:10 -0400500// Rebuild the main GPT header, using the secondary header as a model.
501// Typically called when the main header has been found to be corrupt.
502void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400503 mainHeader.signature = GPT_SIGNATURE;
504 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400505 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400506 mainHeader.headerCRC = UINT32_C(0);
507 mainHeader.reserved = secondHeader.reserved;
508 mainHeader.currentLBA = secondHeader.backupLBA;
509 mainHeader.backupLBA = secondHeader.currentLBA;
510 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
511 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500512 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400513 mainHeader.partitionEntriesLBA = UINT64_C(2);
514 mainHeader.numParts = secondHeader.numParts;
515 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
516 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400517 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500518 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400519 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400520} // GPTData::RebuildMainHeader()
521
522// Rebuild the secondary GPT header, using the main header as a model.
523void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400524 secondHeader.signature = GPT_SIGNATURE;
525 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400526 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400527 secondHeader.headerCRC = UINT32_C(0);
528 secondHeader.reserved = mainHeader.reserved;
529 secondHeader.currentLBA = mainHeader.backupLBA;
530 secondHeader.backupLBA = mainHeader.currentLBA;
531 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
532 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500533 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400534 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
535 secondHeader.numParts = mainHeader.numParts;
536 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
537 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400538 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500539 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400540 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400541} // GPTData::RebuildSecondHeader()
542
543// Search for hybrid MBR entries that have no corresponding GPT partition.
544// Returns number of such mismatches found
545int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500546 int i, found, numFound = 0;
547 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400548 uint64_t mbrFirst, mbrLast;
549
550 for (i = 0; i < 4; i++) {
551 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
552 j = 0;
553 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400554 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
555 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400556 do {
srs5694e4ac11e2009-08-31 10:13:04 -0400557 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
558 (partitions[j].GetLastLBA() == mbrLast))
559 found = 1;
560 j++;
srs56940283dae2010-04-28 16:44:34 -0400561 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400562 if (!found) {
563 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500564 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
565 << i + 1 << ", of type 0x";
566 cout.fill('0');
567 cout.setf(ios::uppercase);
568 cout.width(2);
569 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
570 << "has no corresponding GPT partition! You may continue, but this condition\n"
571 << "might cause data loss in the future!\a\n" << dec;
572 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400573 } // if
574 } // if
575 } // for
576 return numFound;
577} // GPTData::FindHybridMismatches
578
579// Find overlapping partitions and warn user about them. Returns number of
580// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400581// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400582int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500583 int problems = 0;
584 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400585
srs56940283dae2010-04-28 16:44:34 -0400586 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400587 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500588 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400589 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500590 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
591 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
592 << " to " << partitions[i].GetLastLBA() << "\n";
593 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
594 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400595 } // if
596 } // for j...
597 } // for i...
598 return problems;
599} // GPTData::FindOverlaps()
600
srs569455d92612010-03-07 22:16:07 -0500601// Find partitions that are insane -- they start after they end or are too
602// big for the disk. (The latter should duplicate detection of overlaps
603// with GPT backup data structures, but better to err on the side of
604// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400605// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500606int GPTData::FindInsanePartitions(void) {
607 uint32_t i;
608 int problems = 0;
609
srs56940283dae2010-04-28 16:44:34 -0400610 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500611 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
612 problems++;
srs56940283dae2010-04-28 16:44:34 -0400613 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500614 } // if
615 if (partitions[i].GetLastLBA() >= diskSize) {
616 problems++;
srs56940873e9d2010-10-07 13:00:45 -0400617 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500618 } // if
619 } // for
620 return problems;
621} // GPTData::FindInsanePartitions(void)
622
623
srs5694e4ac11e2009-08-31 10:13:04 -0400624/******************************************************************
625 * *
626 * Begin functions that load data from disk or save data to disk. *
627 * *
628 ******************************************************************/
629
srs569464cbd172011-03-01 22:03:54 -0500630// Change the filename associated with the GPT. Used for duplicating
631// the partition table to a new disk and saving backups.
632// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500633int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500634 int err, allOK = 1;
635
636 device = deviceFilename;
637 if (allOK && myDisk.OpenForRead(deviceFilename)) {
638 // store disk information....
639 diskSize = myDisk.DiskSize(&err);
640 blockSize = (uint32_t) myDisk.GetBlockSize();
641 } // if
642 protectiveMBR.SetDisk(&myDisk);
643 protectiveMBR.SetDiskSize(diskSize);
644 protectiveMBR.SetBlockSize(blockSize);
645 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500646} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500647
srs5694e4ac11e2009-08-31 10:13:04 -0400648// Scan for partition data. This function loads the MBR data (regular MBR or
649// protective MBR) and loads BSD disklabel data (which is probably invalid).
650// It also looks for APM data, forces a load of GPT data, and summarizes
651// the results.
srs5694546a9c72010-01-26 16:00:26 -0500652void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400653 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400654
655 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500656 protectiveMBR.ReadMBRData(&myDisk);
657 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400658
659 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500660 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500661
662 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500663 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500664 protectiveMBR.ShowState();
665 bsdDisklabel.ShowState();
666 ShowAPMState(); // Show whether there's an Apple Partition Map present
667 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500668 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500669 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400670
671 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500672 cout << "\n*******************************************************************\n"
673 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500674 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500675 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500676 } // if
srs5694fed16d02010-01-27 23:03:40 -0500677 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400678 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400679} // GPTData::PartitionScan()
680
681// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500682int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500683 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500684 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500685 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400686
srs5694546a9c72010-01-26 16:00:26 -0500687 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500688 err = myDisk.OpenForWrite(deviceFilename);
689 if ((err == 0) && (!justLooking)) {
690 cout << "\aNOTE: Write test failed with error number " << errno
691 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
692#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
693 cout << "You may be able to enable writes by exiting this program, typing\n"
694 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
695 << "program.\n";
696#endif
697 cout << "\n";
698 } // if
699 myDisk.Close(); // Close and re-open read-only in case of bugs
700 } else allOK = 0; // if
701
702 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400703 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500704 diskSize = myDisk.DiskSize(&err);
705 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500706 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500707 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400708
srs5694ba00fed2010-01-12 18:18:36 -0500709 whichWasUsed = UseWhichPartitions();
710 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400711 case use_mbr:
712 XFormPartitions();
713 break;
714 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500715 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400716// bsdDisklabel.DisplayBSDData();
717 ClearGPTData();
718 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500719 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400720 break;
721 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500722 mbrState = protectiveMBR.GetValidity();
723 if ((mbrState == invalid) || (mbrState == mbr))
724 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400725 break;
726 case use_new:
727 ClearGPTData();
728 protectiveMBR.MakeProtectiveMBR();
729 break;
srs56943c0af382010-01-15 19:19:18 -0500730 case use_abort:
731 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400732 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500733 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400734 } // switch
735
srs569455d92612010-03-07 22:16:07 -0500736 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500737 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500738 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400739 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400740 } else {
741 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400742 } // if/else
743 return (allOK);
744} // GPTData::LoadPartitions()
745
746// Loads the GPT, as much as possible. Returns 1 if this seems to have
747// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500748int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500749 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400750
srs5694cb76c672010-02-11 22:22:22 -0500751 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400752
srs5694cb76c672010-02-11 22:22:22 -0500753 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
754 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
755 } else {
srs569408bb0da2010-02-19 17:19:55 -0500756 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
757 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500758 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
759 << "secondary header from the last sector of the disk! You should use 'v' to\n"
760 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
761 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500762 } // if/else
763 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400764 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400765
766 // Return valid headers code: 0 = both headers bad; 1 = main header
767 // good, backup bad; 2 = backup header good, main header bad;
768 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400769 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400770 validHeaders = CheckHeaderValidity();
771
772 // Read partitions (from primary array)
773 if (validHeaders > 0) { // if at least one header is OK....
774 // GPT appears to be valid....
775 state = gpt_valid;
776
777 // We're calling the GPT valid, but there's a possibility that one
778 // of the two headers is corrupt. If so, use the one that seems to
779 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500780 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500781 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
782 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400783 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500784 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400785 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500786 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500787 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
788 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500789 RebuildMainHeader();
790 state = gpt_corrupt;
791 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400792 } // if/else/if
793
srs5694546a9c72010-01-26 16:00:26 -0500794 // Figure out which partition table to load....
795 // Load the main partition table, since either its header's CRC is OK or the
796 // backup header's CRC is not OK....
797 if (mainCrcOk || !secondCrcOk) {
798 if (LoadMainTable() == 0)
799 allOK = 0;
800 } else { // bad main header CRC and backup header CRC is OK
801 state = gpt_corrupt;
802 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500803 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500804 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500805 } else { // backup table bad, bad main header CRC, but try main table in desperation....
806 if (LoadMainTable() == 0) {
807 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500808 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500809 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500810 } // if
811 } // if/else (LoadSecondTableAsMain())
812 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400813
srs5694cb76c672010-02-11 22:22:22 -0500814 if (loadedTable == 1)
815 secondPartsCrcOk = CheckTable(&secondHeader);
816 else if (loadedTable == 2)
817 mainPartsCrcOk = CheckTable(&mainHeader);
818 else
819 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400820
srs5694546a9c72010-01-26 16:00:26 -0500821 // Problem with main partition table; if backup is OK, use it instead....
822 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
823 state = gpt_corrupt;
824 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500825 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500826 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
827 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500828 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500829
srs5694e4ac11e2009-08-31 10:13:04 -0400830 // Check for valid CRCs and warn if there are problems
831 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
832 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500833 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400834 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500835 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400836 } else {
837 state = gpt_invalid;
838 } // if/else
839 return allOK;
840} // GPTData::ForceLoadGPTData()
841
srs5694247657a2009-11-26 18:36:12 -0500842// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400843// main GPT header in memory MUST be valid for this call to do anything
844// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500845// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400846int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500847 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400848} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400849
850// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500851// table. Used in repair functions, and when starting up if the main
852// partition table is damaged.
853// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
854int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500855 return LoadPartitionTable(secondHeader, myDisk);
856} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400857
srs5694cb76c672010-02-11 22:22:22 -0500858// Load a single GPT header (main or backup) from the specified disk device and
859// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
860// value appropriately.
861// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
862// failure.
863int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
864 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500865 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500866
867 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500868 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500869 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
870 allOK = 0;
871 } // if
srs5694cb76c672010-02-11 22:22:22 -0500872
srs56941c6f8b02010-02-21 11:09:20 -0500873 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500874 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500875 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500876 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400877 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500878
srs56940283dae2010-04-28 16:44:34 -0400879 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500880 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500881 }
srs56941c6f8b02010-02-21 11:09:20 -0500882
883 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500884 return allOK;
885} // GPTData::LoadHeader
886
887// Load a partition table (either main or secondary) from the specified disk,
888// using header as a reference for what to load. If sector != 0 (the default
889// is 0), loads from the specified sector; otherwise loads from the sector
890// indicated in header.
891// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
892int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
893 uint32_t sizeOfParts, newCRC;
894 int retval;
895
896 if (disk.OpenForRead()) {
897 if (sector == 0) {
898 retval = disk.Seek(header.partitionEntriesLBA);
899 } else {
900 retval = disk.Seek(sector);
901 } // if/else
srs569455d92612010-03-07 22:16:07 -0500902 if (retval == 1)
903 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500904 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500905 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
906 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500907 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500908 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500909 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400910 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500911 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400912 if (IsLittleEndian() == 0)
913 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500914 if (!mainPartsCrcOk) {
915 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400916 } // if
917 } else {
srs5694cb76c672010-02-11 22:22:22 -0500918 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400919 } // if/else
920 } else {
srs5694fed16d02010-01-27 23:03:40 -0500921 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500922 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500923 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400924 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500925 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500926} // GPTData::LoadPartitionsTable()
927
928// Check the partition table pointed to by header, but don't keep it
929// around.
srs5694a17fe692011-09-10 20:30:20 -0400930// Returns 1 if the CRC is OK & this table matches the one already in memory,
931// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500932int GPTData::CheckTable(struct GPTHeader *header) {
933 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400934 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400935 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400936 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500937
srs56940283dae2010-04-28 16:44:34 -0400938 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500939 // its CRC and store the results, then discard this temporary
940 // storage, since we don't use it in any but recovery operations
941 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400942 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400943 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -0400944 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -0400945 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
946 exit(1);
947 } // if
srs5694a17fe692011-09-10 20:30:20 -0400948 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400949 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500950 } else {
srs5694d1b11e82011-09-18 21:12:28 -0400951 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -0400952 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -0400953 if (header == &mainHeader)
954 otherHeader = &secondHeader;
955 else
956 otherHeader = &mainHeader;
957 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -0400958 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
959 << "on the recovery & transformation menu to examine the two tables.\n\n";
960 allOK = 0;
961 } // if
srs5694cb76c672010-02-11 22:22:22 -0500962 } // if/else
srs5694a17fe692011-09-10 20:30:20 -0400963 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -0500964 } // if
srs5694a17fe692011-09-10 20:30:20 -0400965 return allOK;
srs5694cb76c672010-02-11 22:22:22 -0500966} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400967
srs569464cbd172011-03-01 22:03:54 -0500968// Writes GPT (and protective MBR) to disk. If quiet==1,
srs5694a17fe692011-09-10 20:30:20 -0400969// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500970int GPTData::SaveGPTData(int quiet) {
srs56940541b562011-12-18 16:35:25 -0500971 int allOK = 1;
srs5694e321d442010-01-29 17:44:04 -0500972 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400973
srs5694e7b4ff92009-08-18 13:16:10 -0400974 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500975
976 // This test should only fail on read-only disks....
977 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500978 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500979 allOK = 0;
980 } // if
981
srs569464cbd172011-03-01 22:03:54 -0500982 // Check that disk is really big enough to handle the second header...
983 if (mainHeader.backupLBA >= diskSize) {
984 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
985 << "header, but other problems may occur!\n";
986 MoveSecondHeaderToEnd();
987 } // if
988
srs5694e7b4ff92009-08-18 13:16:10 -0400989 // Is there enough space to hold the GPT headers and partition tables,
990 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400991 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400992 allOK = 0;
993 } // if
994
srs5694247657a2009-11-26 18:36:12 -0500995 // Check that second header is properly placed. Warn and ask if this should
996 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -0500997 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
998 if (quiet == 0) {
999 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1000 << "correct this problem? ";
1001 if (GetYN() == 'Y') {
1002 MoveSecondHeaderToEnd();
1003 cout << "Have moved second header and partition table to correct location.\n";
1004 } else {
1005 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1006 } // if correction requested
1007 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001008 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001009 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001010 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001011
srs569455d92612010-03-07 22:16:07 -05001012 // Check for overlapping or insane partitions....
1013 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001014 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001015 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001016 } // if
1017
1018 // Check for mismatched MBR and GPT data, but let it pass if found
1019 // (function displays warning message)
1020 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001021
1022 RecomputeCRCs();
1023
srs5694ba00fed2010-01-12 18:18:36 -05001024 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001025 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001026 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001027 answer = GetYN();
1028 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -05001029 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001030 } else {
1031 allOK = 0;
1032 } // if/else
1033 } // if
1034
1035 // Do it!
1036 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001037 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001038 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001039 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1040 if (!allOK)
1041 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1042 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001043
1044 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001045 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1046
1047 // Now write the main partition tables...
1048 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1049
1050 // Now write the main GPT header...
1051 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1052
1053 // To top it off, write the protective MBR...
1054 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001055
1056 // re-read the partition table
1057 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001058 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001059 } // if
1060
1061 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001062 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001063 } else {
srs5694fed16d02010-01-27 23:03:40 -05001064 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001065 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001066 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001067
srs5694546a9c72010-01-26 16:00:26 -05001068 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001069 } else {
srs56945a608532011-03-17 13:53:01 -04001070 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001071 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001072 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001073 } // if/else
1074 } else {
srs5694fed16d02010-01-27 23:03:40 -05001075 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001076 } // if
1077
1078 return (allOK);
1079} // GPTData::SaveGPTData()
1080
1081// Save GPT data to a backup file. This function does much less error
1082// checking than SaveGPTData(). It can therefore preserve many types of
1083// corruption for later analysis; however, it preserves only the MBR,
1084// the main GPT header, the backup GPT header, and the main partition
1085// table; it discards the backup partition table, since it should be
1086// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001087int GPTData::SaveGPTBackup(const string & filename) {
1088 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001089 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001090
srs5694546a9c72010-01-26 16:00:26 -05001091 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001092 // Recomputing the CRCs is likely to alter them, which could be bad
1093 // if the intent is to save a potentially bad GPT for later analysis;
1094 // but if we don't do this, we get bogus errors when we load the
1095 // backup. I'm favoring misses over false alarms....
1096 RecomputeCRCs();
1097
srs5694546a9c72010-01-26 16:00:26 -05001098 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001099 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001100
srs5694cb76c672010-02-11 22:22:22 -05001101 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001102 // MBR write closed disk, so re-open and seek to end....
1103 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001104 allOK = SaveHeader(&mainHeader, backupFile, 1);
1105 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001106
srs5694e7b4ff92009-08-18 13:16:10 -04001107 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001108 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001109
srs5694cb76c672010-02-11 22:22:22 -05001110 if (allOK)
1111 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001112
1113 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001114 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001115 } else {
srs5694fed16d02010-01-27 23:03:40 -05001116 cerr << "Warning! An error was reported when writing the backup file.\n"
1117 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001118 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001119 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001120 } else {
srs56945a608532011-03-17 13:53:01 -04001121 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001122 allOK = 0;
1123 } // if/else
1124 return allOK;
1125} // GPTData::SaveGPTBackup()
1126
srs5694cb76c672010-02-11 22:22:22 -05001127// Write a GPT header (main or backup) to the specified sector. Used by both
1128// the SaveGPTData() and SaveGPTBackup() functions.
1129// Should be passed an architecture-appropriate header (DO NOT call
1130// ReverseHeaderBytes() on the header before calling this function)
1131// Returns 1 on success, 0 on failure
1132int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1133 int littleEndian, allOK = 1;
1134
1135 littleEndian = IsLittleEndian();
1136 if (!littleEndian)
1137 ReverseHeaderBytes(header);
1138 if (disk.Seek(sector)) {
1139 if (disk.Write(header, 512) == -1)
1140 allOK = 0;
1141 } else allOK = 0; // if (disk.Seek()...)
1142 if (!littleEndian)
1143 ReverseHeaderBytes(header);
1144 return allOK;
1145} // GPTData::SaveHeader()
1146
1147// Save the partitions to the specified sector. Used by both the SaveGPTData()
1148// and SaveGPTBackup() functions.
1149// Should be passed an architecture-appropriate header (DO NOT call
1150// ReverseHeaderBytes() on the header before calling this function)
1151// Returns 1 on success, 0 on failure
1152int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1153 int littleEndian, allOK = 1;
1154
1155 littleEndian = IsLittleEndian();
1156 if (disk.Seek(sector)) {
1157 if (!littleEndian)
1158 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001159 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001160 allOK = 0;
1161 if (!littleEndian)
1162 ReversePartitionBytes();
1163 } else allOK = 0; // if (myDisk.Seek()...)
1164 return allOK;
1165} // GPTData::SavePartitionTable()
1166
srs5694e7b4ff92009-08-18 13:16:10 -04001167// Load GPT data from a backup file created by SaveGPTBackup(). This function
1168// does minimal error checking. It returns 1 if it completed successfully,
1169// 0 if there was a problem. In the latter case, it creates a new empty
1170// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001171int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001172 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001173 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001174 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001175
srs5694546a9c72010-01-26 16:00:26 -05001176 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001177 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001178 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001179 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001180
srs5694cb76c672010-02-11 22:22:22 -05001181 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001182
srs5694cb76c672010-02-11 22:22:22 -05001183 // Check backup file size and rebuild second header if file is right
1184 // size to be direct dd copy of MBR, main header, and main partition
1185 // table; if other size, treat it like a GPT fdisk-generated backup
1186 // file
1187 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1188 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1189 if (shortBackup) {
1190 RebuildSecondHeader();
1191 secondCrcOk = mainCrcOk;
1192 } else {
1193 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1194 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001195
srs5694e7b4ff92009-08-18 13:16:10 -04001196 // Return valid headers code: 0 = both headers bad; 1 = main header
1197 // good, backup bad; 2 = backup header good, main header bad;
1198 // 3 = both headers good. Note these codes refer to valid GPT
1199 // signatures and version numbers; more subtle problems will elude
1200 // this check!
1201 if ((val = CheckHeaderValidity()) > 0) {
1202 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001203 SetGPTSize(secondHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001204 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001205 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001206 } // if/else
1207
srs5694e7b4ff92009-08-18 13:16:10 -04001208 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001209 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1210 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001211 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001212 } // if
1213
srs5694cb76c672010-02-11 22:22:22 -05001214 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1215 cerr << "Warning! Read error " << errno
1216 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001217 } else {
1218 allOK = 0;
1219 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001220 // Something went badly wrong, so blank out partitions
1221 if (allOK == 0) {
1222 cerr << "Improper backup file! Clearing all partition data!\n";
1223 ClearGPTData();
1224 protectiveMBR.MakeProtectiveMBR();
1225 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001226 } else {
1227 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001228 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001229 } // if/else
1230
srs5694e7b4ff92009-08-18 13:16:10 -04001231 return allOK;
1232} // GPTData::LoadGPTBackup()
1233
srs569408bb0da2010-02-19 17:19:55 -05001234int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001235 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001236} // GPTData::SaveMBR()
1237
1238// This function destroys the on-disk GPT structures, but NOT the on-disk
1239// MBR.
1240// Returns 1 if the operation succeeds, 0 if not.
1241int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001242 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001243 uint8_t blankSector[512];
1244 uint8_t* emptyTable;
1245
srs569401f7f082011-03-15 23:53:31 -04001246 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001247
1248 if (myDisk.OpenForWrite()) {
1249 if (!myDisk.Seek(mainHeader.currentLBA))
1250 allOK = 0;
1251 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1252 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1253 allOK = 0;
1254 } // if
1255 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1256 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001257 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001258 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001259 if (emptyTable == NULL) {
srs5694a17fe692011-09-10 20:30:20 -04001260 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
srs56946aae2a92011-06-10 01:16:51 -04001261 exit(1);
1262 } // if
srs569401f7f082011-03-15 23:53:31 -04001263 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001264 if (allOK) {
1265 sum = myDisk.Write(emptyTable, tableSize);
1266 if (sum != tableSize) {
1267 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1268 allOK = 0;
1269 } // if write failed
1270 } // if
1271 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1272 allOK = 0;
1273 if (allOK) {
1274 sum = myDisk.Write(emptyTable, tableSize);
1275 if (sum != tableSize) {
1276 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1277 << errno << "\n";
1278 allOK = 0;
1279 } // if wrong size written
1280 } // if
1281 if (!myDisk.Seek(secondHeader.currentLBA))
1282 allOK = 0;
1283 if (allOK) {
1284 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1285 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1286 allOK = 0;
1287 } // if
1288 } // if
1289 myDisk.DiskSync();
1290 myDisk.Close();
1291 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1292 << "other utilities.\n";
1293 delete[] emptyTable;
1294 } else {
srs56945a608532011-03-17 13:53:01 -04001295 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001296 } // if/else (fd != -1)
1297 return (allOK);
1298} // GPTDataTextUI::DestroyGPT()
1299
1300// Wipe MBR data from the disk (zero it out completely)
1301// Returns 1 on success, 0 on failure.
1302int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001303 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001304 uint8_t blankSector[512];
1305
srs569401f7f082011-03-15 23:53:31 -04001306 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001307
srs569401f7f082011-03-15 23:53:31 -04001308 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1309
srs569408bb0da2010-02-19 17:19:55 -05001310 if (!allOK)
1311 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1312 return allOK;
1313} // GPTData::DestroyMBR(void)
1314
srs5694e4ac11e2009-08-31 10:13:04 -04001315// Tell user whether Apple Partition Map (APM) was discovered....
1316void GPTData::ShowAPMState(void) {
1317 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001318 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001319 else
srs5694fed16d02010-01-27 23:03:40 -05001320 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001321} // GPTData::ShowAPMState()
1322
1323// Tell user about the state of the GPT data....
1324void GPTData::ShowGPTState(void) {
1325 switch (state) {
1326 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001327 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001328 break;
1329 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001330 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001331 break;
1332 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001333 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001334 break;
1335 default:
srs5694fed16d02010-01-27 23:03:40 -05001336 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001337 break;
1338 } // switch
1339} // GPTData::ShowGPTState()
1340
1341// Display the basic GPT data
1342void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001343 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001344 uint64_t temp, totalFree;
1345
srs5694fed16d02010-01-27 23:03:40 -05001346 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001347 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001348 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001349 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001350 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001351 cout << "First usable sector is " << mainHeader.firstUsableLBA
1352 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001353 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001354 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001355 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001356 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001357 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001358 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001359 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001360 } // for
1361} // GPTData::DisplayGPTData()
1362
srs5694e4ac11e2009-08-31 10:13:04 -04001363// Show detailed information on the specified partition
1364void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001365 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001366 partitions[partNum].ShowDetails(blockSize);
1367 } else {
srs5694fed16d02010-01-27 23:03:40 -05001368 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001369 } // if
1370} // GPTData::ShowPartDetails()
1371
srs5694e4ac11e2009-08-31 10:13:04 -04001372/**************************************************************************
1373 * *
1374 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1375 * (some of these functions may require user interaction) *
1376 * *
1377 **************************************************************************/
1378
srs569408bb0da2010-02-19 17:19:55 -05001379// Examines the MBR & GPT data to determine which set of data to use: the
1380// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1381// a new set of partitions (use_new). A return value of use_abort indicates
1382// that this function couldn't determine what to do. Overriding functions
1383// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001384WhichToUse GPTData::UseWhichPartitions(void) {
1385 WhichToUse which = use_new;
1386 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001387
1388 mbrState = protectiveMBR.GetValidity();
1389
1390 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001391 cout << "\n***************************************************************\n"
1392 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001393 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001394 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001395 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001396 } // if
srs5694fed16d02010-01-27 23:03:40 -05001397 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001398 which = use_mbr;
1399 } // if
1400
1401 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001402 cout << "\n**********************************************************************\n"
1403 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1404 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001405 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001406 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001407 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1408 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001409 } // if
srs5694fed16d02010-01-27 23:03:40 -05001410 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001411 which = use_bsd;
1412 } // if
1413
1414 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001415 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001416 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001417 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001418 } // if
1419 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001420 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001421 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001422 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001423 } // if
1424 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001425 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001426 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001427 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001428 } // if
1429 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001430 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001431 } // if
1432
srs5694e4ac11e2009-08-31 10:13:04 -04001433 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001434 if (mbrState == gpt) {
1435 cout << "\a\a****************************************************************************\n"
1436 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1437 << "verification and recovery are STRONGLY recommended.\n"
1438 << "****************************************************************************\n";
1439 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001440 } else {
srs569408bb0da2010-02-19 17:19:55 -05001441 which = use_abort;
1442 } // if/else MBR says disk is GPT
1443 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001444
1445 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001446 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001447
1448 return which;
1449} // UseWhichPartitions()
1450
srs569408bb0da2010-02-19 17:19:55 -05001451// Convert MBR partition table into GPT form.
1452void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001453 int i, numToConvert;
1454 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001455
1456 // Clear out old data & prepare basics....
1457 ClearGPTData();
1458
1459 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001460 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001461 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001462 else
srs56940283dae2010-04-28 16:44:34 -04001463 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001464
1465 for (i = 0; i < numToConvert; i++) {
1466 origType = protectiveMBR.GetType(i);
1467 // don't waste CPU time trying to convert extended, hybrid protective, or
1468 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001469 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001470 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001471 partitions[i] = protectiveMBR.AsGPT(i);
1472 } // for
1473
1474 // Convert MBR into protective MBR
1475 protectiveMBR.MakeProtectiveMBR();
1476
1477 // Record that all original CRCs were OK so as not to raise flags
1478 // when doing a disk verification
1479 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001480} // GPTData::XFormPartitions()
1481
1482// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001483// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001484// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001485int GPTData::XFormDisklabel(uint32_t partNum) {
1486 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001487 int goOn = 1, numDone = 0;
1488 BSDData disklabel;
1489
srs569408bb0da2010-02-19 17:19:55 -05001490 if (GetPartRange(&low, &high) == 0) {
1491 goOn = 0;
1492 cout << "No partitions!\n";
1493 } // if
1494 if (partNum > high) {
1495 goOn = 0;
1496 cout << "Specified partition is invalid!\n";
1497 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001498
srs569408bb0da2010-02-19 17:19:55 -05001499 // If all is OK, read the disklabel and convert it.
1500 if (goOn) {
1501 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1502 partitions[partNum].GetLastLBA());
1503 if ((goOn) && (disklabel.IsDisklabel())) {
1504 numDone = XFormDisklabel(&disklabel);
1505 if (numDone == 1)
1506 cout << "Converted 1 BSD partition.\n";
1507 else
1508 cout << "Converted " << numDone << " BSD partitions.\n";
1509 } else {
1510 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1511 } // if/else
1512 } // if
1513 if (numDone > 0) { // converted partitions; delete carrier
1514 partitions[partNum].BlankPartition();
1515 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001516 return numDone;
srs569455d92612010-03-07 22:16:07 -05001517} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001518
1519// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001520int GPTData::XFormDisklabel(BSDData* disklabel) {
1521 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001522
srs569408bb0da2010-02-19 17:19:55 -05001523 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001524 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001525 partNum = FindFirstFreePart();
1526 if (partNum >= 0) {
1527 partitions[partNum] = disklabel->AsGPT(i);
1528 if (partitions[partNum].IsUsed())
1529 numDone++;
1530 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001531 } // for
srs569408bb0da2010-02-19 17:19:55 -05001532 if (partNum == -1)
1533 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001534 } // if
1535
1536 // Record that all original CRCs were OK so as not to raise flags
1537 // when doing a disk verification
1538 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1539
1540 return numDone;
1541} // GPTData::XFormDisklabel(BSDData* disklabel)
1542
srs569408bb0da2010-02-19 17:19:55 -05001543// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1544// partition has the active/bootable flag UNset and uses the GPT fdisk
1545// type code divided by 0x0100 as the MBR type code.
1546// Returns 1 if operation was 100% successful, 0 if there were ANY
1547// problems.
srs5694978041c2009-09-21 20:51:47 -04001548int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001549 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001550
srs5694978041c2009-09-21 20:51:47 -04001551 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001552 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001553 allOK = 0;
1554 } // if
srs56940283dae2010-04-28 16:44:34 -04001555 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001556 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001557 allOK = 0;
1558 } // if
1559 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001560 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001561 allOK = 0;
1562 } // if
1563 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1564 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1565 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001566 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1567 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001568 } // if
srs5694978041c2009-09-21 20:51:47 -04001569 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001570 (uint32_t) partitions[gptPart].GetLengthLBA(),
1571 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001572 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001573 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1574 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1575 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001576 allOK = 0;
1577 } // if/else
1578 return allOK;
1579} // GPTData::OnePartToMBR()
1580
srs5694e4ac11e2009-08-31 10:13:04 -04001581
1582/**********************************************************************
1583 * *
1584 * Functions that adjust GPT data structures WITHOUT user interaction *
1585 * (they may display information for the user's benefit, though) *
1586 * *
1587 **********************************************************************/
1588
1589// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001590// necessary, copies data if it already exists. Returns 1 if all goes
1591// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001592int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001593 GPTPart* newParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001594 uint32_t i, high, copyNum;
1595 int allOK = 1;
1596
1597 // First, adjust numEntries upward, if necessary, to get a number
1598 // that fills the allocated sectors
1599 i = blockSize / GPT_SIZE;
1600 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001601 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001602 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001603 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001604 } // if
1605
srs5694247657a2009-11-26 18:36:12 -05001606 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001607 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001608 // partition table, which causes problems when loading data from a RAID
1609 // array that's been expanded because this function is called when loading
1610 // data.
srs56940283dae2010-04-28 16:44:34 -04001611 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001612 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001613 if (newParts != NULL) {
1614 if (partitions != NULL) { // existing partitions; copy them over
1615 GetPartRange(&i, &high);
1616 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001617 cout << "The highest-numbered partition is " << high + 1
1618 << ", which is greater than the requested\n"
1619 << "partition table size of " << numEntries
1620 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001621 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001622 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001623 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001624 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001625 copyNum = numEntries;
1626 else
srs56940283dae2010-04-28 16:44:34 -04001627 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001628 for (i = 0; i < copyNum; i++) {
1629 newParts[i] = partitions[i];
1630 } // for
srs569401f7f082011-03-15 23:53:31 -04001631 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001632 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001633 } // if
1634 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001635 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001636 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001637 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001638 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1639 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1640 MoveSecondHeaderToEnd();
1641 if (diskSize > 0)
1642 CheckGPTSize();
1643 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001644 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001645 allOK = 0;
1646 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001647 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001648 mainHeader.numParts = numParts;
1649 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001650 return (allOK);
1651} // GPTData::SetGPTSize()
1652
1653// Blank the partition array
1654void GPTData::BlankPartitions(void) {
1655 uint32_t i;
1656
srs56940283dae2010-04-28 16:44:34 -04001657 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001658 partitions[i].BlankPartition();
1659 } // for
1660} // GPTData::BlankPartitions()
1661
srs5694ba00fed2010-01-12 18:18:36 -05001662// Delete a partition by number. Returns 1 if successful,
1663// 0 if there was a problem. Returns 1 if partition was in
1664// range, 0 if it was out of range.
1665int GPTData::DeletePartition(uint32_t partNum) {
1666 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001667 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001668
srs56940283dae2010-04-28 16:44:34 -04001669 numUsedParts = GetPartRange(&low, &high);
1670 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001671 // In case there's a protective MBR, look for & delete matching
1672 // MBR partition....
1673 startSector = partitions[partNum].GetFirstLBA();
1674 length = partitions[partNum].GetLengthLBA();
1675 protectiveMBR.DeleteByLocation(startSector, length);
1676
1677 // Now delete the GPT partition
1678 partitions[partNum].BlankPartition();
1679 } else {
srs5694fed16d02010-01-27 23:03:40 -05001680 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001681 retval = 0;
1682 } // if/else
1683 return retval;
1684} // GPTData::DeletePartition(uint32_t partNum)
1685
srs569408bb0da2010-02-19 17:19:55 -05001686// Non-interactively create a partition.
1687// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001688uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001689 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001690 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001691
1692 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001693 if (Align(&startSector)) {
1694 cout << "Information: Moved requested sector from " << origSector << " to "
1695 << startSector << " in\norder to align on " << sectorAlignment
1696 << "-sector boundaries.\n";
1697 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001698 if (IsFree(startSector) && (startSector <= endSector)) {
1699 if (FindLastInFree(startSector) >= endSector) {
1700 partitions[partNum].SetFirstLBA(startSector);
1701 partitions[partNum].SetLastLBA(endSector);
srs569400b6d7a2011-06-26 22:40:06 -04001702 partitions[partNum].SetType(DEFAULT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001703 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001704 } else retval = 0; // if free space until endSector
1705 } else retval = 0; // if startSector is free
1706 } else retval = 0; // if legal partition number
1707 return retval;
1708} // GPTData::CreatePartition(partNum, startSector, endSector)
1709
srs5694e4ac11e2009-08-31 10:13:04 -04001710// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001711// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001712void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001713 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001714 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001715} // GPTData::SortGPT()
1716
srs569408bb0da2010-02-19 17:19:55 -05001717// Swap the contents of two partitions.
1718// Returns 1 if successful, 0 if either partition is out of range
1719// (that is, not a legal number; either or both can be empty).
1720// Note that if partNum1 = partNum2 and this number is in range,
1721// it will be considered successful.
1722int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1723 GPTPart temp;
1724 int allOK = 1;
1725
srs56940283dae2010-04-28 16:44:34 -04001726 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001727 if (partNum1 != partNum2) {
1728 temp = partitions[partNum1];
1729 partitions[partNum1] = partitions[partNum2];
1730 partitions[partNum2] = temp;
1731 } // if
1732 } else allOK = 0; // partition numbers are valid
1733 return allOK;
1734} // GPTData::SwapPartitions()
1735
srs5694e4ac11e2009-08-31 10:13:04 -04001736// Set up data structures for entirely new set of partitions on the
1737// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001738// Note that this function does NOT clear the protectiveMBR data
1739// structure, since it may hold the original MBR partitions if the
1740// program was launched on an MBR disk, and those may need to be
1741// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001742int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001743 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001744
1745 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001746 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001747 partitions = NULL;
1748 SetGPTSize(NUM_GPT_ENTRIES);
1749
1750 // Now initialize a bunch of stuff that's static....
1751 mainHeader.signature = GPT_SIGNATURE;
1752 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001753 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001754 mainHeader.reserved = 0;
1755 mainHeader.currentLBA = UINT64_C(1);
1756 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1757 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1758 for (i = 0; i < GPT_RESERVED; i++) {
1759 mainHeader.reserved2[i] = '\0';
1760 } // for
srs56940873e9d2010-10-07 13:00:45 -04001761 if (blockSize > 0)
1762 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1763 else
1764 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001765
1766 // Now some semi-static items (computed based on end of disk)
1767 mainHeader.backupLBA = diskSize - UINT64_C(1);
1768 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1769
1770 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001771 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001772
1773 // Copy main header to backup header
1774 RebuildSecondHeader();
1775
1776 // Blank out the partitions array....
1777 BlankPartitions();
1778
1779 // Flag all CRCs as being OK....
1780 mainCrcOk = 1;
1781 secondCrcOk = 1;
1782 mainPartsCrcOk = 1;
1783 secondPartsCrcOk = 1;
1784
1785 return (goOn);
1786} // GPTData::ClearGPTData()
1787
srs5694247657a2009-11-26 18:36:12 -05001788// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001789// If the disk size has actually changed, this also adjusts the protective
1790// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001791// Used internally and called by the 'e' option on the recovery &
1792// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001793// to their arrays or to adjust data structures in restore operations
1794// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001795void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001796 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001797 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1798 if (protectiveMBR.GetValidity() == hybrid) {
1799 protectiveMBR.OptimizeEESize();
1800 RecomputeCHS();
1801 } // if
1802 if (protectiveMBR.GetValidity() == gpt)
1803 MakeProtectiveMBR();
1804 } // if
srs56948bb78762009-11-24 15:43:49 -05001805 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1806 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1807} // GPTData::FixSecondHeaderLocation()
1808
srs5694699941e2011-03-21 21:33:57 -04001809// Sets the partition's name to the specified UnicodeString without
1810// user interaction.
1811// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001812int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001813 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001814
srs5694699941e2011-03-21 21:33:57 -04001815 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001816 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001817 else
1818 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001819
1820 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001821} // GPTData::SetName
1822
1823// Set the disk GUID to the specified value. Note that the header CRCs must
1824// be recomputed after calling this function.
1825void GPTData::SetDiskGUID(GUIDData newGUID) {
1826 mainHeader.diskGUID = newGUID;
1827 secondHeader.diskGUID = newGUID;
1828} // SetDiskGUID()
1829
1830// Set the unique GUID of the specified partition. Returns 1 on
1831// successful completion, 0 if there were problems (invalid
1832// partition number).
1833int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1834 int retval = 0;
1835
srs56940283dae2010-04-28 16:44:34 -04001836 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001837 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1838 partitions[pn].SetUniqueGUID(theGUID);
1839 retval = 1;
1840 } // if
1841 } // if
1842 return retval;
1843} // GPTData::SetPartitionGUID()
1844
srs56949ba54212010-05-18 23:24:02 -04001845// Set new random GUIDs for the disk and all partitions. Intended to be used
1846// after disk cloning or similar operations that don't randomize the GUIDs.
1847void GPTData::RandomizeGUIDs(void) {
1848 uint32_t i;
1849
1850 mainHeader.diskGUID.Randomize();
1851 secondHeader.diskGUID = mainHeader.diskGUID;
1852 for (i = 0; i < numParts; i++)
1853 if (partitions[i].IsUsed())
1854 partitions[i].RandomizeUniqueGUID();
1855} // GPTData::RandomizeGUIDs()
1856
srs5694ba00fed2010-01-12 18:18:36 -05001857// Change partition type code non-interactively. Returns 1 if
1858// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001859int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1860 int retval = 1;
1861
1862 if (!IsFreePartNum(partNum)) {
1863 partitions[partNum].SetType(theGUID);
1864 } else retval = 0;
1865 return retval;
1866} // GPTData::ChangePartType()
1867
srs56949ba54212010-05-18 23:24:02 -04001868// Recompute the CHS values of all the MBR partitions. Used to reset
1869// CHS values that some BIOSes require, despite the fact that the
1870// resulting CHS values violate the GPT standard.
1871void GPTData::RecomputeCHS(void) {
1872 int i;
1873
1874 for (i = 0; i < 4; i++)
1875 protectiveMBR.RecomputeCHS(i);
1876} // GPTData::RecomputeCHS()
1877
srs56941d1448a2009-12-31 21:20:19 -05001878// Adjust sector number so that it falls on a sector boundary that's a
1879// multiple of sectorAlignment. This is done to improve the performance
1880// of Western Digital Advanced Format disks and disks with similar
1881// technology from other companies, which use 4096-byte sectors
1882// internally although they translate to 512-byte sectors for the
1883// benefit of the OS. If partitions aren't properly aligned on these
1884// disks, some filesystem data structures can span multiple physical
1885// sectors, degrading performance. This function should be called
1886// only on the FIRST sector of the partition, not the last!
1887// This function returns 1 if the alignment was altered, 0 if it
1888// was unchanged.
1889int GPTData::Align(uint64_t* sector) {
1890 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001891 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001892
1893 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001894 earlier = (*sector / sectorAlignment) * sectorAlignment;
1895 later = earlier + (uint64_t) sectorAlignment;
1896
1897 // Check to see that every sector between the earlier one and the
1898 // requested one is clear, and that it's not too early....
1899 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001900 sectorOK = 1;
1901 testSector = earlier;
1902 do {
1903 sectorOK = IsFree(testSector++);
1904 } while ((sectorOK == 1) && (testSector < *sector));
1905 if (sectorOK == 1) {
1906 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001907 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001908 } // if
1909 } // if firstUsableLBA check
1910
1911 // If couldn't move the sector earlier, try to move it later instead....
1912 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1913 sectorOK = 1;
1914 testSector = later;
1915 do {
1916 sectorOK = IsFree(testSector--);
1917 } while ((sectorOK == 1) && (testSector > *sector));
1918 if (sectorOK == 1) {
1919 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001920 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001921 } // if
1922 } // if
srs56941d1448a2009-12-31 21:20:19 -05001923 } // if
1924 return retval;
1925} // GPTData::Align()
1926
srs5694e4ac11e2009-08-31 10:13:04 -04001927/********************************************************
1928 * *
1929 * Functions that return data about GPT data structures *
1930 * (most of these are inline in gpt.h) *
1931 * *
1932 ********************************************************/
1933
1934// Find the low and high used partition numbers (numbered from 0).
1935// Return value is the number of partitions found. Note that the
1936// *low and *high values are both set to 0 when no partitions
1937// are found, as well as when a single partition in the first
1938// position exists. Thus, the return value is the only way to
1939// tell when no partitions exist.
1940int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1941 uint32_t i;
1942 int numFound = 0;
1943
srs56940283dae2010-04-28 16:44:34 -04001944 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001945 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001946 for (i = 0; i < numParts; i++) {
1947 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1948 *high = i; // since we're counting up, set the high value
1949 // Set the low value only if it's not yet found...
1950 if (*low == (numParts + 1)) *low = i;
1951 numFound++;
1952 } // if
1953 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04001954
1955 // Above will leave *low pointing to its "not found" value if no partitions
1956 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001957 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001958 *low = 0;
1959 return numFound;
1960} // GPTData::GetPartRange()
1961
srs569408bb0da2010-02-19 17:19:55 -05001962// Returns the value of the first free partition, or -1 if none is
1963// unused.
1964int GPTData::FindFirstFreePart(void) {
1965 int i = 0;
1966
1967 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04001968 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05001969 i++;
srs56940283dae2010-04-28 16:44:34 -04001970 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001971 i = -1;
1972 } else i = -1;
1973 return i;
1974} // GPTData::FindFirstFreePart()
1975
srs5694978041c2009-09-21 20:51:47 -04001976// Returns the number of defined partitions.
1977uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001978 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001979
srs56940283dae2010-04-28 16:44:34 -04001980 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001981 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001982 counted++;
1983 } // for
1984 return counted;
1985} // GPTData::CountParts()
1986
srs5694e4ac11e2009-08-31 10:13:04 -04001987/****************************************************
1988 * *
1989 * Functions that return data about disk free space *
1990 * *
1991 ****************************************************/
1992
1993// Find the first available block after the starting point; returns 0 if
1994// there are no available blocks left
1995uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1996 uint64_t first;
1997 uint32_t i;
1998 int firstMoved = 0;
1999
2000 // Begin from the specified starting point or from the first usable
2001 // LBA, whichever is greater...
2002 if (start < mainHeader.firstUsableLBA)
2003 first = mainHeader.firstUsableLBA;
2004 else
2005 first = start;
2006
2007 // ...now search through all partitions; if first is within an
2008 // existing partition, move it to the next sector after that
2009 // partition and repeat. If first was moved, set firstMoved
2010 // flag; repeat until firstMoved is not set, so as to catch
2011 // cases where partitions are out of sequential order....
2012 do {
2013 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002014 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002015 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002016 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002017 first = partitions[i].GetLastLBA() + 1;
2018 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002019 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002020 } // for
2021 } while (firstMoved == 1);
2022 if (first > mainHeader.lastUsableLBA)
2023 first = 0;
2024 return (first);
2025} // GPTData::FindFirstAvailable()
2026
2027// Finds the first available sector in the largest block of unallocated
2028// space on the disk. Returns 0 if there are no available blocks left
2029uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002030 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002031
2032 start = 0;
2033 do {
2034 firstBlock = FindFirstAvailable(start);
2035 if (firstBlock != UINT32_C(0)) { // something's free...
2036 lastBlock = FindLastInFree(firstBlock);
2037 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2038 if (segmentSize > selectedSize) {
2039 selectedSize = segmentSize;
2040 selectedSegment = firstBlock;
2041 } // if
2042 start = lastBlock + 1;
2043 } // if
2044 } while (firstBlock != 0);
2045 return selectedSegment;
2046} // GPTData::FindFirstInLargest()
2047
srs5694cb76c672010-02-11 22:22:22 -05002048// Find the last available block on the disk.
2049// Returns 0 if there are no available partitions
2050uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002051 uint64_t last;
2052 uint32_t i;
2053 int lastMoved = 0;
2054
2055 // Start by assuming the last usable LBA is available....
2056 last = mainHeader.lastUsableLBA;
2057
2058 // ...now, similar to algorithm in FindFirstAvailable(), search
2059 // through all partitions, moving last when it's in an existing
2060 // partition. Set the lastMoved flag so we repeat to catch cases
2061 // where partitions are out of logical order.
2062 do {
2063 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002064 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002065 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002066 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002067 last = partitions[i].GetFirstLBA() - 1;
2068 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002069 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002070 } // for
2071 } while (lastMoved == 1);
2072 if (last < mainHeader.firstUsableLBA)
2073 last = 0;
2074 return (last);
2075} // GPTData::FindLastAvailable()
2076
2077// Find the last available block in the free space pointed to by start.
2078uint64_t GPTData::FindLastInFree(uint64_t start) {
2079 uint64_t nearestStart;
2080 uint32_t i;
2081
2082 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002083 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002084 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002085 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002086 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002087 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002088 } // for
2089 return (nearestStart);
2090} // GPTData::FindLastInFree()
2091
2092// Finds the total number of free blocks, the number of segments in which
2093// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002094uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002095 uint64_t start = UINT64_C(0); // starting point for each search
2096 uint64_t totalFound = UINT64_C(0); // running total
2097 uint64_t firstBlock; // first block in a segment
2098 uint64_t lastBlock; // last block in a segment
2099 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002100 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002101
2102 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002103 if (diskSize > 0) {
2104 do {
2105 firstBlock = FindFirstAvailable(start);
2106 if (firstBlock != UINT64_C(0)) { // something's free...
2107 lastBlock = FindLastInFree(firstBlock);
2108 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2109 if (segmentSize > *largestSegment) {
2110 *largestSegment = segmentSize;
2111 } // if
2112 totalFound += segmentSize;
2113 num++;
2114 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002115 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002116 } while (firstBlock != 0);
2117 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002118 *numSegments = num;
2119 return totalFound;
2120} // GPTData::FindFreeBlocks()
2121
srs569455d92612010-03-07 22:16:07 -05002122// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2123// If it's allocated, return the partition number to which it's allocated
2124// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2125// returned in partNum if the sector is in use by basic GPT data structures.)
2126int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002127 int isFree = 1;
2128 uint32_t i;
2129
srs56940283dae2010-04-28 16:44:34 -04002130 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002131 if ((sector >= partitions[i].GetFirstLBA()) &&
2132 (sector <= partitions[i].GetLastLBA())) {
2133 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002134 if (partNum != NULL)
2135 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002136 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002137 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002138 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002139 (sector > mainHeader.lastUsableLBA)) {
2140 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002141 if (partNum != NULL)
2142 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002143 } // if
2144 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002145} // GPTData::IsFree()
2146
srs5694815fb652011-03-18 12:35:56 -04002147// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002148int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002149 return ((partNum < numParts) && (partitions != NULL) &&
2150 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002151} // GPTData::IsFreePartNum()
2152
srs5694815fb652011-03-18 12:35:56 -04002153// Returns 1 if partNum is in use.
2154int GPTData::IsUsedPartNum(uint32_t partNum) {
2155 return ((partNum < numParts) && (partitions != NULL) &&
2156 (partitions[partNum].IsUsed()));
2157} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002158
2159/***********************************************************
2160 * *
2161 * Change how functions work or return information on them *
2162 * *
2163 ***********************************************************/
2164
2165// Set partition alignment value; partitions will begin on multiples of
2166// the specified value
2167void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002168 if (n > 0)
2169 sectorAlignment = n;
2170 else
2171 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002172} // GPTData::SetAlignment()
2173
2174// Compute sector alignment based on the current partitions (if any). Each
2175// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002176// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2177// sector size), but not by the previously-located alignment value, then the
2178// alignment value is adjusted down. If the computed alignment is less than 8
2179// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2180// is a safety measure for WD Advanced Format and similar drives. If no partitions
2181// are defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2182// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002183// drives are aligned to 2048-sector multiples but the program won't complain
2184// about other alignments on existing disks unless a smaller-than-8 alignment
srs56940873e9d2010-10-07 13:00:45 -04002185// is used on big disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002186// Returns the computed alignment value.
2187uint32_t GPTData::ComputeAlignment(void) {
2188 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002189 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002190
srs56940873e9d2010-10-07 13:00:45 -04002191 if (blockSize > 0)
2192 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2193 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002194 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002195 if (partitions[i].IsUsed()) {
2196 found = 0;
2197 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002198 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002199 if ((partitions[i].GetFirstLBA() % align) == 0) {
2200 found = 1;
2201 } else {
2202 exponent--;
2203 } // if/else
2204 } // while
2205 } // if
2206 } // for
srs56940873e9d2010-10-07 13:00:45 -04002207 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2208 align = MIN_AF_ALIGNMENT;
2209 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002210 return align;
2211} // GPTData::ComputeAlignment()
2212
srs5694e4ac11e2009-08-31 10:13:04 -04002213/********************************
2214 * *
2215 * Endianness support functions *
2216 * *
2217 ********************************/
2218
srs56942a9f5da2009-08-26 00:48:01 -04002219void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002220 ReverseBytes(&header->signature, 8);
2221 ReverseBytes(&header->revision, 4);
2222 ReverseBytes(&header->headerSize, 4);
2223 ReverseBytes(&header->headerCRC, 4);
2224 ReverseBytes(&header->reserved, 4);
2225 ReverseBytes(&header->currentLBA, 8);
2226 ReverseBytes(&header->backupLBA, 8);
2227 ReverseBytes(&header->firstUsableLBA, 8);
2228 ReverseBytes(&header->lastUsableLBA, 8);
2229 ReverseBytes(&header->partitionEntriesLBA, 8);
2230 ReverseBytes(&header->numParts, 4);
2231 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2232 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002233 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002234} // GPTData::ReverseHeaderBytes()
2235
srs56940283dae2010-04-28 16:44:34 -04002236// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002237void GPTData::ReversePartitionBytes() {
2238 uint32_t i;
2239
srs56940283dae2010-04-28 16:44:34 -04002240 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002241 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002242 } // for
2243} // GPTData::ReversePartitionBytes()
2244
srs56949ddc14b2010-08-22 22:44:42 -04002245// Validate partition number
2246bool GPTData::ValidPartNum (const uint32_t partNum) {
2247 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002248 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002249 return false;
2250 } // if
2251 return true;
2252} // GPTData::ValidPartNum
2253
srs56945a081752010-09-24 20:39:41 -04002254// Return a single partition for inspection (not modification!) by other
2255// functions.
2256const GPTPart & GPTData::operator[](uint32_t partNum) const {
2257 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002258 cerr << "Partition number out of range (" << partNum << " requested, but only "
2259 << numParts << " available)\n";
2260 exit(1);
2261 } // if
2262 if (partitions == NULL) {
2263 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2264 exit(1);
srs56945a081752010-09-24 20:39:41 -04002265 } // if
2266 return partitions[partNum];
2267} // operator[]
2268
2269// Return (not for modification!) the disk's GUID value
2270const GUIDData & GPTData::GetDiskGUID(void) const {
2271 return mainHeader.diskGUID;
2272} // GPTData::GetDiskGUID()
2273
srs56949ddc14b2010-08-22 22:44:42 -04002274// Manage attributes for a partition, based on commands passed to this function.
2275// (Function is non-interactive.)
2276// Returns 1 if a modification command succeeded, 0 if the command should not have
2277// modified data, and -1 if a modification command failed.
2278int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2279 int retval = 0;
2280 Attributes theAttr;
2281
2282 if (command == "show") {
2283 ShowAttributes(partNum);
2284 } else if (command == "get") {
2285 GetAttribute(partNum, bits);
2286 } else {
2287 theAttr = partitions[partNum].GetAttributes();
2288 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2289 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2290 retval = 1;
2291 } else {
2292 retval = -1;
2293 } // if/else
2294 } // if/elseif/else
2295
2296 return retval;
2297} // GPTData::ManageAttributes()
2298
2299// Show all attributes for a specified partition....
2300void GPTData::ShowAttributes(const uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04002301 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002302} // GPTData::ShowAttributes
2303
2304// Show whether a single attribute bit is set (terse output)...
2305void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002306 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002307} // GPTData::GetAttribute
2308
2309
srs56942a9f5da2009-08-26 00:48:01 -04002310/******************************************
2311 * *
2312 * Additional non-class support functions *
2313 * *
2314 ******************************************/
2315
srs5694e7b4ff92009-08-18 13:16:10 -04002316// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2317// never fail these tests, but the struct types may fail depending on compile options.
2318// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2319// sizes.
2320int SizesOK(void) {
2321 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002322
2323 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002324 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002325 allOK = 0;
2326 } // if
2327 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002328 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002329 allOK = 0;
2330 } // if
2331 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002332 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002333 allOK = 0;
2334 } // if
2335 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002336 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002337 allOK = 0;
2338 } // if
2339 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002340 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002341 allOK = 0;
2342 } // if
srs5694978041c2009-09-21 20:51:47 -04002343 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002344 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002345 allOK = 0;
2346 } // if
2347 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002348 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002349 allOK = 0;
2350 } // if
srs5694221e0872009-08-29 15:00:31 -04002351 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002352 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002353 allOK = 0;
2354 } // if
srs56946699b012010-02-04 00:55:30 -05002355 if (sizeof(GUIDData) != 16) {
2356 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2357 allOK = 0;
2358 } // if
2359 if (sizeof(PartType) != 16) {
2360 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2361 allOK = 0;
2362 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002363 return (allOK);
2364} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002365