blob: f571ad79ea3019311b422b3df3def2ad5ab5d5b0 [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
srs5694d8eed462012-12-15 01:55:21 -05006/* This program is copyright (c) 2009-2012 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040022#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "crc32.h"
24#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040025#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040026#include "support.h"
27#include "parttypes.h"
28#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050029#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040030
31using namespace std;
32
srs56948f1b2d62010-05-23 13:07:19 -040033#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040034#define log2(x) (log(x) / M_LN2)
35#endif // __FreeBSD__
36
srs56948f1b2d62010-05-23 13:07:19 -040037#ifdef _MSC_VER
38#define log2(x) (log((double) x) / log(2.0))
39#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040040
srs5694e7b4ff92009-08-18 13:16:10 -040041/****************************************
42 * *
43 * GPTData class and related structures *
44 * *
45 ****************************************/
46
srs5694e4ac11e2009-08-31 10:13:04 -040047// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040048GPTData::GPTData(void) {
49 blockSize = SECTOR_SIZE; // set a default
50 diskSize = 0;
51 partitions = NULL;
52 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050053 device = "";
srs56945d58fe02010-01-03 20:57:08 -050054 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040055 mainCrcOk = 0;
56 secondCrcOk = 0;
57 mainPartsCrcOk = 0;
58 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040059 apmFound = 0;
60 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040061 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050062 beQuiet = 0;
63 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050064 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040065 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040066 SetGPTSize(NUM_GPT_ENTRIES);
srs5694d1b11e82011-09-18 21:12:28 -040067 // Initialize CRC functions...
68 chksum_crc32gentab();
srs5694e7b4ff92009-08-18 13:16:10 -040069} // GPTData default constructor
70
71// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050072GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040073 blockSize = SECTOR_SIZE; // set a default
74 diskSize = 0;
75 partitions = NULL;
76 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050077 device = "";
srs56945d58fe02010-01-03 20:57:08 -050078 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040079 mainCrcOk = 0;
80 secondCrcOk = 0;
81 mainPartsCrcOk = 0;
82 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040083 apmFound = 0;
84 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040085 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050086 beQuiet = 0;
87 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050088 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040089 numParts = 0;
srs5694d1b11e82011-09-18 21:12:28 -040090 // Initialize CRC functions...
91 chksum_crc32gentab();
srs56943c0af382010-01-15 19:19:18 -050092 if (!LoadPartitions(filename))
93 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050094} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040095
srs5694e4ac11e2009-08-31 10:13:04 -040096// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040097GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050098 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040099} // GPTData destructor
100
srs569464cbd172011-03-01 22:03:54 -0500101// Assignment operator
102GPTData & GPTData::operator=(const GPTData & orig) {
103 uint32_t i;
104
105 mainHeader = orig.mainHeader;
106 numParts = orig.numParts;
107 secondHeader = orig.secondHeader;
108 protectiveMBR = orig.protectiveMBR;
109 device = orig.device;
110 blockSize = orig.blockSize;
111 diskSize = orig.diskSize;
112 state = orig.state;
113 justLooking = orig.justLooking;
114 mainCrcOk = orig.mainCrcOk;
115 secondCrcOk = orig.secondCrcOk;
116 mainPartsCrcOk = orig.mainPartsCrcOk;
117 secondPartsCrcOk = orig.secondPartsCrcOk;
118 apmFound = orig.apmFound;
119 bsdFound = orig.bsdFound;
120 sectorAlignment = orig.sectorAlignment;
121 beQuiet = orig.beQuiet;
122 whichWasUsed = orig.whichWasUsed;
123
124 myDisk.OpenForRead(orig.myDisk.GetName());
125
126 delete[] partitions;
srs569401f7f082011-03-15 23:53:31 -0400127 partitions = new GPTPart [numParts];
srs56946aae2a92011-06-10 01:16:51 -0400128 if (partitions == NULL) {
srs569464cbd172011-03-01 22:03:54 -0500129 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
srs56946aae2a92011-06-10 01:16:51 -0400130 << "Terminating!\n";
131 exit(1);
132 } // if
133 for (i = 0; i < numParts; i++) {
134 partitions[i] = orig.partitions[i];
srs5694d1b11e82011-09-18 21:12:28 -0400135 } // for
136
srs569464cbd172011-03-01 22:03:54 -0500137 return *this;
138} // GPTData::operator=()
139
srs5694e4ac11e2009-08-31 10:13:04 -0400140/*********************************************************************
141 * *
142 * Begin functions that verify data, or that adjust the verification *
143 * information (compute CRCs, rebuild headers) *
144 * *
145 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400146
srs5694e4ac11e2009-08-31 10:13:04 -0400147// Perform detailed verification, reporting on any problems found, but
148// do *NOT* recover from these problems. Returns the total number of
149// problems identified.
150int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500151 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500152 uint32_t i, numSegments;
153 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400154
155 // First, check for CRC errors in the GPT data....
156 if (!mainCrcOk) {
157 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500158 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
159 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
160 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
161 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (!mainPartsCrcOk) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
166 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
167 << "transformation menu). This report may be a false alarm if you've already\n"
168 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400169 } // if
170 if (!secondCrcOk) {
171 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500172 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
173 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
174 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
175 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400176 } // if
177 if (!secondPartsCrcOk) {
178 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500179 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
180 << "be corrupt. This program will automatically create a new backup partition\n"
181 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400182 } // if
183
srs5694978041c2009-09-21 20:51:47 -0400184 // Now check that the main and backup headers both point to themselves....
185 if (mainHeader.currentLBA != 1) {
186 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500187 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
188 << "is being automatically corrected, but it may be a symptom of more serious\n"
189 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400190 mainHeader.currentLBA = 1;
191 } // if
192 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
193 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500194 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
195 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
196 << "option on the experts' menu to adjust the secondary header's and partition\n"
197 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400198 } // if
199
200 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400201 if (mainHeader.currentLBA != secondHeader.backupLBA) {
202 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500203 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
204 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
205 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400206 } // if
207 if (mainHeader.backupLBA != secondHeader.currentLBA) {
208 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500209 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
210 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
211 << secondHeader.currentLBA << ").\n"
212 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400213 } // if
214 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
215 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500216 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
217 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
218 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400219 } // if
220 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
221 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500222 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
223 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
224 << secondHeader.lastUsableLBA << ")\n"
225 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400226 } // if
srs56946699b012010-02-04 00:55:30 -0500227 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400228 problems++;
srs56945a081752010-09-24 20:39:41 -0400229 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500230 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400231 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500232 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
233 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400234 } // if
235 if (mainHeader.numParts != secondHeader.numParts) {
236 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500237 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
238 << ") doesn't\nmatch the backup GPT header's number of partitions ("
239 << secondHeader.numParts << ")\n"
240 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400241 } // if
242 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
243 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500244 cout << "\nProblem: main GPT header's size of partition entries ("
245 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
246 << "match the backup GPT header's size of partition entries ("
247 << secondHeader.sizeOfPartitionEntries << ")\n"
248 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
249 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400250 } // if
251
252 // Now check for a few other miscellaneous problems...
253 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500254 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400255 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500256 cout << "\nProblem: Disk is too small to hold all the data!\n"
257 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500258 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500259 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400260 } // if
261
srs5694d8eed462012-12-15 01:55:21 -0500262 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
263 problems++;
srs56940741fa22013-01-09 12:55:40 -0500264 cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
265 << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
266 << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
267 << "The 'e' option on the experts' menu will probably fix this problem\n";
srs5694d8eed462012-12-15 01:55:21 -0500268 }
269
srs5694e4ac11e2009-08-31 10:13:04 -0400270 // Check for overlapping partitions....
271 problems += FindOverlaps();
272
srs569455d92612010-03-07 22:16:07 -0500273 // Check for insane partitions (start after end, hugely big, etc.)
274 problems += FindInsanePartitions();
275
srs5694e4ac11e2009-08-31 10:13:04 -0400276 // Check for mismatched MBR and GPT partitions...
277 problems += FindHybridMismatches();
278
srs5694327129e2010-09-22 01:07:31 -0400279 // Check for MBR-specific problems....
280 problems += VerifyMBR();
281
srs5694e4ac11e2009-08-31 10:13:04 -0400282 // Verify that partitions don't run into GPT data areas....
283 problems += CheckGPTSize();
284
srs56941d1448a2009-12-31 21:20:19 -0500285 // Check that partitions are aligned on proper boundaries (for WD Advanced
286 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400287 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500288 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500289 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
290 << sectorAlignment << "-sector boundary. This may\nresult "
291 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500292 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500293 } // if
294 } // for
srs569464cbd172011-03-01 22:03:54 -0500295 if (alignProbs > 0)
296 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
297 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500298
srs5694e4ac11e2009-08-31 10:13:04 -0400299 // Now compute available space, but only if no problems found, since
300 // problems could affect the results
301 if (problems == 0) {
302 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500303 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400304 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500305 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400306 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400307 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400308 } else {
srs56940a697312010-01-28 21:10:52 -0500309 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400310 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400311
312 return (problems);
313} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400314
315// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400316// do, issues a warning but takes no action. Returns number of problems
317// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400318int GPTData::CheckGPTSize(void) {
319 uint64_t overlap, firstUsedBlock, lastUsedBlock;
320 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400321 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400322
323 // first, locate the first & last used blocks
324 firstUsedBlock = UINT64_MAX;
325 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400326 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500327 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500328 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500329 firstUsedBlock = partitions[i].GetFirstLBA();
330 if (partitions[i].GetLastLBA() > lastUsedBlock) {
331 lastUsedBlock = partitions[i].GetLastLBA();
332 } // if
333 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400334 } // for
335
336 // If the disk size is 0 (the default), then it means that various
337 // variables aren't yet set, so the below tests will be useless;
338 // therefore we should skip everything
339 if (diskSize != 0) {
340 if (mainHeader.firstUsableLBA > firstUsedBlock) {
341 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500342 cout << "Warning! Main partition table overlaps the first partition by "
343 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400344 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500345 cout << "Try reducing the partition table size by " << overlap * 4
346 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400347 } else {
srs5694fed16d02010-01-27 23:03:40 -0500348 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400349 } // if/else
350 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400351 } // Problem at start of disk
352 if (mainHeader.lastUsableLBA < lastUsedBlock) {
353 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500354 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500355 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400356 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500357 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400358 } else {
srs5694fed16d02010-01-27 23:03:40 -0500359 cout << "Try reducing the partition table size by " << overlap * 4
360 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400361 } // if/else
362 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400363 } // Problem at end of disk
364 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400365 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400366} // GPTData::CheckGPTSize()
367
srs5694e7b4ff92009-08-18 13:16:10 -0400368// Check the validity of the GPT header. Returns 1 if the main header
369// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400370// 0 if neither is valid. Note that this function checks the GPT signature,
371// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400372int GPTData::CheckHeaderValidity(void) {
373 int valid = 3;
374
srs5694fed16d02010-01-27 23:03:40 -0500375 cout.setf(ios::uppercase);
376 cout.fill('0');
377
378 // Note: failed GPT signature checks produce no error message because
379 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400380 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400381 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400382 } else if ((mainHeader.revision != 0x00010000) && valid) {
383 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500384 cout << "Unsupported GPT version in main header; read 0x";
385 cout.width(8);
386 cout << hex << mainHeader.revision << ", should be\n0x";
387 cout.width(8);
388 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400389 } // if/else/if
390
srs5694d1b11e82011-09-18 21:12:28 -0400391 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400392 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400393 } else if ((secondHeader.revision != 0x00010000) && valid) {
394 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500395 cout << "Unsupported GPT version in backup header; read 0x";
396 cout.width(8);
397 cout << hex << secondHeader.revision << ", should be\n0x";
398 cout.width(8);
399 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400400 } // if/else/if
401
srs5694df9d3632011-01-08 18:33:24 -0500402 // Check for an Apple disk signature
403 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
404 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400405 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500406 } // if
srs5694fed16d02010-01-27 23:03:40 -0500407 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400408
srs5694fed16d02010-01-27 23:03:40 -0500409 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400410} // GPTData::CheckHeaderValidity()
411
412// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400413// Note: Must be called with header in platform-ordered byte order.
414// Returns 1 if header's computed CRC matches the stored value, 0 if the
415// computed and stored values don't match
416int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400417 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400418 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400419
srs56942a9f5da2009-08-26 00:48:01 -0400420 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400421 // computation to be valid
422 oldCRC = header->headerCRC;
423 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400424
srs5694978041c2009-09-21 20:51:47 -0400425 hSize = header->headerSize;
426
srs5694d1b11e82011-09-18 21:12:28 -0400427 if (IsLittleEndian() == 0)
428 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400429
srs5694d1b11e82011-09-18 21:12:28 -0400430 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
431 if (warn) {
432 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
433 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
434 } // if
435 hSize = HEADER_SIZE;
436 } else if ((hSize > sizeof(GPTHeader)) && warn) {
437 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
438 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
439 << "which may result in a CRC false alarm.\n";
440 } // if/elseif
441 temp = new uint8_t[hSize];
442 if (temp != NULL) {
443 memset(temp, 0, hSize);
444 if (hSize < sizeof(GPTHeader))
445 memcpy(temp, header, hSize);
446 else
447 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400448
srs5694d1b11e82011-09-18 21:12:28 -0400449 newCRC = chksum_crc32((unsigned char*) temp, hSize);
450 delete[] temp;
451 } else {
452 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
453 exit(1);
454 }
455 if (IsLittleEndian() == 0)
456 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400457 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400458 return (oldCRC == newCRC);
459} // GPTData::CheckHeaderCRC()
460
srs56946699b012010-02-04 00:55:30 -0500461// Recompute all the CRCs. Must be called before saving if any changes have
462// been made. Must be called on platform-ordered data (this function reverses
463// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400464void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400465 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400466 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400467
srs5694d1b11e82011-09-18 21:12:28 -0400468 // If the header size is bigger than the GPT header data structure, reset it;
469 // otherwise, set both header sizes to whatever the main one is....
470 if (mainHeader.headerSize > sizeof(GPTHeader))
471 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
472 else
473 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500474
475 if ((littleEndian = IsLittleEndian()) == 0) {
476 ReversePartitionBytes();
477 ReverseHeaderBytes(&mainHeader);
478 ReverseHeaderBytes(&secondHeader);
479 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400480
srs5694e7b4ff92009-08-18 13:16:10 -0400481 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400482 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400483 mainHeader.partitionEntriesCRC = crc;
484 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400485 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400486 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
487 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400488 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400489
srs5694d1b11e82011-09-18 21:12:28 -0400490 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400491 mainHeader.headerCRC = 0;
492 secondHeader.headerCRC = 0;
493
srs5694978041c2009-09-21 20:51:47 -0400494 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400495 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400496 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400497 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400498 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400499 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400500 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400501 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500502
srs5694d1b11e82011-09-18 21:12:28 -0400503 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500504 ReverseHeaderBytes(&mainHeader);
505 ReverseHeaderBytes(&secondHeader);
506 ReversePartitionBytes();
507 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400508} // GPTData::RecomputeCRCs()
509
srs5694e7b4ff92009-08-18 13:16:10 -0400510// Rebuild the main GPT header, using the secondary header as a model.
511// Typically called when the main header has been found to be corrupt.
512void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400513 mainHeader.signature = GPT_SIGNATURE;
514 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400515 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400516 mainHeader.headerCRC = UINT32_C(0);
517 mainHeader.reserved = secondHeader.reserved;
518 mainHeader.currentLBA = secondHeader.backupLBA;
519 mainHeader.backupLBA = secondHeader.currentLBA;
520 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
521 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500522 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400523 mainHeader.partitionEntriesLBA = UINT64_C(2);
524 mainHeader.numParts = secondHeader.numParts;
525 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
526 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400527 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500528 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500529 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400530} // GPTData::RebuildMainHeader()
531
532// Rebuild the secondary GPT header, using the main header as a model.
533void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400534 secondHeader.signature = GPT_SIGNATURE;
535 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400536 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400537 secondHeader.headerCRC = UINT32_C(0);
538 secondHeader.reserved = mainHeader.reserved;
539 secondHeader.currentLBA = mainHeader.backupLBA;
540 secondHeader.backupLBA = mainHeader.currentLBA;
541 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
542 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500543 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400544 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
545 secondHeader.numParts = mainHeader.numParts;
546 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
547 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400548 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500549 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500550 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400551} // GPTData::RebuildSecondHeader()
552
553// Search for hybrid MBR entries that have no corresponding GPT partition.
554// Returns number of such mismatches found
555int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500556 int i, found, numFound = 0;
557 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400558 uint64_t mbrFirst, mbrLast;
559
560 for (i = 0; i < 4; i++) {
561 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
562 j = 0;
563 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400564 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
565 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400566 do {
srs5694e4ac11e2009-08-31 10:13:04 -0400567 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500568 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400569 found = 1;
570 j++;
srs56940283dae2010-04-28 16:44:34 -0400571 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400572 if (!found) {
573 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500574 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
575 << i + 1 << ", of type 0x";
576 cout.fill('0');
577 cout.setf(ios::uppercase);
578 cout.width(2);
579 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
580 << "has no corresponding GPT partition! You may continue, but this condition\n"
581 << "might cause data loss in the future!\a\n" << dec;
582 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400583 } // if
584 } // if
585 } // for
586 return numFound;
587} // GPTData::FindHybridMismatches
588
589// Find overlapping partitions and warn user about them. Returns number of
590// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400591// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400592int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500593 int problems = 0;
594 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400595
srs56940283dae2010-04-28 16:44:34 -0400596 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400597 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500598 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
599 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400600 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500601 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
602 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
603 << " to " << partitions[i].GetLastLBA() << "\n";
604 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
605 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400606 } // if
607 } // for j...
608 } // for i...
609 return problems;
610} // GPTData::FindOverlaps()
611
srs569455d92612010-03-07 22:16:07 -0500612// Find partitions that are insane -- they start after they end or are too
613// big for the disk. (The latter should duplicate detection of overlaps
614// with GPT backup data structures, but better to err on the side of
615// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400616// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500617int GPTData::FindInsanePartitions(void) {
618 uint32_t i;
619 int problems = 0;
620
srs56940283dae2010-04-28 16:44:34 -0400621 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500622 if (partitions[i].IsUsed()) {
623 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
624 problems++;
625 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
626 } // if
627 if (partitions[i].GetLastLBA() >= diskSize) {
628 problems++;
629 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
630 } // if
srs569455d92612010-03-07 22:16:07 -0500631 } // if
632 } // for
633 return problems;
634} // GPTData::FindInsanePartitions(void)
635
636
srs5694e4ac11e2009-08-31 10:13:04 -0400637/******************************************************************
638 * *
639 * Begin functions that load data from disk or save data to disk. *
640 * *
641 ******************************************************************/
642
srs569464cbd172011-03-01 22:03:54 -0500643// Change the filename associated with the GPT. Used for duplicating
644// the partition table to a new disk and saving backups.
645// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500646int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500647 int err, allOK = 1;
648
649 device = deviceFilename;
650 if (allOK && myDisk.OpenForRead(deviceFilename)) {
651 // store disk information....
652 diskSize = myDisk.DiskSize(&err);
653 blockSize = (uint32_t) myDisk.GetBlockSize();
654 } // if
655 protectiveMBR.SetDisk(&myDisk);
656 protectiveMBR.SetDiskSize(diskSize);
657 protectiveMBR.SetBlockSize(blockSize);
658 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500659} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500660
srs5694e4ac11e2009-08-31 10:13:04 -0400661// Scan for partition data. This function loads the MBR data (regular MBR or
662// protective MBR) and loads BSD disklabel data (which is probably invalid).
663// It also looks for APM data, forces a load of GPT data, and summarizes
664// the results.
srs5694546a9c72010-01-26 16:00:26 -0500665void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400666 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400667
668 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500669 protectiveMBR.ReadMBRData(&myDisk);
670 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400671
672 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500673 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500674
675 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500676 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500677 protectiveMBR.ShowState();
678 bsdDisklabel.ShowState();
679 ShowAPMState(); // Show whether there's an Apple Partition Map present
680 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500681 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500682 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400683
684 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500685 cout << "\n*******************************************************************\n"
686 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500687 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500688 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500689 } // if
srs5694fed16d02010-01-27 23:03:40 -0500690 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400691 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400692} // GPTData::PartitionScan()
693
694// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500695int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500696 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500697 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500698 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400699
srs5694546a9c72010-01-26 16:00:26 -0500700 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500701 err = myDisk.OpenForWrite(deviceFilename);
702 if ((err == 0) && (!justLooking)) {
703 cout << "\aNOTE: Write test failed with error number " << errno
704 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
705#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
706 cout << "You may be able to enable writes by exiting this program, typing\n"
707 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
708 << "program.\n";
709#endif
710 cout << "\n";
711 } // if
712 myDisk.Close(); // Close and re-open read-only in case of bugs
713 } else allOK = 0; // if
714
715 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400716 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500717 diskSize = myDisk.DiskSize(&err);
718 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500719 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500720 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400721
srs5694ba00fed2010-01-12 18:18:36 -0500722 whichWasUsed = UseWhichPartitions();
723 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400724 case use_mbr:
725 XFormPartitions();
726 break;
727 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500728 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400729// bsdDisklabel.DisplayBSDData();
730 ClearGPTData();
731 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500732 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400733 break;
734 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500735 mbrState = protectiveMBR.GetValidity();
736 if ((mbrState == invalid) || (mbrState == mbr))
737 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400738 break;
739 case use_new:
740 ClearGPTData();
741 protectiveMBR.MakeProtectiveMBR();
742 break;
srs56943c0af382010-01-15 19:19:18 -0500743 case use_abort:
744 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400745 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500746 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400747 } // switch
748
srs569455d92612010-03-07 22:16:07 -0500749 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500750 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500751 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400752 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400753 } else {
754 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400755 } // if/else
756 return (allOK);
757} // GPTData::LoadPartitions()
758
759// Loads the GPT, as much as possible. Returns 1 if this seems to have
760// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500761int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500762 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400763
srs5694cb76c672010-02-11 22:22:22 -0500764 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400765
srs5694cb76c672010-02-11 22:22:22 -0500766 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
767 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
768 } else {
srs569408bb0da2010-02-19 17:19:55 -0500769 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
770 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500771 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
772 << "secondary header from the last sector of the disk! You should use 'v' to\n"
773 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
774 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500775 } // if/else
776 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400777 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400778
779 // Return valid headers code: 0 = both headers bad; 1 = main header
780 // good, backup bad; 2 = backup header good, main header bad;
781 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400782 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400783 validHeaders = CheckHeaderValidity();
784
785 // Read partitions (from primary array)
786 if (validHeaders > 0) { // if at least one header is OK....
787 // GPT appears to be valid....
788 state = gpt_valid;
789
790 // We're calling the GPT valid, but there's a possibility that one
791 // of the two headers is corrupt. If so, use the one that seems to
792 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500793 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500794 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
795 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400796 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500797 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400798 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500799 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500800 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
801 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500802 RebuildMainHeader();
803 state = gpt_corrupt;
804 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400805 } // if/else/if
806
srs5694546a9c72010-01-26 16:00:26 -0500807 // Figure out which partition table to load....
808 // Load the main partition table, since either its header's CRC is OK or the
809 // backup header's CRC is not OK....
810 if (mainCrcOk || !secondCrcOk) {
811 if (LoadMainTable() == 0)
812 allOK = 0;
813 } else { // bad main header CRC and backup header CRC is OK
814 state = gpt_corrupt;
815 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500816 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500817 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500818 } else { // backup table bad, bad main header CRC, but try main table in desperation....
819 if (LoadMainTable() == 0) {
820 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500821 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500822 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500823 } // if
824 } // if/else (LoadSecondTableAsMain())
825 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400826
srs5694cb76c672010-02-11 22:22:22 -0500827 if (loadedTable == 1)
828 secondPartsCrcOk = CheckTable(&secondHeader);
829 else if (loadedTable == 2)
830 mainPartsCrcOk = CheckTable(&mainHeader);
831 else
832 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400833
srs5694546a9c72010-01-26 16:00:26 -0500834 // Problem with main partition table; if backup is OK, use it instead....
835 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
836 state = gpt_corrupt;
837 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500838 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500839 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
840 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500841 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500842
srs5694e4ac11e2009-08-31 10:13:04 -0400843 // Check for valid CRCs and warn if there are problems
844 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
845 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500846 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400847 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500848 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400849 } else {
850 state = gpt_invalid;
851 } // if/else
852 return allOK;
853} // GPTData::ForceLoadGPTData()
854
srs5694247657a2009-11-26 18:36:12 -0500855// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400856// main GPT header in memory MUST be valid for this call to do anything
857// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500858// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400859int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500860 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400861} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400862
863// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500864// table. Used in repair functions, and when starting up if the main
865// partition table is damaged.
866// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
867int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500868 return LoadPartitionTable(secondHeader, myDisk);
869} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400870
srs5694cb76c672010-02-11 22:22:22 -0500871// Load a single GPT header (main or backup) from the specified disk device and
872// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
873// value appropriately.
874// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
875// failure.
876int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
877 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500878 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500879
880 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500881 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500882 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
883 allOK = 0;
884 } // if
srs5694cb76c672010-02-11 22:22:22 -0500885
srs56941c6f8b02010-02-21 11:09:20 -0500886 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500887 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500888 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500889 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400890 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500891
srs56940283dae2010-04-28 16:44:34 -0400892 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500893 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500894 }
srs56941c6f8b02010-02-21 11:09:20 -0500895
896 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500897 return allOK;
898} // GPTData::LoadHeader
899
900// Load a partition table (either main or secondary) from the specified disk,
901// using header as a reference for what to load. If sector != 0 (the default
902// is 0), loads from the specified sector; otherwise loads from the sector
903// indicated in header.
904// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
905int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
906 uint32_t sizeOfParts, newCRC;
907 int retval;
908
909 if (disk.OpenForRead()) {
910 if (sector == 0) {
911 retval = disk.Seek(header.partitionEntriesLBA);
912 } else {
913 retval = disk.Seek(sector);
914 } // if/else
srs569455d92612010-03-07 22:16:07 -0500915 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500916 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500917 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500918 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
919 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500920 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500921 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500922 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400923 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500924 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400925 if (IsLittleEndian() == 0)
926 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500927 if (!mainPartsCrcOk) {
928 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400929 } // if
930 } else {
srs5694cb76c672010-02-11 22:22:22 -0500931 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400932 } // if/else
933 } else {
srs5694fed16d02010-01-27 23:03:40 -0500934 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500935 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500936 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400937 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500938 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500939} // GPTData::LoadPartitionsTable()
940
941// Check the partition table pointed to by header, but don't keep it
942// around.
srs5694a17fe692011-09-10 20:30:20 -0400943// Returns 1 if the CRC is OK & this table matches the one already in memory,
944// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500945int GPTData::CheckTable(struct GPTHeader *header) {
946 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400947 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400948 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400949 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500950
srs56940283dae2010-04-28 16:44:34 -0400951 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500952 // its CRC and store the results, then discard this temporary
953 // storage, since we don't use it in any but recovery operations
954 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400955 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400956 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -0400957 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -0400958 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
959 exit(1);
960 } // if
srs5694a17fe692011-09-10 20:30:20 -0400961 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400962 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500963 } else {
srs5694d1b11e82011-09-18 21:12:28 -0400964 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -0400965 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -0400966 if (header == &mainHeader)
967 otherHeader = &secondHeader;
968 else
969 otherHeader = &mainHeader;
970 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -0400971 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
972 << "on the recovery & transformation menu to examine the two tables.\n\n";
973 allOK = 0;
974 } // if
srs5694cb76c672010-02-11 22:22:22 -0500975 } // if/else
srs5694a17fe692011-09-10 20:30:20 -0400976 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -0500977 } // if
srs5694a17fe692011-09-10 20:30:20 -0400978 return allOK;
srs5694cb76c672010-02-11 22:22:22 -0500979} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400980
srs56944307ef22012-05-30 12:30:48 -0400981// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
982// header later on the disk without asking for permission, if necessary, and
983// doesn't confirm the operation before writing. If quiet==0, asks permission
984// before moving the second header and asks for final confirmation of any
985// write.
srs5694a17fe692011-09-10 20:30:20 -0400986// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -0500987int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -0400988 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -0500989 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400990
srs5694e7b4ff92009-08-18 13:16:10 -0400991 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500992
993 // This test should only fail on read-only disks....
994 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500995 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500996 allOK = 0;
997 } // if
998
srs569464cbd172011-03-01 22:03:54 -0500999 // Check that disk is really big enough to handle the second header...
1000 if (mainHeader.backupLBA >= diskSize) {
1001 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1002 << "header, but other problems may occur!\n";
1003 MoveSecondHeaderToEnd();
1004 } // if
1005
srs5694e7b4ff92009-08-18 13:16:10 -04001006 // Is there enough space to hold the GPT headers and partition tables,
1007 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001008 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001009 allOK = 0;
1010 } // if
1011
srs5694247657a2009-11-26 18:36:12 -05001012 // Check that second header is properly placed. Warn and ask if this should
1013 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001014 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1015 if (quiet == 0) {
1016 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1017 << "correct this problem? ";
1018 if (GetYN() == 'Y') {
1019 MoveSecondHeaderToEnd();
1020 cout << "Have moved second header and partition table to correct location.\n";
1021 } else {
1022 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1023 } // if correction requested
1024 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001025 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001026 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001027 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001028
srs5694d8eed462012-12-15 01:55:21 -05001029 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1030 if (quiet == 0) {
1031 cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1032 << "this problem? ";
1033 if (GetYN() == 'Y') {
1034 MoveSecondHeaderToEnd();
1035 cout << "Have adjusted the second header and last usable sector value.\n";
1036 } else {
1037 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1038 } // if correction requested
1039 } else { // go ahead and do correction automatically
1040 MoveSecondHeaderToEnd();
1041 } // if/else quiet
1042 } // if
1043
srs569455d92612010-03-07 22:16:07 -05001044 // Check for overlapping or insane partitions....
1045 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001046 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001047 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001048 } // if
1049
1050 // Check for mismatched MBR and GPT data, but let it pass if found
1051 // (function displays warning message)
1052 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001053
1054 RecomputeCRCs();
1055
srs5694ba00fed2010-01-12 18:18:36 -05001056 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001057 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001058 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001059 answer = GetYN();
1060 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001061 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001062 } else {
1063 allOK = 0;
1064 } // if/else
1065 } // if
1066
1067 // Do it!
1068 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001069 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001070 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001071 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001072 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001073 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1074 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001075 syncIt = 0;
1076 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001077
1078 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001079 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1080
1081 // Now write the main partition tables...
1082 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1083
1084 // Now write the main GPT header...
1085 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1086
1087 // To top it off, write the protective MBR...
1088 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001089
1090 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001091 // Note: Done even if some write operations failed, but not if all of them failed.
1092 // Done this way because I've received one problem report from a user one whose
1093 // system the MBR write failed but everything else was OK (on a GPT disk under
1094 // Windows), and the failure to sync therefore caused Windows to restore the
1095 // original partition table from its cache. OTOH, such restoration might be
1096 // desirable if the error occurs later; but that seems unlikely unless the initial
1097 // write fails....
1098 if (syncIt)
srs5694546a9c72010-01-26 16:00:26 -05001099 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001100
1101 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001102 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001103 } else {
srs5694fed16d02010-01-27 23:03:40 -05001104 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001105 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001106 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001107
srs5694546a9c72010-01-26 16:00:26 -05001108 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001109 } else {
srs56945a608532011-03-17 13:53:01 -04001110 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001111 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001112 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001113 } // if/else
1114 } else {
srs5694fed16d02010-01-27 23:03:40 -05001115 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001116 } // if
1117
1118 return (allOK);
1119} // GPTData::SaveGPTData()
1120
1121// Save GPT data to a backup file. This function does much less error
1122// checking than SaveGPTData(). It can therefore preserve many types of
1123// corruption for later analysis; however, it preserves only the MBR,
1124// the main GPT header, the backup GPT header, and the main partition
1125// table; it discards the backup partition table, since it should be
1126// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001127int GPTData::SaveGPTBackup(const string & filename) {
1128 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001129 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001130
srs5694546a9c72010-01-26 16:00:26 -05001131 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001132 // Recomputing the CRCs is likely to alter them, which could be bad
1133 // if the intent is to save a potentially bad GPT for later analysis;
1134 // but if we don't do this, we get bogus errors when we load the
1135 // backup. I'm favoring misses over false alarms....
1136 RecomputeCRCs();
1137
srs5694546a9c72010-01-26 16:00:26 -05001138 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001139 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001140
srs5694cb76c672010-02-11 22:22:22 -05001141 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001142 // MBR write closed disk, so re-open and seek to end....
1143 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001144 allOK = SaveHeader(&mainHeader, backupFile, 1);
1145 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001146
srs5694e7b4ff92009-08-18 13:16:10 -04001147 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001148 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001149
srs5694cb76c672010-02-11 22:22:22 -05001150 if (allOK)
1151 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001152
1153 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001154 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001155 } else {
srs5694fed16d02010-01-27 23:03:40 -05001156 cerr << "Warning! An error was reported when writing the backup file.\n"
1157 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001158 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001159 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001160 } else {
srs56945a608532011-03-17 13:53:01 -04001161 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001162 allOK = 0;
1163 } // if/else
1164 return allOK;
1165} // GPTData::SaveGPTBackup()
1166
srs5694cb76c672010-02-11 22:22:22 -05001167// Write a GPT header (main or backup) to the specified sector. Used by both
1168// the SaveGPTData() and SaveGPTBackup() functions.
1169// Should be passed an architecture-appropriate header (DO NOT call
1170// ReverseHeaderBytes() on the header before calling this function)
1171// Returns 1 on success, 0 on failure
1172int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1173 int littleEndian, allOK = 1;
1174
1175 littleEndian = IsLittleEndian();
1176 if (!littleEndian)
1177 ReverseHeaderBytes(header);
1178 if (disk.Seek(sector)) {
1179 if (disk.Write(header, 512) == -1)
1180 allOK = 0;
1181 } else allOK = 0; // if (disk.Seek()...)
1182 if (!littleEndian)
1183 ReverseHeaderBytes(header);
1184 return allOK;
1185} // GPTData::SaveHeader()
1186
1187// Save the partitions to the specified sector. Used by both the SaveGPTData()
1188// and SaveGPTBackup() functions.
1189// Should be passed an architecture-appropriate header (DO NOT call
1190// ReverseHeaderBytes() on the header before calling this function)
1191// Returns 1 on success, 0 on failure
1192int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1193 int littleEndian, allOK = 1;
1194
1195 littleEndian = IsLittleEndian();
1196 if (disk.Seek(sector)) {
1197 if (!littleEndian)
1198 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001199 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001200 allOK = 0;
1201 if (!littleEndian)
1202 ReversePartitionBytes();
1203 } else allOK = 0; // if (myDisk.Seek()...)
1204 return allOK;
1205} // GPTData::SavePartitionTable()
1206
srs5694e7b4ff92009-08-18 13:16:10 -04001207// Load GPT data from a backup file created by SaveGPTBackup(). This function
1208// does minimal error checking. It returns 1 if it completed successfully,
1209// 0 if there was a problem. In the latter case, it creates a new empty
1210// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001211int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001212 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001213 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001214 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001215
srs5694546a9c72010-01-26 16:00:26 -05001216 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001217 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001218 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001219 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001220
srs5694cb76c672010-02-11 22:22:22 -05001221 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001222
srs5694cb76c672010-02-11 22:22:22 -05001223 // Check backup file size and rebuild second header if file is right
1224 // size to be direct dd copy of MBR, main header, and main partition
1225 // table; if other size, treat it like a GPT fdisk-generated backup
1226 // file
1227 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1228 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1229 if (shortBackup) {
1230 RebuildSecondHeader();
1231 secondCrcOk = mainCrcOk;
1232 } else {
1233 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1234 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001235
srs5694e7b4ff92009-08-18 13:16:10 -04001236 // Return valid headers code: 0 = both headers bad; 1 = main header
1237 // good, backup bad; 2 = backup header good, main header bad;
1238 // 3 = both headers good. Note these codes refer to valid GPT
1239 // signatures and version numbers; more subtle problems will elude
1240 // this check!
1241 if ((val = CheckHeaderValidity()) > 0) {
1242 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001243 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001244 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001245 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001246 } // if/else
1247
srs5694e7b4ff92009-08-18 13:16:10 -04001248 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1250 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001251 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001252 } // if
1253
srs5694cb76c672010-02-11 22:22:22 -05001254 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1255 cerr << "Warning! Read error " << errno
1256 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001257 } else {
1258 allOK = 0;
1259 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001260 // Something went badly wrong, so blank out partitions
1261 if (allOK == 0) {
1262 cerr << "Improper backup file! Clearing all partition data!\n";
1263 ClearGPTData();
1264 protectiveMBR.MakeProtectiveMBR();
1265 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001266 } else {
1267 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001268 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001269 } // if/else
1270
srs5694e7b4ff92009-08-18 13:16:10 -04001271 return allOK;
1272} // GPTData::LoadGPTBackup()
1273
srs569408bb0da2010-02-19 17:19:55 -05001274int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001275 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001276} // GPTData::SaveMBR()
1277
1278// This function destroys the on-disk GPT structures, but NOT the on-disk
1279// MBR.
1280// Returns 1 if the operation succeeds, 0 if not.
1281int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001282 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001283 uint8_t blankSector[512];
1284 uint8_t* emptyTable;
1285
srs569401f7f082011-03-15 23:53:31 -04001286 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001287
1288 if (myDisk.OpenForWrite()) {
1289 if (!myDisk.Seek(mainHeader.currentLBA))
1290 allOK = 0;
1291 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1292 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1293 allOK = 0;
1294 } // if
1295 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1296 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001297 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001298 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001299 if (emptyTable == NULL) {
srs5694a17fe692011-09-10 20:30:20 -04001300 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
srs56946aae2a92011-06-10 01:16:51 -04001301 exit(1);
1302 } // if
srs569401f7f082011-03-15 23:53:31 -04001303 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001304 if (allOK) {
1305 sum = myDisk.Write(emptyTable, tableSize);
1306 if (sum != tableSize) {
1307 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1308 allOK = 0;
1309 } // if write failed
1310 } // if
1311 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1312 allOK = 0;
1313 if (allOK) {
1314 sum = myDisk.Write(emptyTable, tableSize);
1315 if (sum != tableSize) {
1316 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1317 << errno << "\n";
1318 allOK = 0;
1319 } // if wrong size written
1320 } // if
1321 if (!myDisk.Seek(secondHeader.currentLBA))
1322 allOK = 0;
1323 if (allOK) {
1324 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1325 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1326 allOK = 0;
1327 } // if
1328 } // if
1329 myDisk.DiskSync();
1330 myDisk.Close();
1331 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1332 << "other utilities.\n";
1333 delete[] emptyTable;
1334 } else {
srs56945a608532011-03-17 13:53:01 -04001335 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001336 } // if/else (fd != -1)
1337 return (allOK);
1338} // GPTDataTextUI::DestroyGPT()
1339
1340// Wipe MBR data from the disk (zero it out completely)
1341// Returns 1 on success, 0 on failure.
1342int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001343 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001344 uint8_t blankSector[512];
1345
srs569401f7f082011-03-15 23:53:31 -04001346 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001347
srs569401f7f082011-03-15 23:53:31 -04001348 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1349
srs569408bb0da2010-02-19 17:19:55 -05001350 if (!allOK)
1351 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1352 return allOK;
1353} // GPTData::DestroyMBR(void)
1354
srs5694e4ac11e2009-08-31 10:13:04 -04001355// Tell user whether Apple Partition Map (APM) was discovered....
1356void GPTData::ShowAPMState(void) {
1357 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001358 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001359 else
srs5694fed16d02010-01-27 23:03:40 -05001360 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001361} // GPTData::ShowAPMState()
1362
1363// Tell user about the state of the GPT data....
1364void GPTData::ShowGPTState(void) {
1365 switch (state) {
1366 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001367 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001368 break;
1369 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001370 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001371 break;
1372 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001373 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001374 break;
1375 default:
srs5694fed16d02010-01-27 23:03:40 -05001376 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001377 break;
1378 } // switch
1379} // GPTData::ShowGPTState()
1380
1381// Display the basic GPT data
1382void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001383 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001384 uint64_t temp, totalFree;
1385
srs5694fed16d02010-01-27 23:03:40 -05001386 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001387 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001388 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001389 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001390 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001391 cout << "First usable sector is " << mainHeader.firstUsableLBA
1392 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001393 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001394 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001395 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001396 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001397 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001398 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001399 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001400 } // for
1401} // GPTData::DisplayGPTData()
1402
srs5694e4ac11e2009-08-31 10:13:04 -04001403// Show detailed information on the specified partition
1404void GPTData::ShowPartDetails(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -04001405 if (!IsFreePartNum(partNum)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001406 partitions[partNum].ShowDetails(blockSize);
1407 } else {
srs5694fed16d02010-01-27 23:03:40 -05001408 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001409 } // if
1410} // GPTData::ShowPartDetails()
1411
srs5694e4ac11e2009-08-31 10:13:04 -04001412/**************************************************************************
1413 * *
1414 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1415 * (some of these functions may require user interaction) *
1416 * *
1417 **************************************************************************/
1418
srs569408bb0da2010-02-19 17:19:55 -05001419// Examines the MBR & GPT data to determine which set of data to use: the
1420// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1421// a new set of partitions (use_new). A return value of use_abort indicates
1422// that this function couldn't determine what to do. Overriding functions
1423// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001424WhichToUse GPTData::UseWhichPartitions(void) {
1425 WhichToUse which = use_new;
1426 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001427
1428 mbrState = protectiveMBR.GetValidity();
1429
1430 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001431 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001432 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1433 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001434 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001435 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1436 << "typing 'q' if you don't want to convert your MBR partitions\n"
1437 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001438 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001439 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001440 which = use_mbr;
1441 } // if
1442
1443 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001444 cout << "\n**********************************************************************\n"
1445 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1446 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001447 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001448 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001449 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1450 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001451 } // if
srs5694fed16d02010-01-27 23:03:40 -05001452 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001453 which = use_bsd;
1454 } // if
1455
1456 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001457 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001458 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001459 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001460 } // if
1461 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001462 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001463 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001464 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001465 } // if
1466 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001467 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001468 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001469 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001470 } // if
1471 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001472 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001473 } // if
1474
srs5694e4ac11e2009-08-31 10:13:04 -04001475 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001476 if (mbrState == gpt) {
1477 cout << "\a\a****************************************************************************\n"
1478 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1479 << "verification and recovery are STRONGLY recommended.\n"
1480 << "****************************************************************************\n";
1481 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001482 } else {
srs569408bb0da2010-02-19 17:19:55 -05001483 which = use_abort;
1484 } // if/else MBR says disk is GPT
1485 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001486
1487 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001488 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001489
1490 return which;
1491} // UseWhichPartitions()
1492
srs569408bb0da2010-02-19 17:19:55 -05001493// Convert MBR partition table into GPT form.
1494void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001495 int i, numToConvert;
1496 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001497
1498 // Clear out old data & prepare basics....
1499 ClearGPTData();
1500
1501 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001502 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001503 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001504 else
srs56940283dae2010-04-28 16:44:34 -04001505 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001506
1507 for (i = 0; i < numToConvert; i++) {
1508 origType = protectiveMBR.GetType(i);
1509 // don't waste CPU time trying to convert extended, hybrid protective, or
1510 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001511 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001512 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001513 partitions[i] = protectiveMBR.AsGPT(i);
1514 } // for
1515
1516 // Convert MBR into protective MBR
1517 protectiveMBR.MakeProtectiveMBR();
1518
1519 // Record that all original CRCs were OK so as not to raise flags
1520 // when doing a disk verification
1521 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001522} // GPTData::XFormPartitions()
1523
1524// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001525// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001526// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001527int GPTData::XFormDisklabel(uint32_t partNum) {
1528 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001529 int goOn = 1, numDone = 0;
1530 BSDData disklabel;
1531
srs569408bb0da2010-02-19 17:19:55 -05001532 if (GetPartRange(&low, &high) == 0) {
1533 goOn = 0;
1534 cout << "No partitions!\n";
1535 } // if
1536 if (partNum > high) {
1537 goOn = 0;
1538 cout << "Specified partition is invalid!\n";
1539 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001540
srs569408bb0da2010-02-19 17:19:55 -05001541 // If all is OK, read the disklabel and convert it.
1542 if (goOn) {
1543 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1544 partitions[partNum].GetLastLBA());
1545 if ((goOn) && (disklabel.IsDisklabel())) {
1546 numDone = XFormDisklabel(&disklabel);
1547 if (numDone == 1)
1548 cout << "Converted 1 BSD partition.\n";
1549 else
1550 cout << "Converted " << numDone << " BSD partitions.\n";
1551 } else {
1552 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1553 } // if/else
1554 } // if
1555 if (numDone > 0) { // converted partitions; delete carrier
1556 partitions[partNum].BlankPartition();
1557 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001558 return numDone;
srs569455d92612010-03-07 22:16:07 -05001559} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001560
1561// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001562int GPTData::XFormDisklabel(BSDData* disklabel) {
1563 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001564
srs569408bb0da2010-02-19 17:19:55 -05001565 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001566 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001567 partNum = FindFirstFreePart();
1568 if (partNum >= 0) {
1569 partitions[partNum] = disklabel->AsGPT(i);
1570 if (partitions[partNum].IsUsed())
1571 numDone++;
1572 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001573 } // for
srs569408bb0da2010-02-19 17:19:55 -05001574 if (partNum == -1)
1575 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001576 } // if
1577
1578 // Record that all original CRCs were OK so as not to raise flags
1579 // when doing a disk verification
1580 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1581
1582 return numDone;
1583} // GPTData::XFormDisklabel(BSDData* disklabel)
1584
srs569408bb0da2010-02-19 17:19:55 -05001585// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1586// partition has the active/bootable flag UNset and uses the GPT fdisk
1587// type code divided by 0x0100 as the MBR type code.
1588// Returns 1 if operation was 100% successful, 0 if there were ANY
1589// problems.
srs5694978041c2009-09-21 20:51:47 -04001590int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001591 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001592
srs5694978041c2009-09-21 20:51:47 -04001593 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001594 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001595 allOK = 0;
1596 } // if
srs56940283dae2010-04-28 16:44:34 -04001597 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001598 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001599 allOK = 0;
1600 } // if
1601 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001602 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001603 allOK = 0;
1604 } // if
1605 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1606 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1607 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001608 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1609 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001610 } // if
srs5694978041c2009-09-21 20:51:47 -04001611 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001612 (uint32_t) partitions[gptPart].GetLengthLBA(),
1613 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001614 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001615 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1616 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1617 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001618 allOK = 0;
1619 } // if/else
1620 return allOK;
1621} // GPTData::OnePartToMBR()
1622
srs5694e4ac11e2009-08-31 10:13:04 -04001623
1624/**********************************************************************
1625 * *
1626 * Functions that adjust GPT data structures WITHOUT user interaction *
1627 * (they may display information for the user's benefit, though) *
1628 * *
1629 **********************************************************************/
1630
1631// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001632// necessary, copies data if it already exists. If fillGPTSectors is 1
1633// (the default), rounds numEntries to fill all the sectors necessary to
1634// hold the GPT.
1635// Returns 1 if all goes well, 0 if an error is encountered.
1636int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001637 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001638 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001639 int allOK = 1;
1640
1641 // First, adjust numEntries upward, if necessary, to get a number
1642 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001643 entriesPerSector = blockSize / GPT_SIZE;
1644 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001645 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001646 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001647 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001648 } // if
1649
srs5694247657a2009-11-26 18:36:12 -05001650 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001651 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001652 // partition table, which causes problems when loading data from a RAID
1653 // array that's been expanded because this function is called when loading
1654 // data.
srs56940283dae2010-04-28 16:44:34 -04001655 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001656 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001657 if (newParts != NULL) {
1658 if (partitions != NULL) { // existing partitions; copy them over
1659 GetPartRange(&i, &high);
1660 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001661 cout << "The highest-numbered partition is " << high + 1
1662 << ", which is greater than the requested\n"
1663 << "partition table size of " << numEntries
1664 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001665 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001666 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001667 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001668 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001669 copyNum = numEntries;
1670 else
srs56940283dae2010-04-28 16:44:34 -04001671 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001672 for (i = 0; i < copyNum; i++) {
1673 newParts[i] = partitions[i];
1674 } // for
srs569401f7f082011-03-15 23:53:31 -04001675 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001676 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001677 } // if
1678 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001679 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001680 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001681 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001682 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001683 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1684 MoveSecondHeaderToEnd();
1685 if (diskSize > 0)
1686 CheckGPTSize();
1687 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001688 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001689 allOK = 0;
1690 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001691 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001692 mainHeader.numParts = numParts;
1693 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001694 return (allOK);
1695} // GPTData::SetGPTSize()
1696
1697// Blank the partition array
1698void GPTData::BlankPartitions(void) {
1699 uint32_t i;
1700
srs56940283dae2010-04-28 16:44:34 -04001701 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001702 partitions[i].BlankPartition();
1703 } // for
1704} // GPTData::BlankPartitions()
1705
srs5694ba00fed2010-01-12 18:18:36 -05001706// Delete a partition by number. Returns 1 if successful,
1707// 0 if there was a problem. Returns 1 if partition was in
1708// range, 0 if it was out of range.
1709int GPTData::DeletePartition(uint32_t partNum) {
1710 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001711 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001712
srs56940283dae2010-04-28 16:44:34 -04001713 numUsedParts = GetPartRange(&low, &high);
1714 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001715 // In case there's a protective MBR, look for & delete matching
1716 // MBR partition....
1717 startSector = partitions[partNum].GetFirstLBA();
1718 length = partitions[partNum].GetLengthLBA();
1719 protectiveMBR.DeleteByLocation(startSector, length);
1720
1721 // Now delete the GPT partition
1722 partitions[partNum].BlankPartition();
1723 } else {
srs5694fed16d02010-01-27 23:03:40 -05001724 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001725 retval = 0;
1726 } // if/else
1727 return retval;
1728} // GPTData::DeletePartition(uint32_t partNum)
1729
srs569408bb0da2010-02-19 17:19:55 -05001730// Non-interactively create a partition.
1731// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001732uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001733 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001734 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001735
1736 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001737 if (Align(&startSector)) {
1738 cout << "Information: Moved requested sector from " << origSector << " to "
1739 << startSector << " in\norder to align on " << sectorAlignment
1740 << "-sector boundaries.\n";
1741 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001742 if (IsFree(startSector) && (startSector <= endSector)) {
1743 if (FindLastInFree(startSector) >= endSector) {
1744 partitions[partNum].SetFirstLBA(startSector);
1745 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001746 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001747 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001748 } else retval = 0; // if free space until endSector
1749 } else retval = 0; // if startSector is free
1750 } else retval = 0; // if legal partition number
1751 return retval;
1752} // GPTData::CreatePartition(partNum, startSector, endSector)
1753
srs5694e4ac11e2009-08-31 10:13:04 -04001754// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001755// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001756void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001757 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001758 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001759} // GPTData::SortGPT()
1760
srs569408bb0da2010-02-19 17:19:55 -05001761// Swap the contents of two partitions.
1762// Returns 1 if successful, 0 if either partition is out of range
1763// (that is, not a legal number; either or both can be empty).
1764// Note that if partNum1 = partNum2 and this number is in range,
1765// it will be considered successful.
1766int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1767 GPTPart temp;
1768 int allOK = 1;
1769
srs56940283dae2010-04-28 16:44:34 -04001770 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001771 if (partNum1 != partNum2) {
1772 temp = partitions[partNum1];
1773 partitions[partNum1] = partitions[partNum2];
1774 partitions[partNum2] = temp;
1775 } // if
1776 } else allOK = 0; // partition numbers are valid
1777 return allOK;
1778} // GPTData::SwapPartitions()
1779
srs5694e4ac11e2009-08-31 10:13:04 -04001780// Set up data structures for entirely new set of partitions on the
1781// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001782// Note that this function does NOT clear the protectiveMBR data
1783// structure, since it may hold the original MBR partitions if the
1784// program was launched on an MBR disk, and those may need to be
1785// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001786int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001787 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001788
1789 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001790 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001791 partitions = NULL;
1792 SetGPTSize(NUM_GPT_ENTRIES);
1793
1794 // Now initialize a bunch of stuff that's static....
1795 mainHeader.signature = GPT_SIGNATURE;
1796 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001797 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001798 mainHeader.reserved = 0;
1799 mainHeader.currentLBA = UINT64_C(1);
1800 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1801 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1802 for (i = 0; i < GPT_RESERVED; i++) {
1803 mainHeader.reserved2[i] = '\0';
1804 } // for
srs56940873e9d2010-10-07 13:00:45 -04001805 if (blockSize > 0)
1806 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1807 else
1808 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001809
1810 // Now some semi-static items (computed based on end of disk)
1811 mainHeader.backupLBA = diskSize - UINT64_C(1);
1812 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1813
1814 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001815 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001816
1817 // Copy main header to backup header
1818 RebuildSecondHeader();
1819
1820 // Blank out the partitions array....
1821 BlankPartitions();
1822
1823 // Flag all CRCs as being OK....
1824 mainCrcOk = 1;
1825 secondCrcOk = 1;
1826 mainPartsCrcOk = 1;
1827 secondPartsCrcOk = 1;
1828
1829 return (goOn);
1830} // GPTData::ClearGPTData()
1831
srs5694247657a2009-11-26 18:36:12 -05001832// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001833// If the disk size has actually changed, this also adjusts the protective
1834// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001835// Used internally and called by the 'e' option on the recovery &
1836// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001837// to their arrays or to adjust data structures in restore operations
1838// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001839void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001840 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001841 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1842 if (protectiveMBR.GetValidity() == hybrid) {
1843 protectiveMBR.OptimizeEESize();
1844 RecomputeCHS();
1845 } // if
1846 if (protectiveMBR.GetValidity() == gpt)
1847 MakeProtectiveMBR();
1848 } // if
srs56948bb78762009-11-24 15:43:49 -05001849 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1850 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1851} // GPTData::FixSecondHeaderLocation()
1852
srs5694699941e2011-03-21 21:33:57 -04001853// Sets the partition's name to the specified UnicodeString without
1854// user interaction.
1855// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001856int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001857 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001858
srs5694699941e2011-03-21 21:33:57 -04001859 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001860 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001861 else
1862 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001863
1864 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001865} // GPTData::SetName
1866
1867// Set the disk GUID to the specified value. Note that the header CRCs must
1868// be recomputed after calling this function.
1869void GPTData::SetDiskGUID(GUIDData newGUID) {
1870 mainHeader.diskGUID = newGUID;
1871 secondHeader.diskGUID = newGUID;
1872} // SetDiskGUID()
1873
1874// Set the unique GUID of the specified partition. Returns 1 on
1875// successful completion, 0 if there were problems (invalid
1876// partition number).
1877int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1878 int retval = 0;
1879
srs56940283dae2010-04-28 16:44:34 -04001880 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001881 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001882 partitions[pn].SetUniqueGUID(theGUID);
1883 retval = 1;
1884 } // if
1885 } // if
1886 return retval;
1887} // GPTData::SetPartitionGUID()
1888
srs56949ba54212010-05-18 23:24:02 -04001889// Set new random GUIDs for the disk and all partitions. Intended to be used
1890// after disk cloning or similar operations that don't randomize the GUIDs.
1891void GPTData::RandomizeGUIDs(void) {
1892 uint32_t i;
1893
1894 mainHeader.diskGUID.Randomize();
1895 secondHeader.diskGUID = mainHeader.diskGUID;
1896 for (i = 0; i < numParts; i++)
1897 if (partitions[i].IsUsed())
1898 partitions[i].RandomizeUniqueGUID();
1899} // GPTData::RandomizeGUIDs()
1900
srs5694ba00fed2010-01-12 18:18:36 -05001901// Change partition type code non-interactively. Returns 1 if
1902// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001903int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1904 int retval = 1;
1905
1906 if (!IsFreePartNum(partNum)) {
1907 partitions[partNum].SetType(theGUID);
1908 } else retval = 0;
1909 return retval;
1910} // GPTData::ChangePartType()
1911
srs56949ba54212010-05-18 23:24:02 -04001912// Recompute the CHS values of all the MBR partitions. Used to reset
1913// CHS values that some BIOSes require, despite the fact that the
1914// resulting CHS values violate the GPT standard.
1915void GPTData::RecomputeCHS(void) {
1916 int i;
1917
1918 for (i = 0; i < 4; i++)
1919 protectiveMBR.RecomputeCHS(i);
1920} // GPTData::RecomputeCHS()
1921
srs56941d1448a2009-12-31 21:20:19 -05001922// Adjust sector number so that it falls on a sector boundary that's a
1923// multiple of sectorAlignment. This is done to improve the performance
1924// of Western Digital Advanced Format disks and disks with similar
1925// technology from other companies, which use 4096-byte sectors
1926// internally although they translate to 512-byte sectors for the
1927// benefit of the OS. If partitions aren't properly aligned on these
1928// disks, some filesystem data structures can span multiple physical
1929// sectors, degrading performance. This function should be called
1930// only on the FIRST sector of the partition, not the last!
1931// This function returns 1 if the alignment was altered, 0 if it
1932// was unchanged.
1933int GPTData::Align(uint64_t* sector) {
1934 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001935 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001936
1937 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001938 earlier = (*sector / sectorAlignment) * sectorAlignment;
1939 later = earlier + (uint64_t) sectorAlignment;
1940
1941 // Check to see that every sector between the earlier one and the
1942 // requested one is clear, and that it's not too early....
1943 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001944 sectorOK = 1;
1945 testSector = earlier;
1946 do {
1947 sectorOK = IsFree(testSector++);
1948 } while ((sectorOK == 1) && (testSector < *sector));
1949 if (sectorOK == 1) {
1950 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04001951 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001952 } // if
1953 } // if firstUsableLBA check
1954
1955 // If couldn't move the sector earlier, try to move it later instead....
1956 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1957 sectorOK = 1;
1958 testSector = later;
1959 do {
1960 sectorOK = IsFree(testSector--);
1961 } while ((sectorOK == 1) && (testSector > *sector));
1962 if (sectorOK == 1) {
1963 *sector = later;
srs56945a081752010-09-24 20:39:41 -04001964 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05001965 } // if
1966 } // if
srs56941d1448a2009-12-31 21:20:19 -05001967 } // if
1968 return retval;
1969} // GPTData::Align()
1970
srs5694e4ac11e2009-08-31 10:13:04 -04001971/********************************************************
1972 * *
1973 * Functions that return data about GPT data structures *
1974 * (most of these are inline in gpt.h) *
1975 * *
1976 ********************************************************/
1977
1978// Find the low and high used partition numbers (numbered from 0).
1979// Return value is the number of partitions found. Note that the
1980// *low and *high values are both set to 0 when no partitions
1981// are found, as well as when a single partition in the first
1982// position exists. Thus, the return value is the only way to
1983// tell when no partitions exist.
1984int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1985 uint32_t i;
1986 int numFound = 0;
1987
srs56940283dae2010-04-28 16:44:34 -04001988 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001989 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04001990 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05001991 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04001992 *high = i; // since we're counting up, set the high value
1993 // Set the low value only if it's not yet found...
1994 if (*low == (numParts + 1)) *low = i;
1995 numFound++;
1996 } // if
1997 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04001998
1999 // Above will leave *low pointing to its "not found" value if no partitions
2000 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002001 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002002 *low = 0;
2003 return numFound;
2004} // GPTData::GetPartRange()
2005
srs569408bb0da2010-02-19 17:19:55 -05002006// Returns the value of the first free partition, or -1 if none is
2007// unused.
2008int GPTData::FindFirstFreePart(void) {
2009 int i = 0;
2010
2011 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002012 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002013 i++;
srs56940283dae2010-04-28 16:44:34 -04002014 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002015 i = -1;
2016 } else i = -1;
2017 return i;
2018} // GPTData::FindFirstFreePart()
2019
srs5694978041c2009-09-21 20:51:47 -04002020// Returns the number of defined partitions.
2021uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002022 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002023
srs56940283dae2010-04-28 16:44:34 -04002024 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002025 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002026 counted++;
2027 } // for
2028 return counted;
2029} // GPTData::CountParts()
2030
srs5694e4ac11e2009-08-31 10:13:04 -04002031/****************************************************
2032 * *
2033 * Functions that return data about disk free space *
2034 * *
2035 ****************************************************/
2036
2037// Find the first available block after the starting point; returns 0 if
2038// there are no available blocks left
2039uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2040 uint64_t first;
2041 uint32_t i;
2042 int firstMoved = 0;
2043
2044 // Begin from the specified starting point or from the first usable
2045 // LBA, whichever is greater...
2046 if (start < mainHeader.firstUsableLBA)
2047 first = mainHeader.firstUsableLBA;
2048 else
2049 first = start;
2050
2051 // ...now search through all partitions; if first is within an
2052 // existing partition, move it to the next sector after that
2053 // partition and repeat. If first was moved, set firstMoved
2054 // flag; repeat until firstMoved is not set, so as to catch
2055 // cases where partitions are out of sequential order....
2056 do {
2057 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002058 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002059 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002060 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002061 first = partitions[i].GetLastLBA() + 1;
2062 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002063 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002064 } // for
2065 } while (firstMoved == 1);
2066 if (first > mainHeader.lastUsableLBA)
2067 first = 0;
2068 return (first);
2069} // GPTData::FindFirstAvailable()
2070
2071// Finds the first available sector in the largest block of unallocated
2072// space on the disk. Returns 0 if there are no available blocks left
2073uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002074 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002075
2076 start = 0;
2077 do {
2078 firstBlock = FindFirstAvailable(start);
2079 if (firstBlock != UINT32_C(0)) { // something's free...
2080 lastBlock = FindLastInFree(firstBlock);
2081 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2082 if (segmentSize > selectedSize) {
2083 selectedSize = segmentSize;
2084 selectedSegment = firstBlock;
2085 } // if
2086 start = lastBlock + 1;
2087 } // if
2088 } while (firstBlock != 0);
2089 return selectedSegment;
2090} // GPTData::FindFirstInLargest()
2091
srs5694cb76c672010-02-11 22:22:22 -05002092// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002093// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002094uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002095 uint64_t last;
2096 uint32_t i;
2097 int lastMoved = 0;
2098
2099 // Start by assuming the last usable LBA is available....
2100 last = mainHeader.lastUsableLBA;
2101
2102 // ...now, similar to algorithm in FindFirstAvailable(), search
2103 // through all partitions, moving last when it's in an existing
2104 // partition. Set the lastMoved flag so we repeat to catch cases
2105 // where partitions are out of logical order.
2106 do {
2107 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002108 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002109 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002110 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002111 last = partitions[i].GetFirstLBA() - 1;
2112 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002113 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002114 } // for
2115 } while (lastMoved == 1);
2116 if (last < mainHeader.firstUsableLBA)
2117 last = 0;
2118 return (last);
2119} // GPTData::FindLastAvailable()
2120
2121// Find the last available block in the free space pointed to by start.
2122uint64_t GPTData::FindLastInFree(uint64_t start) {
2123 uint64_t nearestStart;
2124 uint32_t i;
2125
2126 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002127 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002128 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002129 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002130 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002131 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002132 } // for
2133 return (nearestStart);
2134} // GPTData::FindLastInFree()
2135
2136// Finds the total number of free blocks, the number of segments in which
2137// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002138uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002139 uint64_t start = UINT64_C(0); // starting point for each search
2140 uint64_t totalFound = UINT64_C(0); // running total
2141 uint64_t firstBlock; // first block in a segment
2142 uint64_t lastBlock; // last block in a segment
2143 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002144 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002145
2146 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002147 if (diskSize > 0) {
2148 do {
2149 firstBlock = FindFirstAvailable(start);
2150 if (firstBlock != UINT64_C(0)) { // something's free...
2151 lastBlock = FindLastInFree(firstBlock);
2152 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2153 if (segmentSize > *largestSegment) {
2154 *largestSegment = segmentSize;
2155 } // if
2156 totalFound += segmentSize;
2157 num++;
2158 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002159 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002160 } while (firstBlock != 0);
2161 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002162 *numSegments = num;
2163 return totalFound;
2164} // GPTData::FindFreeBlocks()
2165
srs569455d92612010-03-07 22:16:07 -05002166// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2167// If it's allocated, return the partition number to which it's allocated
2168// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2169// returned in partNum if the sector is in use by basic GPT data structures.)
2170int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002171 int isFree = 1;
2172 uint32_t i;
2173
srs56940283dae2010-04-28 16:44:34 -04002174 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002175 if ((sector >= partitions[i].GetFirstLBA()) &&
2176 (sector <= partitions[i].GetLastLBA())) {
2177 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002178 if (partNum != NULL)
2179 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002180 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002181 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002182 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002183 (sector > mainHeader.lastUsableLBA)) {
2184 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002185 if (partNum != NULL)
2186 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002187 } // if
2188 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002189} // GPTData::IsFree()
2190
srs5694815fb652011-03-18 12:35:56 -04002191// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002192int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002193 return ((partNum < numParts) && (partitions != NULL) &&
2194 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002195} // GPTData::IsFreePartNum()
2196
srs5694815fb652011-03-18 12:35:56 -04002197// Returns 1 if partNum is in use.
2198int GPTData::IsUsedPartNum(uint32_t partNum) {
2199 return ((partNum < numParts) && (partitions != NULL) &&
2200 (partitions[partNum].IsUsed()));
2201} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002202
2203/***********************************************************
2204 * *
2205 * Change how functions work or return information on them *
2206 * *
2207 ***********************************************************/
2208
2209// Set partition alignment value; partitions will begin on multiples of
2210// the specified value
2211void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002212 if (n > 0)
2213 sectorAlignment = n;
2214 else
2215 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002216} // GPTData::SetAlignment()
2217
2218// Compute sector alignment based on the current partitions (if any). Each
2219// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002220// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2221// sector size), but not by the previously-located alignment value, then the
2222// alignment value is adjusted down. If the computed alignment is less than 8
2223// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002224// is a safety measure for Advanced Format drives. If no partitions are
2225// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002226// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002227// drives are aligned to 2048-sector multiples but the program won't complain
2228// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002229// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002230// Returns the computed alignment value.
2231uint32_t GPTData::ComputeAlignment(void) {
2232 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002233 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002234
srs56940873e9d2010-10-07 13:00:45 -04002235 if (blockSize > 0)
2236 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2237 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002238 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002239 if (partitions[i].IsUsed()) {
2240 found = 0;
2241 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002242 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002243 if ((partitions[i].GetFirstLBA() % align) == 0) {
2244 found = 1;
2245 } else {
2246 exponent--;
2247 } // if/else
2248 } // while
2249 } // if
2250 } // for
srs56940873e9d2010-10-07 13:00:45 -04002251 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2252 align = MIN_AF_ALIGNMENT;
2253 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002254 return align;
2255} // GPTData::ComputeAlignment()
2256
srs5694e4ac11e2009-08-31 10:13:04 -04002257/********************************
2258 * *
2259 * Endianness support functions *
2260 * *
2261 ********************************/
2262
srs56942a9f5da2009-08-26 00:48:01 -04002263void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002264 ReverseBytes(&header->signature, 8);
2265 ReverseBytes(&header->revision, 4);
2266 ReverseBytes(&header->headerSize, 4);
2267 ReverseBytes(&header->headerCRC, 4);
2268 ReverseBytes(&header->reserved, 4);
2269 ReverseBytes(&header->currentLBA, 8);
2270 ReverseBytes(&header->backupLBA, 8);
2271 ReverseBytes(&header->firstUsableLBA, 8);
2272 ReverseBytes(&header->lastUsableLBA, 8);
2273 ReverseBytes(&header->partitionEntriesLBA, 8);
2274 ReverseBytes(&header->numParts, 4);
2275 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2276 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002277 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002278} // GPTData::ReverseHeaderBytes()
2279
srs56940283dae2010-04-28 16:44:34 -04002280// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002281void GPTData::ReversePartitionBytes() {
2282 uint32_t i;
2283
srs56940283dae2010-04-28 16:44:34 -04002284 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002285 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002286 } // for
2287} // GPTData::ReversePartitionBytes()
2288
srs56949ddc14b2010-08-22 22:44:42 -04002289// Validate partition number
2290bool GPTData::ValidPartNum (const uint32_t partNum) {
2291 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002292 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002293 return false;
2294 } // if
2295 return true;
2296} // GPTData::ValidPartNum
2297
srs56945a081752010-09-24 20:39:41 -04002298// Return a single partition for inspection (not modification!) by other
2299// functions.
2300const GPTPart & GPTData::operator[](uint32_t partNum) const {
2301 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002302 cerr << "Partition number out of range (" << partNum << " requested, but only "
2303 << numParts << " available)\n";
2304 exit(1);
2305 } // if
2306 if (partitions == NULL) {
2307 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2308 exit(1);
srs56945a081752010-09-24 20:39:41 -04002309 } // if
2310 return partitions[partNum];
2311} // operator[]
2312
2313// Return (not for modification!) the disk's GUID value
2314const GUIDData & GPTData::GetDiskGUID(void) const {
2315 return mainHeader.diskGUID;
2316} // GPTData::GetDiskGUID()
2317
srs56949ddc14b2010-08-22 22:44:42 -04002318// Manage attributes for a partition, based on commands passed to this function.
2319// (Function is non-interactive.)
2320// Returns 1 if a modification command succeeded, 0 if the command should not have
2321// modified data, and -1 if a modification command failed.
2322int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2323 int retval = 0;
2324 Attributes theAttr;
2325
2326 if (command == "show") {
2327 ShowAttributes(partNum);
2328 } else if (command == "get") {
2329 GetAttribute(partNum, bits);
2330 } else {
2331 theAttr = partitions[partNum].GetAttributes();
2332 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2333 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2334 retval = 1;
2335 } else {
2336 retval = -1;
2337 } // if/else
2338 } // if/elseif/else
2339
2340 return retval;
2341} // GPTData::ManageAttributes()
2342
2343// Show all attributes for a specified partition....
2344void GPTData::ShowAttributes(const uint32_t partNum) {
srs5694e69e6802012-01-20 22:37:12 -05002345 if (partitions[partNum].IsUsed())
2346 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002347} // GPTData::ShowAttributes
2348
2349// Show whether a single attribute bit is set (terse output)...
2350void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
srs56940873e9d2010-10-07 13:00:45 -04002351 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002352} // GPTData::GetAttribute
2353
2354
srs56942a9f5da2009-08-26 00:48:01 -04002355/******************************************
2356 * *
2357 * Additional non-class support functions *
2358 * *
2359 ******************************************/
2360
srs5694e7b4ff92009-08-18 13:16:10 -04002361// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2362// never fail these tests, but the struct types may fail depending on compile options.
2363// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2364// sizes.
2365int SizesOK(void) {
2366 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002367
2368 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002369 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002370 allOK = 0;
2371 } // if
2372 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002373 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002374 allOK = 0;
2375 } // if
2376 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002377 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002378 allOK = 0;
2379 } // if
2380 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002381 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002382 allOK = 0;
2383 } // if
2384 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002385 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002386 allOK = 0;
2387 } // if
srs5694978041c2009-09-21 20:51:47 -04002388 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002389 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002390 allOK = 0;
2391 } // if
2392 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002393 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002394 allOK = 0;
2395 } // if
srs5694221e0872009-08-29 15:00:31 -04002396 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002397 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002398 allOK = 0;
2399 } // if
srs56946699b012010-02-04 00:55:30 -05002400 if (sizeof(GUIDData) != 16) {
2401 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2402 allOK = 0;
2403 } // if
2404 if (sizeof(PartType) != 16) {
2405 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2406 allOK = 0;
2407 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002408 return (allOK);
2409} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002410