blob: 278f392528e1a8e7e43dc3477d1b06e0d61fe706 [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2 data. */
3
srs5694e4ac11e2009-08-31 10:13:04 -04004/* By Rod Smith, initial coding January to February, 2009 */
srs5694e7b4ff92009-08-18 13:16:10 -04005
Roderick W. Smithe3ee7332013-09-24 12:56:11 -04006/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070010#ifndef __STDC_CONSTANT_MACROS
srs5694e7b4ff92009-08-18 13:16:10 -040011#define __STDC_CONSTANT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070012#endif
srs5694e7b4ff92009-08-18 13:16:10 -040013
14#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040015#include <stdlib.h>
16#include <stdint.h>
17#include <fcntl.h>
18#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040019#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040020#include <time.h>
21#include <sys/stat.h>
22#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050023#include <iostream>
srs56949a46b042011-03-15 00:34:10 -040024#include <algorithm>
srs5694e7b4ff92009-08-18 13:16:10 -040025#include "crc32.h"
26#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040027#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040028#include "support.h"
29#include "parttypes.h"
30#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050031#include "diskio.h"
srs5694e7b4ff92009-08-18 13:16:10 -040032
33using namespace std;
34
srs56948f1b2d62010-05-23 13:07:19 -040035#ifdef __FreeBSD__
srs56949ba54212010-05-18 23:24:02 -040036#define log2(x) (log(x) / M_LN2)
37#endif // __FreeBSD__
38
srs56948f1b2d62010-05-23 13:07:19 -040039#ifdef _MSC_VER
40#define log2(x) (log((double) x) / log(2.0))
41#endif // Microsoft Visual C++
srs56949ba54212010-05-18 23:24:02 -040042
Roderick W. Smith1f7822e2014-03-28 23:54:21 -040043#ifdef EFI
44// in UEFI mode MMX registers are not yet available so using the
45// x86_64 ABI to move "double" values around is not an option.
46#ifdef log2
47#undef log2
48#endif
49#define log2(x) log2_32( x )
50static inline uint32_t log2_32(uint32_t v) {
51 int r = -1;
52 while (v >= 1) {
53 r++;
54 v >>= 1;
55 }
56 return r;
57}
58#endif
59
srs5694e7b4ff92009-08-18 13:16:10 -040060/****************************************
61 * *
62 * GPTData class and related structures *
63 * *
64 ****************************************/
65
srs5694e4ac11e2009-08-31 10:13:04 -040066// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040067GPTData::GPTData(void) {
68 blockSize = SECTOR_SIZE; // set a default
69 diskSize = 0;
70 partitions = NULL;
71 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050072 device = "";
srs56945d58fe02010-01-03 20:57:08 -050073 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040074 mainCrcOk = 0;
75 secondCrcOk = 0;
76 mainPartsCrcOk = 0;
77 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040078 apmFound = 0;
79 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -040080 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050081 beQuiet = 0;
82 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -050083 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040084 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040085 SetGPTSize(NUM_GPT_ENTRIES);
srs5694d1b11e82011-09-18 21:12:28 -040086 // Initialize CRC functions...
87 chksum_crc32gentab();
srs5694e7b4ff92009-08-18 13:16:10 -040088} // GPTData default constructor
89
90// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050091GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040092 blockSize = SECTOR_SIZE; // set a default
93 diskSize = 0;
94 partitions = NULL;
95 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050096 device = "";
srs56945d58fe02010-01-03 20:57:08 -050097 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040098 mainCrcOk = 0;
99 secondCrcOk = 0;
100 mainPartsCrcOk = 0;
101 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -0400102 apmFound = 0;
103 bsdFound = 0;
srs56940873e9d2010-10-07 13:00:45 -0400104 sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -0500105 beQuiet = 0;
106 whichWasUsed = use_new;
srs56941e093722010-01-05 00:14:19 -0500107 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -0400108 numParts = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400109 // Initialize CRC functions...
110 chksum_crc32gentab();
srs56943c0af382010-01-15 19:19:18 -0500111 if (!LoadPartitions(filename))
112 exit(2);
srs5694fed16d02010-01-27 23:03:40 -0500113} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -0400114
srs5694e4ac11e2009-08-31 10:13:04 -0400115// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -0400116GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500117 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -0400118} // GPTData destructor
119
srs569464cbd172011-03-01 22:03:54 -0500120// Assignment operator
121GPTData & GPTData::operator=(const GPTData & orig) {
122 uint32_t i;
123
124 mainHeader = orig.mainHeader;
125 numParts = orig.numParts;
126 secondHeader = orig.secondHeader;
127 protectiveMBR = orig.protectiveMBR;
128 device = orig.device;
129 blockSize = orig.blockSize;
130 diskSize = orig.diskSize;
131 state = orig.state;
132 justLooking = orig.justLooking;
133 mainCrcOk = orig.mainCrcOk;
134 secondCrcOk = orig.secondCrcOk;
135 mainPartsCrcOk = orig.mainPartsCrcOk;
136 secondPartsCrcOk = orig.secondPartsCrcOk;
137 apmFound = orig.apmFound;
138 bsdFound = orig.bsdFound;
139 sectorAlignment = orig.sectorAlignment;
140 beQuiet = orig.beQuiet;
141 whichWasUsed = orig.whichWasUsed;
142
143 myDisk.OpenForRead(orig.myDisk.GetName());
144
145 delete[] partitions;
srs569401f7f082011-03-15 23:53:31 -0400146 partitions = new GPTPart [numParts];
srs56946aae2a92011-06-10 01:16:51 -0400147 if (partitions == NULL) {
srs569464cbd172011-03-01 22:03:54 -0500148 cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
srs56946aae2a92011-06-10 01:16:51 -0400149 << "Terminating!\n";
150 exit(1);
151 } // if
152 for (i = 0; i < numParts; i++) {
153 partitions[i] = orig.partitions[i];
srs5694d1b11e82011-09-18 21:12:28 -0400154 } // for
155
srs569464cbd172011-03-01 22:03:54 -0500156 return *this;
157} // GPTData::operator=()
158
srs5694e4ac11e2009-08-31 10:13:04 -0400159/*********************************************************************
160 * *
161 * Begin functions that verify data, or that adjust the verification *
162 * information (compute CRCs, rebuild headers) *
163 * *
164 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -0400165
srs5694e4ac11e2009-08-31 10:13:04 -0400166// Perform detailed verification, reporting on any problems found, but
167// do *NOT* recover from these problems. Returns the total number of
168// problems identified.
169int GPTData::Verify(void) {
srs569464cbd172011-03-01 22:03:54 -0500170 int problems = 0, alignProbs = 0;
srs5694e321d442010-01-29 17:44:04 -0500171 uint32_t i, numSegments;
172 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400173
174 // First, check for CRC errors in the GPT data....
175 if (!mainCrcOk) {
176 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500177 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
178 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
179 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
180 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400181 } // if
182 if (!mainPartsCrcOk) {
183 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500184 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
185 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
186 << "transformation menu). This report may be a false alarm if you've already\n"
187 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400188 } // if
189 if (!secondCrcOk) {
190 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500191 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
192 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
193 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
194 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400195 } // if
196 if (!secondPartsCrcOk) {
197 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500198 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
199 << "be corrupt. This program will automatically create a new backup partition\n"
200 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400201 } // if
202
srs5694978041c2009-09-21 20:51:47 -0400203 // Now check that the main and backup headers both point to themselves....
204 if (mainHeader.currentLBA != 1) {
205 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500206 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
207 << "is being automatically corrected, but it may be a symptom of more serious\n"
208 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400209 mainHeader.currentLBA = 1;
210 } // if
211 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
212 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500213 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
214 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
215 << "option on the experts' menu to adjust the secondary header's and partition\n"
216 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400217 } // if
218
219 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400220 if (mainHeader.currentLBA != secondHeader.backupLBA) {
221 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500222 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
223 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
224 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400225 } // if
226 if (mainHeader.backupLBA != secondHeader.currentLBA) {
227 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500228 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
229 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
230 << secondHeader.currentLBA << ").\n"
231 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400232 } // if
233 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
234 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500235 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
236 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
237 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400238 } // if
239 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
240 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500241 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
242 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
243 << secondHeader.lastUsableLBA << ")\n"
244 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400245 } // if
srs56946699b012010-02-04 00:55:30 -0500246 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400247 problems++;
srs56945a081752010-09-24 20:39:41 -0400248 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
srs5694fed16d02010-01-27 23:03:40 -0500249 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56945a081752010-09-24 20:39:41 -0400250 << secondHeader.diskGUID << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500251 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
252 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400253 } // if
254 if (mainHeader.numParts != secondHeader.numParts) {
255 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500256 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
257 << ") doesn't\nmatch the backup GPT header's number of partitions ("
258 << secondHeader.numParts << ")\n"
259 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400260 } // if
261 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
262 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500263 cout << "\nProblem: main GPT header's size of partition entries ("
264 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
265 << "match the backup GPT header's size of partition entries ("
266 << secondHeader.sizeOfPartitionEntries << ")\n"
267 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
268 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400269 } // if
270
271 // Now check for a few other miscellaneous problems...
272 // Check that the disk size will hold the data...
srs569464cbd172011-03-01 22:03:54 -0500273 if (mainHeader.backupLBA >= diskSize) {
srs5694e4ac11e2009-08-31 10:13:04 -0400274 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500275 cout << "\nProblem: Disk is too small to hold all the data!\n"
276 << "(Disk size is " << diskSize << " sectors, needs to be "
srs569464cbd172011-03-01 22:03:54 -0500277 << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
srs5694fed16d02010-01-27 23:03:40 -0500278 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400279 } // if
280
srs5694d8eed462012-12-15 01:55:21 -0500281 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
282 problems++;
srs56940741fa22013-01-09 12:55:40 -0500283 cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
284 << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
285 << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
286 << "The 'e' option on the experts' menu will probably fix this problem\n";
srs5694d8eed462012-12-15 01:55:21 -0500287 }
288
srs5694e4ac11e2009-08-31 10:13:04 -0400289 // Check for overlapping partitions....
290 problems += FindOverlaps();
291
srs569455d92612010-03-07 22:16:07 -0500292 // Check for insane partitions (start after end, hugely big, etc.)
293 problems += FindInsanePartitions();
294
srs5694e4ac11e2009-08-31 10:13:04 -0400295 // Check for mismatched MBR and GPT partitions...
296 problems += FindHybridMismatches();
297
srs5694327129e2010-09-22 01:07:31 -0400298 // Check for MBR-specific problems....
299 problems += VerifyMBR();
300
Roderick W. Smith042f38a2013-08-31 17:40:15 -0400301 // Check for a 0xEE protective partition that's marked as active....
302 if (protectiveMBR.IsEEActive()) {
303 cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
304 << "technically a violation of the GPT specification, and can cause some EFIs to\n"
305 << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
306 << "computers. You can clear this flag by creating a fresh protective MBR using\n"
307 << "the 'n' option on the experts' menu.\n";
308 }
309
srs5694e4ac11e2009-08-31 10:13:04 -0400310 // Verify that partitions don't run into GPT data areas....
311 problems += CheckGPTSize();
312
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500313 if (!protectiveMBR.DoTheyFit()) {
314 cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
315 << "fresh protective or hybrid MBR is recommended.\n";
316 problems++;
317 }
318
srs56941d1448a2009-12-31 21:20:19 -0500319 // Check that partitions are aligned on proper boundaries (for WD Advanced
320 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400321 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500322 if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500323 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
324 << sectorAlignment << "-sector boundary. This may\nresult "
325 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs569464cbd172011-03-01 22:03:54 -0500326 alignProbs++;
srs56941d1448a2009-12-31 21:20:19 -0500327 } // if
328 } // for
srs569464cbd172011-03-01 22:03:54 -0500329 if (alignProbs > 0)
330 cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
331 << "for information on disk alignment.\n";
srs56941d1448a2009-12-31 21:20:19 -0500332
srs5694e4ac11e2009-08-31 10:13:04 -0400333 // Now compute available space, but only if no problems found, since
334 // problems could affect the results
335 if (problems == 0) {
336 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs569464cbd172011-03-01 22:03:54 -0500337 cout << "\nNo problems found. " << totalFree << " free sectors ("
srs569401f7f082011-03-15 23:53:31 -0400338 << BytesToIeee(totalFree, blockSize) << ") available in "
srs5694fed16d02010-01-27 23:03:40 -0500339 << numSegments << "\nsegments, the largest of which is "
srs569401f7f082011-03-15 23:53:31 -0400340 << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
srs56940283dae2010-04-28 16:44:34 -0400341 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400342 } else {
srs56940a697312010-01-28 21:10:52 -0500343 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400344 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400345
346 return (problems);
347} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400348
349// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400350// do, issues a warning but takes no action. Returns number of problems
351// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400352int GPTData::CheckGPTSize(void) {
353 uint64_t overlap, firstUsedBlock, lastUsedBlock;
354 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400355 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400356
357 // first, locate the first & last used blocks
358 firstUsedBlock = UINT64_MAX;
359 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400360 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500361 if (partitions[i].IsUsed()) {
srs5694706e5122012-01-21 13:47:24 -0500362 if (partitions[i].GetFirstLBA() < firstUsedBlock)
srs5694e69e6802012-01-20 22:37:12 -0500363 firstUsedBlock = partitions[i].GetFirstLBA();
364 if (partitions[i].GetLastLBA() > lastUsedBlock) {
365 lastUsedBlock = partitions[i].GetLastLBA();
366 } // if
367 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400368 } // for
369
370 // If the disk size is 0 (the default), then it means that various
371 // variables aren't yet set, so the below tests will be useless;
372 // therefore we should skip everything
373 if (diskSize != 0) {
374 if (mainHeader.firstUsableLBA > firstUsedBlock) {
375 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500376 cout << "Warning! Main partition table overlaps the first partition by "
377 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400378 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500379 cout << "Try reducing the partition table size by " << overlap * 4
380 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400381 } else {
srs5694fed16d02010-01-27 23:03:40 -0500382 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400383 } // if/else
384 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400385 } // Problem at start of disk
386 if (mainHeader.lastUsableLBA < lastUsedBlock) {
387 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500388 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500389 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400390 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500391 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400392 } else {
srs5694fed16d02010-01-27 23:03:40 -0500393 cout << "Try reducing the partition table size by " << overlap * 4
394 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400395 } // if/else
396 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400397 } // Problem at end of disk
398 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400399 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400400} // GPTData::CheckGPTSize()
401
srs5694e7b4ff92009-08-18 13:16:10 -0400402// Check the validity of the GPT header. Returns 1 if the main header
403// is valid, 2 if the backup header is valid, 3 if both are valid, and
srs5694d1b11e82011-09-18 21:12:28 -0400404// 0 if neither is valid. Note that this function checks the GPT signature,
405// revision value, and CRCs in both headers.
srs5694e7b4ff92009-08-18 13:16:10 -0400406int GPTData::CheckHeaderValidity(void) {
407 int valid = 3;
408
srs5694fed16d02010-01-27 23:03:40 -0500409 cout.setf(ios::uppercase);
410 cout.fill('0');
411
412 // Note: failed GPT signature checks produce no error message because
413 // a message is displayed in the ReversePartitionBytes() function
srs5694d1b11e82011-09-18 21:12:28 -0400414 if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400415 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400416 } else if ((mainHeader.revision != 0x00010000) && valid) {
417 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500418 cout << "Unsupported GPT version in main header; read 0x";
419 cout.width(8);
420 cout << hex << mainHeader.revision << ", should be\n0x";
421 cout.width(8);
422 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400423 } // if/else/if
424
srs5694d1b11e82011-09-18 21:12:28 -0400425 if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
srs5694e7b4ff92009-08-18 13:16:10 -0400426 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400427 } else if ((secondHeader.revision != 0x00010000) && valid) {
428 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500429 cout << "Unsupported GPT version in backup header; read 0x";
430 cout.width(8);
431 cout << hex << secondHeader.revision << ", should be\n0x";
432 cout.width(8);
433 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400434 } // if/else/if
435
srs5694df9d3632011-01-08 18:33:24 -0500436 // Check for an Apple disk signature
437 if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
438 (mainHeader.signature << 32) == APM_SIGNATURE2) {
srs5694221e0872009-08-29 15:00:31 -0400439 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500440 } // if
srs5694fed16d02010-01-27 23:03:40 -0500441 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400442
srs5694fed16d02010-01-27 23:03:40 -0500443 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400444} // GPTData::CheckHeaderValidity()
445
446// Check the header CRC to see if it's OK...
srs5694d1b11e82011-09-18 21:12:28 -0400447// Note: Must be called with header in platform-ordered byte order.
448// Returns 1 if header's computed CRC matches the stored value, 0 if the
449// computed and stored values don't match
450int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
srs5694978041c2009-09-21 20:51:47 -0400451 uint32_t oldCRC, newCRC, hSize;
srs5694d1b11e82011-09-18 21:12:28 -0400452 uint8_t *temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400453
srs56942a9f5da2009-08-26 00:48:01 -0400454 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400455 // computation to be valid
456 oldCRC = header->headerCRC;
457 header->headerCRC = UINT32_C(0);
srs5694d1b11e82011-09-18 21:12:28 -0400458
srs5694978041c2009-09-21 20:51:47 -0400459 hSize = header->headerSize;
460
srs5694d1b11e82011-09-18 21:12:28 -0400461 if (IsLittleEndian() == 0)
462 ReverseHeaderBytes(header);
srs5694e7b4ff92009-08-18 13:16:10 -0400463
srs5694d1b11e82011-09-18 21:12:28 -0400464 if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
465 if (warn) {
466 cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
467 cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
468 } // if
469 hSize = HEADER_SIZE;
470 } else if ((hSize > sizeof(GPTHeader)) && warn) {
471 cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
472 cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
473 << "which may result in a CRC false alarm.\n";
474 } // if/elseif
475 temp = new uint8_t[hSize];
476 if (temp != NULL) {
477 memset(temp, 0, hSize);
478 if (hSize < sizeof(GPTHeader))
479 memcpy(temp, header, hSize);
480 else
481 memcpy(temp, header, sizeof(GPTHeader));
srs5694e7b4ff92009-08-18 13:16:10 -0400482
srs5694d1b11e82011-09-18 21:12:28 -0400483 newCRC = chksum_crc32((unsigned char*) temp, hSize);
484 delete[] temp;
485 } else {
486 cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
487 exit(1);
488 }
489 if (IsLittleEndian() == 0)
490 ReverseHeaderBytes(header);
srs5694978041c2009-09-21 20:51:47 -0400491 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400492 return (oldCRC == newCRC);
493} // GPTData::CheckHeaderCRC()
494
srs56946699b012010-02-04 00:55:30 -0500495// Recompute all the CRCs. Must be called before saving if any changes have
496// been made. Must be called on platform-ordered data (this function reverses
497// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400498void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400499 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400500 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400501
srs5694d1b11e82011-09-18 21:12:28 -0400502 // If the header size is bigger than the GPT header data structure, reset it;
503 // otherwise, set both header sizes to whatever the main one is....
504 if (mainHeader.headerSize > sizeof(GPTHeader))
505 hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
506 else
507 hSize = secondHeader.headerSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500508
509 if ((littleEndian = IsLittleEndian()) == 0) {
510 ReversePartitionBytes();
511 ReverseHeaderBytes(&mainHeader);
512 ReverseHeaderBytes(&secondHeader);
513 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400514
srs5694e7b4ff92009-08-18 13:16:10 -0400515 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400516 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400517 mainHeader.partitionEntriesCRC = crc;
518 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400519 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400520 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
521 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400522 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400523
srs5694d1b11e82011-09-18 21:12:28 -0400524 // Zero out GPT headers' own CRCs (required for correct computation)
srs5694e7b4ff92009-08-18 13:16:10 -0400525 mainHeader.headerCRC = 0;
526 secondHeader.headerCRC = 0;
527
srs5694978041c2009-09-21 20:51:47 -0400528 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400529 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400530 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400531 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400532 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400533 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400534 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400535 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500536
srs5694d1b11e82011-09-18 21:12:28 -0400537 if (littleEndian == 0) {
srs56946699b012010-02-04 00:55:30 -0500538 ReverseHeaderBytes(&mainHeader);
539 ReverseHeaderBytes(&secondHeader);
540 ReversePartitionBytes();
541 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400542} // GPTData::RecomputeCRCs()
543
srs5694e7b4ff92009-08-18 13:16:10 -0400544// Rebuild the main GPT header, using the secondary header as a model.
545// Typically called when the main header has been found to be corrupt.
546void GPTData::RebuildMainHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400547 mainHeader.signature = GPT_SIGNATURE;
548 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400549 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400550 mainHeader.headerCRC = UINT32_C(0);
551 mainHeader.reserved = secondHeader.reserved;
552 mainHeader.currentLBA = secondHeader.backupLBA;
553 mainHeader.backupLBA = secondHeader.currentLBA;
554 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
555 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500556 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400557 mainHeader.partitionEntriesLBA = UINT64_C(2);
558 mainHeader.numParts = secondHeader.numParts;
559 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
560 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400561 memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500562 mainCrcOk = secondCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500563 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -0400564} // GPTData::RebuildMainHeader()
565
566// Rebuild the secondary GPT header, using the main header as a model.
567void GPTData::RebuildSecondHeader(void) {
srs5694e7b4ff92009-08-18 13:16:10 -0400568 secondHeader.signature = GPT_SIGNATURE;
569 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400570 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400571 secondHeader.headerCRC = UINT32_C(0);
572 secondHeader.reserved = mainHeader.reserved;
573 secondHeader.currentLBA = mainHeader.backupLBA;
574 secondHeader.backupLBA = mainHeader.currentLBA;
575 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
576 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500577 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400578 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
579 secondHeader.numParts = mainHeader.numParts;
580 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
581 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
srs569401f7f082011-03-15 23:53:31 -0400582 memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
srs5694546a9c72010-01-26 16:00:26 -0500583 secondCrcOk = mainCrcOk;
srs5694706e5122012-01-21 13:47:24 -0500584 SetGPTSize(secondHeader.numParts, 0);
srs5694e4ac11e2009-08-31 10:13:04 -0400585} // GPTData::RebuildSecondHeader()
586
587// Search for hybrid MBR entries that have no corresponding GPT partition.
588// Returns number of such mismatches found
589int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500590 int i, found, numFound = 0;
591 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400592 uint64_t mbrFirst, mbrLast;
593
594 for (i = 0; i < 4; i++) {
595 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
596 j = 0;
597 found = 0;
srs5694d1b11e82011-09-18 21:12:28 -0400598 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
599 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
srs5694e4ac11e2009-08-31 10:13:04 -0400600 do {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -0400601 if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
srs5694e69e6802012-01-20 22:37:12 -0500602 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
srs5694e4ac11e2009-08-31 10:13:04 -0400603 found = 1;
604 j++;
srs56940283dae2010-04-28 16:44:34 -0400605 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400606 if (!found) {
607 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500608 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
609 << i + 1 << ", of type 0x";
610 cout.fill('0');
611 cout.setf(ios::uppercase);
612 cout.width(2);
613 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
614 << "has no corresponding GPT partition! You may continue, but this condition\n"
615 << "might cause data loss in the future!\a\n" << dec;
616 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400617 } // if
618 } // if
619 } // for
620 return numFound;
621} // GPTData::FindHybridMismatches
622
623// Find overlapping partitions and warn user about them. Returns number of
624// overlapping partitions.
srs5694d1b11e82011-09-18 21:12:28 -0400625// Returns number of overlapping segments found.
srs5694e4ac11e2009-08-31 10:13:04 -0400626int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500627 int problems = 0;
628 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400629
srs56940283dae2010-04-28 16:44:34 -0400630 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400631 for (j = 0; j < i; j++) {
srs5694e69e6802012-01-20 22:37:12 -0500632 if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
633 (partitions[i].DoTheyOverlap(partitions[j]))) {
srs5694e4ac11e2009-08-31 10:13:04 -0400634 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500635 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
636 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
637 << " to " << partitions[i].GetLastLBA() << "\n";
638 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
639 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400640 } // if
641 } // for j...
642 } // for i...
643 return problems;
644} // GPTData::FindOverlaps()
645
srs569455d92612010-03-07 22:16:07 -0500646// Find partitions that are insane -- they start after they end or are too
647// big for the disk. (The latter should duplicate detection of overlaps
648// with GPT backup data structures, but better to err on the side of
649// redundant tests than to miss something....)
srs5694d1b11e82011-09-18 21:12:28 -0400650// Returns number of problems found.
srs569455d92612010-03-07 22:16:07 -0500651int GPTData::FindInsanePartitions(void) {
652 uint32_t i;
653 int problems = 0;
654
srs56940283dae2010-04-28 16:44:34 -0400655 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -0500656 if (partitions[i].IsUsed()) {
657 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
658 problems++;
659 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
660 } // if
661 if (partitions[i].GetLastLBA() >= diskSize) {
662 problems++;
663 cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
664 } // if
srs569455d92612010-03-07 22:16:07 -0500665 } // if
666 } // for
667 return problems;
668} // GPTData::FindInsanePartitions(void)
669
670
srs5694e4ac11e2009-08-31 10:13:04 -0400671/******************************************************************
672 * *
673 * Begin functions that load data from disk or save data to disk. *
674 * *
675 ******************************************************************/
676
srs569464cbd172011-03-01 22:03:54 -0500677// Change the filename associated with the GPT. Used for duplicating
678// the partition table to a new disk and saving backups.
679// Returns 1 on success, 0 on failure.
srs5694bf8950c2011-03-12 01:23:12 -0500680int GPTData::SetDisk(const string & deviceFilename) {
srs569464cbd172011-03-01 22:03:54 -0500681 int err, allOK = 1;
682
683 device = deviceFilename;
684 if (allOK && myDisk.OpenForRead(deviceFilename)) {
685 // store disk information....
686 diskSize = myDisk.DiskSize(&err);
687 blockSize = (uint32_t) myDisk.GetBlockSize();
688 } // if
689 protectiveMBR.SetDisk(&myDisk);
690 protectiveMBR.SetDiskSize(diskSize);
691 protectiveMBR.SetBlockSize(blockSize);
692 return allOK;
srs5694bf8950c2011-03-12 01:23:12 -0500693} // GPTData::SetDisk()
srs569464cbd172011-03-01 22:03:54 -0500694
srs5694e4ac11e2009-08-31 10:13:04 -0400695// Scan for partition data. This function loads the MBR data (regular MBR or
696// protective MBR) and loads BSD disklabel data (which is probably invalid).
697// It also looks for APM data, forces a load of GPT data, and summarizes
698// the results.
srs5694546a9c72010-01-26 16:00:26 -0500699void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400700 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400701
702 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500703 protectiveMBR.ReadMBRData(&myDisk);
704 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400705
706 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500707 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500708
Roderick W. Smith4a702a22014-01-25 23:46:42 -0500709 // Some tools create a 0xEE partition that's too big. If this is detected,
710 // normalize it....
711 if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
712 if (!beQuiet) {
713 cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
714 } // if
715 protectiveMBR.MakeProtectiveMBR();
716 } // if
717
srs5694ba00fed2010-01-12 18:18:36 -0500718 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500719 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500720 protectiveMBR.ShowState();
721 bsdDisklabel.ShowState();
722 ShowAPMState(); // Show whether there's an Apple Partition Map present
723 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500724 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500725 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400726
727 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500728 cout << "\n*******************************************************************\n"
729 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500730 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500731 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500732 } // if
srs5694fed16d02010-01-27 23:03:40 -0500733 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400734 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400735} // GPTData::PartitionScan()
736
737// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500738int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500739 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500740 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500741 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400742
srs5694546a9c72010-01-26 16:00:26 -0500743 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500744 err = myDisk.OpenForWrite(deviceFilename);
745 if ((err == 0) && (!justLooking)) {
746 cout << "\aNOTE: Write test failed with error number " << errno
747 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
748#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
749 cout << "You may be able to enable writes by exiting this program, typing\n"
750 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
751 << "program.\n";
752#endif
Aurimas Liutikasbdbab022017-03-07 09:50:36 -0800753 cout << "\n";
srs569455d92612010-03-07 22:16:07 -0500754 } // if
755 myDisk.Close(); // Close and re-open read-only in case of bugs
756 } else allOK = 0; // if
757
758 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400759 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500760 diskSize = myDisk.DiskSize(&err);
761 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500762 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500763 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400764
srs5694ba00fed2010-01-12 18:18:36 -0500765 whichWasUsed = UseWhichPartitions();
766 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400767 case use_mbr:
768 XFormPartitions();
769 break;
770 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500771 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400772// bsdDisklabel.DisplayBSDData();
773 ClearGPTData();
774 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500775 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400776 break;
777 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500778 mbrState = protectiveMBR.GetValidity();
779 if ((mbrState == invalid) || (mbrState == mbr))
780 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400781 break;
782 case use_new:
783 ClearGPTData();
784 protectiveMBR.MakeProtectiveMBR();
785 break;
srs56943c0af382010-01-15 19:19:18 -0500786 case use_abort:
787 allOK = 0;
srs56949ddc14b2010-08-22 22:44:42 -0400788 cerr << "Invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500789 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400790 } // switch
791
srs569455d92612010-03-07 22:16:07 -0500792 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500793 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500794 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400795 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400796 } else {
797 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400798 } // if/else
799 return (allOK);
800} // GPTData::LoadPartitions()
801
802// Loads the GPT, as much as possible. Returns 1 if this seems to have
803// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500804int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500805 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400806
srs5694cb76c672010-02-11 22:22:22 -0500807 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400808
srs5694cb76c672010-02-11 22:22:22 -0500809 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
810 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
811 } else {
srs569408bb0da2010-02-19 17:19:55 -0500812 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
813 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500814 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
815 << "secondary header from the last sector of the disk! You should use 'v' to\n"
816 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
817 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500818 } // if/else
819 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400820 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400821
822 // Return valid headers code: 0 = both headers bad; 1 = main header
823 // good, backup bad; 2 = backup header good, main header bad;
824 // 3 = both headers good. Note these codes refer to valid GPT
srs569423d8d542011-10-01 18:40:10 -0400825 // signatures, version numbers, and CRCs.
srs5694e4ac11e2009-08-31 10:13:04 -0400826 validHeaders = CheckHeaderValidity();
827
828 // Read partitions (from primary array)
829 if (validHeaders > 0) { // if at least one header is OK....
830 // GPT appears to be valid....
831 state = gpt_valid;
832
833 // We're calling the GPT valid, but there's a possibility that one
834 // of the two headers is corrupt. If so, use the one that seems to
835 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500836 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500837 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
838 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400839 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500840 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400841 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500842 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500843 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
844 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500845 RebuildMainHeader();
846 state = gpt_corrupt;
847 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400848 } // if/else/if
849
srs5694546a9c72010-01-26 16:00:26 -0500850 // Figure out which partition table to load....
851 // Load the main partition table, since either its header's CRC is OK or the
852 // backup header's CRC is not OK....
853 if (mainCrcOk || !secondCrcOk) {
854 if (LoadMainTable() == 0)
855 allOK = 0;
856 } else { // bad main header CRC and backup header CRC is OK
857 state = gpt_corrupt;
858 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500859 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500860 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500861 } else { // backup table bad, bad main header CRC, but try main table in desperation....
862 if (LoadMainTable() == 0) {
863 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500864 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500865 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500866 } // if
867 } // if/else (LoadSecondTableAsMain())
868 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400869
srs5694cb76c672010-02-11 22:22:22 -0500870 if (loadedTable == 1)
871 secondPartsCrcOk = CheckTable(&secondHeader);
872 else if (loadedTable == 2)
873 mainPartsCrcOk = CheckTable(&mainHeader);
874 else
875 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400876
srs5694546a9c72010-01-26 16:00:26 -0500877 // Problem with main partition table; if backup is OK, use it instead....
878 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
879 state = gpt_corrupt;
880 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500881 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500882 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
883 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500884 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500885
srs5694e4ac11e2009-08-31 10:13:04 -0400886 // Check for valid CRCs and warn if there are problems
887 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
888 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500889 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400890 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500891 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400892 } else {
893 state = gpt_invalid;
894 } // if/else
895 return allOK;
896} // GPTData::ForceLoadGPTData()
897
srs5694247657a2009-11-26 18:36:12 -0500898// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400899// main GPT header in memory MUST be valid for this call to do anything
900// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500901// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400902int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500903 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400904} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400905
906// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500907// table. Used in repair functions, and when starting up if the main
908// partition table is damaged.
909// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
910int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500911 return LoadPartitionTable(secondHeader, myDisk);
912} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400913
srs5694cb76c672010-02-11 22:22:22 -0500914// Load a single GPT header (main or backup) from the specified disk device and
915// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
916// value appropriately.
917// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
918// failure.
919int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
920 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500921 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500922
923 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500924 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500925 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
926 allOK = 0;
927 } // if
srs5694cb76c672010-02-11 22:22:22 -0500928
srs56941c6f8b02010-02-21 11:09:20 -0500929 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500930 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500931 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500932 } // if
srs5694d1b11e82011-09-18 21:12:28 -0400933 *crcOk = CheckHeaderCRC(&tempHeader);
srs56941c6f8b02010-02-21 11:09:20 -0500934
srs56940283dae2010-04-28 16:44:34 -0400935 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs5694706e5122012-01-21 13:47:24 -0500936 allOK = SetGPTSize(tempHeader.numParts, 0);
srs569455d92612010-03-07 22:16:07 -0500937 }
srs56941c6f8b02010-02-21 11:09:20 -0500938
939 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500940 return allOK;
941} // GPTData::LoadHeader
942
943// Load a partition table (either main or secondary) from the specified disk,
944// using header as a reference for what to load. If sector != 0 (the default
945// is 0), loads from the specified sector; otherwise loads from the sector
946// indicated in header.
947// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
948int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
949 uint32_t sizeOfParts, newCRC;
950 int retval;
951
952 if (disk.OpenForRead()) {
953 if (sector == 0) {
954 retval = disk.Seek(header.partitionEntriesLBA);
955 } else {
956 retval = disk.Seek(sector);
957 } // if/else
srs569455d92612010-03-07 22:16:07 -0500958 if (retval == 1)
srs5694706e5122012-01-21 13:47:24 -0500959 retval = SetGPTSize(header.numParts, 0);
srs5694546a9c72010-01-26 16:00:26 -0500960 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500961 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
962 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500963 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500964 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500965 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400966 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500967 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400968 if (IsLittleEndian() == 0)
969 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500970 if (!mainPartsCrcOk) {
971 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400972 } // if
973 } else {
srs5694cb76c672010-02-11 22:22:22 -0500974 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400975 } // if/else
976 } else {
srs5694fed16d02010-01-27 23:03:40 -0500977 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500978 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500979 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400980 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500981 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500982} // GPTData::LoadPartitionsTable()
983
984// Check the partition table pointed to by header, but don't keep it
985// around.
srs5694a17fe692011-09-10 20:30:20 -0400986// Returns 1 if the CRC is OK & this table matches the one already in memory,
987// 0 if not or if there was a read error.
srs5694cb76c672010-02-11 22:22:22 -0500988int GPTData::CheckTable(struct GPTHeader *header) {
989 uint32_t sizeOfParts, newCRC;
srs5694a17fe692011-09-10 20:30:20 -0400990 GPTPart *partsToCheck;
srs5694d1b11e82011-09-18 21:12:28 -0400991 GPTHeader *otherHeader;
srs5694a17fe692011-09-10 20:30:20 -0400992 int allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500993
srs56940283dae2010-04-28 16:44:34 -0400994 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500995 // its CRC and store the results, then discard this temporary
996 // storage, since we don't use it in any but recovery operations
997 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs5694a17fe692011-09-10 20:30:20 -0400998 partsToCheck = new GPTPart[header->numParts];
srs56940283dae2010-04-28 16:44:34 -0400999 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694a17fe692011-09-10 20:30:20 -04001000 if (partsToCheck == NULL) {
srs56946aae2a92011-06-10 01:16:51 -04001001 cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
1002 exit(1);
1003 } // if
srs5694a17fe692011-09-10 20:30:20 -04001004 if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -04001005 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -05001006 } else {
srs5694d1b11e82011-09-18 21:12:28 -04001007 newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
srs5694a17fe692011-09-10 20:30:20 -04001008 allOK = (newCRC == header->partitionEntriesCRC);
srs5694d1b11e82011-09-18 21:12:28 -04001009 if (header == &mainHeader)
1010 otherHeader = &secondHeader;
1011 else
1012 otherHeader = &mainHeader;
1013 if (newCRC != otherHeader->partitionEntriesCRC) {
srs5694a17fe692011-09-10 20:30:20 -04001014 cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
1015 << "on the recovery & transformation menu to examine the two tables.\n\n";
1016 allOK = 0;
1017 } // if
srs5694cb76c672010-02-11 22:22:22 -05001018 } // if/else
srs5694a17fe692011-09-10 20:30:20 -04001019 delete[] partsToCheck;
srs5694cb76c672010-02-11 22:22:22 -05001020 } // if
srs5694a17fe692011-09-10 20:30:20 -04001021 return allOK;
srs5694cb76c672010-02-11 22:22:22 -05001022} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -04001023
srs56944307ef22012-05-30 12:30:48 -04001024// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1025// header later on the disk without asking for permission, if necessary, and
1026// doesn't confirm the operation before writing. If quiet==0, asks permission
1027// before moving the second header and asks for final confirmation of any
1028// write.
srs5694a17fe692011-09-10 20:30:20 -04001029// Returns 1 on successful write, 0 if there was a problem.
srs569464cbd172011-03-01 22:03:54 -05001030int GPTData::SaveGPTData(int quiet) {
srs56944307ef22012-05-30 12:30:48 -04001031 int allOK = 1, syncIt = 1;
srs5694e321d442010-01-29 17:44:04 -05001032 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -04001033
srs5694e7b4ff92009-08-18 13:16:10 -04001034 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -05001035
1036 // This test should only fail on read-only disks....
1037 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001038 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -05001039 allOK = 0;
1040 } // if
1041
srs569464cbd172011-03-01 22:03:54 -05001042 // Check that disk is really big enough to handle the second header...
1043 if (mainHeader.backupLBA >= diskSize) {
1044 cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1045 << "header, but other problems may occur!\n";
1046 MoveSecondHeaderToEnd();
1047 } // if
1048
srs5694e7b4ff92009-08-18 13:16:10 -04001049 // Is there enough space to hold the GPT headers and partition tables,
1050 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -04001051 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -04001052 allOK = 0;
1053 } // if
1054
srs5694247657a2009-11-26 18:36:12 -05001055 // Check that second header is properly placed. Warn and ask if this should
1056 // be corrected if the test fails....
srs569464cbd172011-03-01 22:03:54 -05001057 if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1058 if (quiet == 0) {
1059 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1060 << "correct this problem? ";
1061 if (GetYN() == 'Y') {
1062 MoveSecondHeaderToEnd();
1063 cout << "Have moved second header and partition table to correct location.\n";
1064 } else {
1065 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1066 } // if correction requested
1067 } else { // Go ahead and do correction automatically
srs5694247657a2009-11-26 18:36:12 -05001068 MoveSecondHeaderToEnd();
srs569464cbd172011-03-01 22:03:54 -05001069 } // if/else quiet
srs5694247657a2009-11-26 18:36:12 -05001070 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001071
srs5694d8eed462012-12-15 01:55:21 -05001072 if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1073 if (quiet == 0) {
1074 cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1075 << "this problem? ";
1076 if (GetYN() == 'Y') {
1077 MoveSecondHeaderToEnd();
1078 cout << "Have adjusted the second header and last usable sector value.\n";
1079 } else {
1080 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1081 } // if correction requested
1082 } else { // go ahead and do correction automatically
1083 MoveSecondHeaderToEnd();
1084 } // if/else quiet
1085 } // if
1086
srs569455d92612010-03-07 22:16:07 -05001087 // Check for overlapping or insane partitions....
1088 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001089 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001090 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001091 } // if
1092
Roderick W. Smith4a702a22014-01-25 23:46:42 -05001093 // Check that protective MBR fits, and warn if it doesn't....
1094 if (!protectiveMBR.DoTheyFit()) {
1095 cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1096 << "fresh protective or hybrid MBR is recommended.\n";
1097 }
1098
srs5694e4ac11e2009-08-31 10:13:04 -04001099 // Check for mismatched MBR and GPT data, but let it pass if found
1100 // (function displays warning message)
1101 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -04001102
1103 RecomputeCRCs();
1104
srs5694ba00fed2010-01-12 18:18:36 -05001105 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001106 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
srs5694bf8950c2011-03-12 01:23:12 -05001107 << "PARTITIONS!!\n\nDo you want to proceed? ";
srs56945d58fe02010-01-03 20:57:08 -05001108 answer = GetYN();
1109 if (answer == 'Y') {
srs569434882942012-03-23 12:49:15 -04001110 cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001111 } else {
1112 allOK = 0;
1113 } // if/else
1114 } // if
1115
1116 // Do it!
1117 if (allOK) {
srs569464cbd172011-03-01 22:03:54 -05001118 if (myDisk.OpenForWrite()) {
srs56948a4ddfc2010-03-21 19:05:49 -04001119 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -05001120 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
srs56944307ef22012-05-30 12:30:48 -04001121 if (!allOK) {
srs5694cb76c672010-02-11 22:22:22 -05001122 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1123 << "menu will resolve this problem.\n";
srs56944307ef22012-05-30 12:30:48 -04001124 syncIt = 0;
1125 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001126
1127 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -04001128 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1129
1130 // Now write the main partition tables...
1131 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1132
1133 // Now write the main GPT header...
1134 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1135
1136 // To top it off, write the protective MBR...
1137 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001138
1139 // re-read the partition table
srs56944307ef22012-05-30 12:30:48 -04001140 // Note: Done even if some write operations failed, but not if all of them failed.
1141 // Done this way because I've received one problem report from a user one whose
1142 // system the MBR write failed but everything else was OK (on a GPT disk under
1143 // Windows), and the failure to sync therefore caused Windows to restore the
1144 // original partition table from its cache. OTOH, such restoration might be
1145 // desirable if the error occurs later; but that seems unlikely unless the initial
1146 // write fails....
1147 if (syncIt)
srs5694546a9c72010-01-26 16:00:26 -05001148 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -04001149
1150 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001151 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001152 } else {
srs5694fed16d02010-01-27 23:03:40 -05001153 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56944307ef22012-05-30 12:30:48 -04001154 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001155 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -04001156
srs5694546a9c72010-01-26 16:00:26 -05001157 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001158 } else {
srs56945a608532011-03-17 13:53:01 -04001159 cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
srs5694fed16d02010-01-27 23:03:40 -05001160 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001161 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -04001162 } // if/else
1163 } else {
srs5694fed16d02010-01-27 23:03:40 -05001164 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001165 } // if
1166
1167 return (allOK);
1168} // GPTData::SaveGPTData()
1169
1170// Save GPT data to a backup file. This function does much less error
1171// checking than SaveGPTData(). It can therefore preserve many types of
1172// corruption for later analysis; however, it preserves only the MBR,
1173// the main GPT header, the backup GPT header, and the main partition
1174// table; it discards the backup partition table, since it should be
1175// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -05001176int GPTData::SaveGPTBackup(const string & filename) {
1177 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -05001178 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001179
srs5694546a9c72010-01-26 16:00:26 -05001180 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -05001181 // Recomputing the CRCs is likely to alter them, which could be bad
1182 // if the intent is to save a potentially bad GPT for later analysis;
1183 // but if we don't do this, we get bogus errors when we load the
1184 // backup. I'm favoring misses over false alarms....
1185 RecomputeCRCs();
1186
srs5694546a9c72010-01-26 16:00:26 -05001187 protectiveMBR.WriteMBRData(&backupFile);
srs5694699941e2011-03-21 21:33:57 -04001188 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001189
srs5694cb76c672010-02-11 22:22:22 -05001190 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -05001191 // MBR write closed disk, so re-open and seek to end....
1192 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001193 allOK = SaveHeader(&mainHeader, backupFile, 1);
1194 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001195
srs5694e7b4ff92009-08-18 13:16:10 -04001196 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001197 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001198
srs5694cb76c672010-02-11 22:22:22 -05001199 if (allOK)
1200 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001201
1202 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001203 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001204 } else {
srs5694fed16d02010-01-27 23:03:40 -05001205 cerr << "Warning! An error was reported when writing the backup file.\n"
1206 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001207 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001208 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001209 } else {
srs56945a608532011-03-17 13:53:01 -04001210 cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001211 allOK = 0;
1212 } // if/else
1213 return allOK;
1214} // GPTData::SaveGPTBackup()
1215
srs5694cb76c672010-02-11 22:22:22 -05001216// Write a GPT header (main or backup) to the specified sector. Used by both
1217// the SaveGPTData() and SaveGPTBackup() functions.
1218// Should be passed an architecture-appropriate header (DO NOT call
1219// ReverseHeaderBytes() on the header before calling this function)
1220// Returns 1 on success, 0 on failure
1221int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1222 int littleEndian, allOK = 1;
1223
1224 littleEndian = IsLittleEndian();
1225 if (!littleEndian)
1226 ReverseHeaderBytes(header);
1227 if (disk.Seek(sector)) {
1228 if (disk.Write(header, 512) == -1)
1229 allOK = 0;
1230 } else allOK = 0; // if (disk.Seek()...)
1231 if (!littleEndian)
1232 ReverseHeaderBytes(header);
1233 return allOK;
1234} // GPTData::SaveHeader()
1235
1236// Save the partitions to the specified sector. Used by both the SaveGPTData()
1237// and SaveGPTBackup() functions.
1238// Should be passed an architecture-appropriate header (DO NOT call
1239// ReverseHeaderBytes() on the header before calling this function)
1240// Returns 1 on success, 0 on failure
1241int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1242 int littleEndian, allOK = 1;
1243
1244 littleEndian = IsLittleEndian();
1245 if (disk.Seek(sector)) {
1246 if (!littleEndian)
1247 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001248 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001249 allOK = 0;
1250 if (!littleEndian)
1251 ReversePartitionBytes();
1252 } else allOK = 0; // if (myDisk.Seek()...)
1253 return allOK;
1254} // GPTData::SavePartitionTable()
1255
srs5694e7b4ff92009-08-18 13:16:10 -04001256// Load GPT data from a backup file created by SaveGPTBackup(). This function
1257// does minimal error checking. It returns 1 if it completed successfully,
1258// 0 if there was a problem. In the latter case, it creates a new empty
1259// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001260int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001261 int allOK = 1, val, err;
srs56940541b562011-12-18 16:35:25 -05001262 int shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001263 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001264
srs5694546a9c72010-01-26 16:00:26 -05001265 if (backupFile.OpenForRead(filename)) {
srs5694e7b4ff92009-08-18 13:16:10 -04001266 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001267 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694815fb652011-03-18 12:35:56 -04001268 protectiveMBR.SetDisk(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -04001269
srs5694cb76c672010-02-11 22:22:22 -05001270 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001271
srs5694cb76c672010-02-11 22:22:22 -05001272 // Check backup file size and rebuild second header if file is right
1273 // size to be direct dd copy of MBR, main header, and main partition
1274 // table; if other size, treat it like a GPT fdisk-generated backup
1275 // file
1276 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1277 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1278 if (shortBackup) {
1279 RebuildSecondHeader();
1280 secondCrcOk = mainCrcOk;
1281 } else {
1282 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1283 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001284
srs5694e7b4ff92009-08-18 13:16:10 -04001285 // Return valid headers code: 0 = both headers bad; 1 = main header
1286 // good, backup bad; 2 = backup header good, main header bad;
1287 // 3 = both headers good. Note these codes refer to valid GPT
1288 // signatures and version numbers; more subtle problems will elude
1289 // this check!
1290 if ((val = CheckHeaderValidity()) > 0) {
1291 if (val == 2) { // only backup header seems to be good
srs5694706e5122012-01-21 13:47:24 -05001292 SetGPTSize(secondHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001293 } else { // main header is OK
srs5694706e5122012-01-21 13:47:24 -05001294 SetGPTSize(mainHeader.numParts, 0);
srs5694e7b4ff92009-08-18 13:16:10 -04001295 } // if/else
1296
srs5694e7b4ff92009-08-18 13:16:10 -04001297 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001298 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1299 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001300 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001301 } // if
1302
srs5694cb76c672010-02-11 22:22:22 -05001303 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1304 cerr << "Warning! Read error " << errno
1305 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001306 } else {
1307 allOK = 0;
1308 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001309 // Something went badly wrong, so blank out partitions
1310 if (allOK == 0) {
1311 cerr << "Improper backup file! Clearing all partition data!\n";
1312 ClearGPTData();
1313 protectiveMBR.MakeProtectiveMBR();
1314 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001315 } else {
1316 allOK = 0;
srs56945a608532011-03-17 13:53:01 -04001317 cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001318 } // if/else
1319
srs5694e7b4ff92009-08-18 13:16:10 -04001320 return allOK;
1321} // GPTData::LoadGPTBackup()
1322
srs569408bb0da2010-02-19 17:19:55 -05001323int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001324 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001325} // GPTData::SaveMBR()
1326
1327// This function destroys the on-disk GPT structures, but NOT the on-disk
1328// MBR.
1329// Returns 1 if the operation succeeds, 0 if not.
1330int GPTData::DestroyGPT(void) {
srs569401f7f082011-03-15 23:53:31 -04001331 int sum, tableSize, allOK = 1;
srs569408bb0da2010-02-19 17:19:55 -05001332 uint8_t blankSector[512];
1333 uint8_t* emptyTable;
1334
srs569401f7f082011-03-15 23:53:31 -04001335 memset(blankSector, 0, sizeof(blankSector));
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001336 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001337
1338 if (myDisk.OpenForWrite()) {
1339 if (!myDisk.Seek(mainHeader.currentLBA))
1340 allOK = 0;
1341 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1342 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1343 allOK = 0;
1344 } // if
1345 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1346 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001347 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001348 emptyTable = new uint8_t[tableSize];
srs56946aae2a92011-06-10 01:16:51 -04001349 if (emptyTable == NULL) {
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001350 cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
1351 exit(1);
srs56946aae2a92011-06-10 01:16:51 -04001352 } // if
srs569401f7f082011-03-15 23:53:31 -04001353 memset(emptyTable, 0, tableSize);
srs569408bb0da2010-02-19 17:19:55 -05001354 if (allOK) {
1355 sum = myDisk.Write(emptyTable, tableSize);
1356 if (sum != tableSize) {
1357 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1358 allOK = 0;
1359 } // if write failed
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001360 } // if
1361 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1362 allOK = 0;
1363 if (allOK) {
1364 sum = myDisk.Write(emptyTable, tableSize);
1365 if (sum != tableSize) {
1366 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1367 << errno << "\n";
1368 allOK = 0;
1369 } // if wrong size written
srs569408bb0da2010-02-19 17:19:55 -05001370 } // if
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001371 if (!myDisk.Seek(secondHeader.currentLBA))
1372 allOK = 0;
1373 if (allOK) {
1374 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1375 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
srs569408bb0da2010-02-19 17:19:55 -05001376 allOK = 0;
1377 } // if
Roderick W. Smith84aaff62014-02-17 16:17:11 -05001378 } // if
srs569408bb0da2010-02-19 17:19:55 -05001379 myDisk.DiskSync();
1380 myDisk.Close();
1381 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1382 << "other utilities.\n";
1383 delete[] emptyTable;
1384 } else {
srs56945a608532011-03-17 13:53:01 -04001385 cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
srs569408bb0da2010-02-19 17:19:55 -05001386 } // if/else (fd != -1)
1387 return (allOK);
1388} // GPTDataTextUI::DestroyGPT()
1389
1390// Wipe MBR data from the disk (zero it out completely)
1391// Returns 1 on success, 0 on failure.
1392int GPTData::DestroyMBR(void) {
srs569401f7f082011-03-15 23:53:31 -04001393 int allOK;
srs569408bb0da2010-02-19 17:19:55 -05001394 uint8_t blankSector[512];
1395
srs569401f7f082011-03-15 23:53:31 -04001396 memset(blankSector, 0, sizeof(blankSector));
srs569408bb0da2010-02-19 17:19:55 -05001397
srs569401f7f082011-03-15 23:53:31 -04001398 allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1399
srs569408bb0da2010-02-19 17:19:55 -05001400 if (!allOK)
1401 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1402 return allOK;
1403} // GPTData::DestroyMBR(void)
1404
srs5694e4ac11e2009-08-31 10:13:04 -04001405// Tell user whether Apple Partition Map (APM) was discovered....
1406void GPTData::ShowAPMState(void) {
1407 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001408 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001409 else
srs5694fed16d02010-01-27 23:03:40 -05001410 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001411} // GPTData::ShowAPMState()
1412
1413// Tell user about the state of the GPT data....
1414void GPTData::ShowGPTState(void) {
1415 switch (state) {
1416 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001417 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001418 break;
1419 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001420 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001421 break;
1422 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001423 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001424 break;
1425 default:
srs5694fed16d02010-01-27 23:03:40 -05001426 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001427 break;
1428 } // switch
1429} // GPTData::ShowGPTState()
1430
1431// Display the basic GPT data
1432void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001433 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001434 uint64_t temp, totalFree;
1435
srs5694fed16d02010-01-27 23:03:40 -05001436 cout << "Disk " << device << ": " << diskSize << " sectors, "
srs569401f7f082011-03-15 23:53:31 -04001437 << BytesToIeee(diskSize, blockSize) << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001438 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56945a081752010-09-24 20:39:41 -04001439 cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
srs56940283dae2010-04-28 16:44:34 -04001440 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001441 cout << "First usable sector is " << mainHeader.firstUsableLBA
1442 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001443 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001444 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001445 cout << "Total free space is " << totalFree << " sectors ("
srs569401f7f082011-03-15 23:53:31 -04001446 << BytesToIeee(totalFree, blockSize) << ")\n";
srs5694fed16d02010-01-27 23:03:40 -05001447 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001448 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001449 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001450 } // for
1451} // GPTData::DisplayGPTData()
1452
srs5694e4ac11e2009-08-31 10:13:04 -04001453// Show detailed information on the specified partition
Jeff Sharkeyd761ff52015-02-28 19:18:39 -08001454void GPTData::ShowPartDetails(uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001455 if ((partNum < numParts) && !IsFreePartNum(partNum)) {
Jeff Sharkeyd761ff52015-02-28 19:18:39 -08001456 partitions[partNum].ShowDetails(blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001457 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04001458 cout << "Partition #" << partNum + 1 << " does not exist.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001459 } // if
1460} // GPTData::ShowPartDetails()
1461
srs5694e4ac11e2009-08-31 10:13:04 -04001462/**************************************************************************
1463 * *
1464 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1465 * (some of these functions may require user interaction) *
1466 * *
1467 **************************************************************************/
1468
srs569408bb0da2010-02-19 17:19:55 -05001469// Examines the MBR & GPT data to determine which set of data to use: the
1470// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1471// a new set of partitions (use_new). A return value of use_abort indicates
1472// that this function couldn't determine what to do. Overriding functions
1473// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001474WhichToUse GPTData::UseWhichPartitions(void) {
1475 WhichToUse which = use_new;
1476 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001477
1478 mbrState = protectiveMBR.GetValidity();
1479
1480 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001481 cout << "\n***************************************************************\n"
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001482 << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1483 << "in memory. ";
srs56945d58fe02010-01-03 20:57:08 -05001484 if (!justLooking) {
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001485 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1486 << "typing 'q' if you don't want to convert your MBR partitions\n"
1487 << "to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001488 } // if
Roderick W. Smith1eea9b02013-07-06 22:52:58 -04001489 cout << "\n***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001490 which = use_mbr;
1491 } // if
1492
1493 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001494 cout << "\n**********************************************************************\n"
1495 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1496 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001497 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001498 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001499 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1500 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001501 } // if
srs5694fed16d02010-01-27 23:03:40 -05001502 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001503 which = use_bsd;
1504 } // if
1505
1506 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001507 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001508 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001509 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001510 } // if
1511 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001512 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001513 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001514 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001515 } // if
1516 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001517 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001518 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001519 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001520 } // if
1521 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001522 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001523 } // if
1524
srs5694e4ac11e2009-08-31 10:13:04 -04001525 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001526 if (mbrState == gpt) {
1527 cout << "\a\a****************************************************************************\n"
1528 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1529 << "verification and recovery are STRONGLY recommended.\n"
1530 << "****************************************************************************\n";
1531 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001532 } else {
srs569408bb0da2010-02-19 17:19:55 -05001533 which = use_abort;
1534 } // if/else MBR says disk is GPT
1535 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001536
1537 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001538 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001539
1540 return which;
1541} // UseWhichPartitions()
1542
srs569408bb0da2010-02-19 17:19:55 -05001543// Convert MBR partition table into GPT form.
1544void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001545 int i, numToConvert;
1546 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001547
1548 // Clear out old data & prepare basics....
1549 ClearGPTData();
1550
1551 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001552 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001553 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001554 else
srs56940283dae2010-04-28 16:44:34 -04001555 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001556
1557 for (i = 0; i < numToConvert; i++) {
1558 origType = protectiveMBR.GetType(i);
1559 // don't waste CPU time trying to convert extended, hybrid protective, or
1560 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001561 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001562 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001563 partitions[i] = protectiveMBR.AsGPT(i);
1564 } // for
1565
1566 // Convert MBR into protective MBR
1567 protectiveMBR.MakeProtectiveMBR();
1568
1569 // Record that all original CRCs were OK so as not to raise flags
1570 // when doing a disk verification
1571 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001572} // GPTData::XFormPartitions()
1573
1574// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001575// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001576// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001577int GPTData::XFormDisklabel(uint32_t partNum) {
1578 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001579 int goOn = 1, numDone = 0;
1580 BSDData disklabel;
1581
srs569408bb0da2010-02-19 17:19:55 -05001582 if (GetPartRange(&low, &high) == 0) {
1583 goOn = 0;
1584 cout << "No partitions!\n";
1585 } // if
1586 if (partNum > high) {
1587 goOn = 0;
1588 cout << "Specified partition is invalid!\n";
1589 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001590
srs569408bb0da2010-02-19 17:19:55 -05001591 // If all is OK, read the disklabel and convert it.
1592 if (goOn) {
1593 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1594 partitions[partNum].GetLastLBA());
1595 if ((goOn) && (disklabel.IsDisklabel())) {
1596 numDone = XFormDisklabel(&disklabel);
1597 if (numDone == 1)
1598 cout << "Converted 1 BSD partition.\n";
1599 else
1600 cout << "Converted " << numDone << " BSD partitions.\n";
1601 } else {
1602 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1603 } // if/else
1604 } // if
1605 if (numDone > 0) { // converted partitions; delete carrier
1606 partitions[partNum].BlankPartition();
1607 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001608 return numDone;
srs569455d92612010-03-07 22:16:07 -05001609} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001610
1611// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001612int GPTData::XFormDisklabel(BSDData* disklabel) {
1613 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001614
srs569408bb0da2010-02-19 17:19:55 -05001615 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001616 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001617 partNum = FindFirstFreePart();
1618 if (partNum >= 0) {
1619 partitions[partNum] = disklabel->AsGPT(i);
1620 if (partitions[partNum].IsUsed())
1621 numDone++;
1622 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001623 } // for
srs569408bb0da2010-02-19 17:19:55 -05001624 if (partNum == -1)
1625 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001626 } // if
1627
1628 // Record that all original CRCs were OK so as not to raise flags
1629 // when doing a disk verification
1630 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1631
1632 return numDone;
1633} // GPTData::XFormDisklabel(BSDData* disklabel)
1634
srs569408bb0da2010-02-19 17:19:55 -05001635// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1636// partition has the active/bootable flag UNset and uses the GPT fdisk
1637// type code divided by 0x0100 as the MBR type code.
1638// Returns 1 if operation was 100% successful, 0 if there were ANY
1639// problems.
srs5694978041c2009-09-21 20:51:47 -04001640int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001641 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001642
srs5694978041c2009-09-21 20:51:47 -04001643 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001644 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001645 allOK = 0;
1646 } // if
srs56940283dae2010-04-28 16:44:34 -04001647 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001648 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001649 allOK = 0;
1650 } // if
1651 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001652 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001653 allOK = 0;
1654 } // if
1655 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1656 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1657 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001658 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1659 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001660 } // if
srs5694978041c2009-09-21 20:51:47 -04001661 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001662 (uint32_t) partitions[gptPart].GetLengthLBA(),
1663 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001664 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001665 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1666 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1667 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001668 allOK = 0;
1669 } // if/else
1670 return allOK;
1671} // GPTData::OnePartToMBR()
1672
srs5694e4ac11e2009-08-31 10:13:04 -04001673
1674/**********************************************************************
1675 * *
1676 * Functions that adjust GPT data structures WITHOUT user interaction *
1677 * (they may display information for the user's benefit, though) *
1678 * *
1679 **********************************************************************/
1680
1681// Resizes GPT to specified number of entries. Creates a new table if
srs5694706e5122012-01-21 13:47:24 -05001682// necessary, copies data if it already exists. If fillGPTSectors is 1
1683// (the default), rounds numEntries to fill all the sectors necessary to
1684// hold the GPT.
1685// Returns 1 if all goes well, 0 if an error is encountered.
1686int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
srs569408bb0da2010-02-19 17:19:55 -05001687 GPTPart* newParts;
srs5694706e5122012-01-21 13:47:24 -05001688 uint32_t i, high, copyNum, entriesPerSector;
srs5694e4ac11e2009-08-31 10:13:04 -04001689 int allOK = 1;
1690
1691 // First, adjust numEntries upward, if necessary, to get a number
1692 // that fills the allocated sectors
srs5694706e5122012-01-21 13:47:24 -05001693 entriesPerSector = blockSize / GPT_SIZE;
1694 if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
srs5694fed16d02010-01-27 23:03:40 -05001695 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694706e5122012-01-21 13:47:24 -05001696 numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
srs5694fed16d02010-01-27 23:03:40 -05001697 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001698 } // if
1699
srs5694247657a2009-11-26 18:36:12 -05001700 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001701 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001702 // partition table, which causes problems when loading data from a RAID
1703 // array that's been expanded because this function is called when loading
1704 // data.
srs56940283dae2010-04-28 16:44:34 -04001705 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs569401f7f082011-03-15 23:53:31 -04001706 newParts = new GPTPart [numEntries];
srs5694247657a2009-11-26 18:36:12 -05001707 if (newParts != NULL) {
1708 if (partitions != NULL) { // existing partitions; copy them over
1709 GetPartRange(&i, &high);
1710 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001711 cout << "The highest-numbered partition is " << high + 1
1712 << ", which is greater than the requested\n"
1713 << "partition table size of " << numEntries
1714 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001715 allOK = 0;
srs5694815fb652011-03-18 12:35:56 -04001716 delete[] newParts;
srs5694247657a2009-11-26 18:36:12 -05001717 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001718 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001719 copyNum = numEntries;
1720 else
srs56940283dae2010-04-28 16:44:34 -04001721 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001722 for (i = 0; i < copyNum; i++) {
1723 newParts[i] = partitions[i];
1724 } // for
srs569401f7f082011-03-15 23:53:31 -04001725 delete[] partitions;
srs5694247657a2009-11-26 18:36:12 -05001726 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001727 } // if
1728 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001729 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001730 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001731 numParts = numEntries;
srs5694706e5122012-01-21 13:47:24 -05001732 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
srs5694247657a2009-11-26 18:36:12 -05001733 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1734 MoveSecondHeaderToEnd();
1735 if (diskSize > 0)
1736 CheckGPTSize();
1737 } else { // Bad memory allocation
srs56946aae2a92011-06-10 01:16:51 -04001738 cerr << "Error allocating memory for partition table! Size is unchanged!\n";
srs5694247657a2009-11-26 18:36:12 -05001739 allOK = 0;
1740 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001741 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001742 mainHeader.numParts = numParts;
1743 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001744 return (allOK);
1745} // GPTData::SetGPTSize()
1746
1747// Blank the partition array
1748void GPTData::BlankPartitions(void) {
1749 uint32_t i;
1750
srs56940283dae2010-04-28 16:44:34 -04001751 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001752 partitions[i].BlankPartition();
1753 } // for
1754} // GPTData::BlankPartitions()
1755
srs5694ba00fed2010-01-12 18:18:36 -05001756// Delete a partition by number. Returns 1 if successful,
1757// 0 if there was a problem. Returns 1 if partition was in
1758// range, 0 if it was out of range.
1759int GPTData::DeletePartition(uint32_t partNum) {
1760 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001761 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001762
srs56940283dae2010-04-28 16:44:34 -04001763 numUsedParts = GetPartRange(&low, &high);
1764 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001765 // In case there's a protective MBR, look for & delete matching
1766 // MBR partition....
1767 startSector = partitions[partNum].GetFirstLBA();
1768 length = partitions[partNum].GetLengthLBA();
1769 protectiveMBR.DeleteByLocation(startSector, length);
1770
1771 // Now delete the GPT partition
1772 partitions[partNum].BlankPartition();
1773 } else {
srs5694fed16d02010-01-27 23:03:40 -05001774 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001775 retval = 0;
1776 } // if/else
1777 return retval;
1778} // GPTData::DeletePartition(uint32_t partNum)
1779
srs569408bb0da2010-02-19 17:19:55 -05001780// Non-interactively create a partition.
1781// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001782uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001783 int retval = 1; // assume there'll be no problems
srs56945a081752010-09-24 20:39:41 -04001784 uint64_t origSector = startSector;
srs5694ba00fed2010-01-12 18:18:36 -05001785
1786 if (IsFreePartNum(partNum)) {
srs56945a081752010-09-24 20:39:41 -04001787 if (Align(&startSector)) {
1788 cout << "Information: Moved requested sector from " << origSector << " to "
1789 << startSector << " in\norder to align on " << sectorAlignment
1790 << "-sector boundaries.\n";
1791 } // if
srs5694ba00fed2010-01-12 18:18:36 -05001792 if (IsFree(startSector) && (startSector <= endSector)) {
1793 if (FindLastInFree(startSector) >= endSector) {
1794 partitions[partNum].SetFirstLBA(startSector);
1795 partitions[partNum].SetLastLBA(endSector);
srs56940741fa22013-01-09 12:55:40 -05001796 partitions[partNum].SetType(DEFAULT_GPT_TYPE);
srs56946699b012010-02-04 00:55:30 -05001797 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001798 } else retval = 0; // if free space until endSector
1799 } else retval = 0; // if startSector is free
1800 } else retval = 0; // if legal partition number
1801 return retval;
1802} // GPTData::CreatePartition(partNum, startSector, endSector)
1803
srs5694e4ac11e2009-08-31 10:13:04 -04001804// Sort the GPT entries, eliminating gaps and making for a logical
srs56949a46b042011-03-15 00:34:10 -04001805// ordering.
srs5694e4ac11e2009-08-31 10:13:04 -04001806void GPTData::SortGPT(void) {
srs56949a46b042011-03-15 00:34:10 -04001807 if (numParts > 0)
srs569401f7f082011-03-15 23:53:31 -04001808 sort(partitions, partitions + numParts);
srs5694e4ac11e2009-08-31 10:13:04 -04001809} // GPTData::SortGPT()
1810
srs569408bb0da2010-02-19 17:19:55 -05001811// Swap the contents of two partitions.
1812// Returns 1 if successful, 0 if either partition is out of range
1813// (that is, not a legal number; either or both can be empty).
1814// Note that if partNum1 = partNum2 and this number is in range,
1815// it will be considered successful.
1816int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1817 GPTPart temp;
1818 int allOK = 1;
1819
srs56940283dae2010-04-28 16:44:34 -04001820 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001821 if (partNum1 != partNum2) {
1822 temp = partitions[partNum1];
1823 partitions[partNum1] = partitions[partNum2];
1824 partitions[partNum2] = temp;
1825 } // if
1826 } else allOK = 0; // partition numbers are valid
1827 return allOK;
1828} // GPTData::SwapPartitions()
1829
srs5694e4ac11e2009-08-31 10:13:04 -04001830// Set up data structures for entirely new set of partitions on the
1831// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001832// Note that this function does NOT clear the protectiveMBR data
1833// structure, since it may hold the original MBR partitions if the
1834// program was launched on an MBR disk, and those may need to be
1835// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001836int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001837 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001838
1839 // Set up the partition table....
srs56949a46b042011-03-15 00:34:10 -04001840 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001841 partitions = NULL;
1842 SetGPTSize(NUM_GPT_ENTRIES);
1843
1844 // Now initialize a bunch of stuff that's static....
1845 mainHeader.signature = GPT_SIGNATURE;
1846 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001847 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001848 mainHeader.reserved = 0;
1849 mainHeader.currentLBA = UINT64_C(1);
1850 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1851 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1852 for (i = 0; i < GPT_RESERVED; i++) {
1853 mainHeader.reserved2[i] = '\0';
1854 } // for
srs56940873e9d2010-10-07 13:00:45 -04001855 if (blockSize > 0)
1856 sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1857 else
1858 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001859
1860 // Now some semi-static items (computed based on end of disk)
1861 mainHeader.backupLBA = diskSize - UINT64_C(1);
1862 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1863
1864 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001865 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001866
1867 // Copy main header to backup header
1868 RebuildSecondHeader();
1869
1870 // Blank out the partitions array....
1871 BlankPartitions();
1872
1873 // Flag all CRCs as being OK....
1874 mainCrcOk = 1;
1875 secondCrcOk = 1;
1876 mainPartsCrcOk = 1;
1877 secondPartsCrcOk = 1;
1878
1879 return (goOn);
1880} // GPTData::ClearGPTData()
1881
srs5694247657a2009-11-26 18:36:12 -05001882// Set the location of the second GPT header data to the end of the disk.
srs569464cbd172011-03-01 22:03:54 -05001883// If the disk size has actually changed, this also adjusts the protective
1884// entry in the MBR, since it's probably no longer correct.
srs5694247657a2009-11-26 18:36:12 -05001885// Used internally and called by the 'e' option on the recovery &
1886// transformation menu, to help users of RAID arrays who add disk space
srs569464cbd172011-03-01 22:03:54 -05001887// to their arrays or to adjust data structures in restore operations
1888// involving unequal-sized disks.
srs5694247657a2009-11-26 18:36:12 -05001889void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001890 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
srs569464cbd172011-03-01 22:03:54 -05001891 if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1892 if (protectiveMBR.GetValidity() == hybrid) {
1893 protectiveMBR.OptimizeEESize();
1894 RecomputeCHS();
1895 } // if
1896 if (protectiveMBR.GetValidity() == gpt)
1897 MakeProtectiveMBR();
1898 } // if
srs56948bb78762009-11-24 15:43:49 -05001899 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1900 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1901} // GPTData::FixSecondHeaderLocation()
1902
srs5694699941e2011-03-21 21:33:57 -04001903// Sets the partition's name to the specified UnicodeString without
1904// user interaction.
1905// Returns 1 on success, 0 on failure (invalid partition number).
srs56945a608532011-03-17 13:53:01 -04001906int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001907 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001908
srs5694699941e2011-03-21 21:33:57 -04001909 if (IsUsedPartNum(partNum))
srs5694fed16d02010-01-27 23:03:40 -05001910 partitions[partNum].SetName(theName);
srs5694699941e2011-03-21 21:33:57 -04001911 else
1912 retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001913
1914 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001915} // GPTData::SetName
1916
1917// Set the disk GUID to the specified value. Note that the header CRCs must
1918// be recomputed after calling this function.
1919void GPTData::SetDiskGUID(GUIDData newGUID) {
1920 mainHeader.diskGUID = newGUID;
1921 secondHeader.diskGUID = newGUID;
1922} // SetDiskGUID()
1923
1924// Set the unique GUID of the specified partition. Returns 1 on
1925// successful completion, 0 if there were problems (invalid
1926// partition number).
1927int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1928 int retval = 0;
1929
srs56940283dae2010-04-28 16:44:34 -04001930 if (pn < numParts) {
srs5694e69e6802012-01-20 22:37:12 -05001931 if (partitions[pn].IsUsed()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001932 partitions[pn].SetUniqueGUID(theGUID);
1933 retval = 1;
1934 } // if
1935 } // if
1936 return retval;
1937} // GPTData::SetPartitionGUID()
1938
srs56949ba54212010-05-18 23:24:02 -04001939// Set new random GUIDs for the disk and all partitions. Intended to be used
1940// after disk cloning or similar operations that don't randomize the GUIDs.
1941void GPTData::RandomizeGUIDs(void) {
1942 uint32_t i;
1943
1944 mainHeader.diskGUID.Randomize();
1945 secondHeader.diskGUID = mainHeader.diskGUID;
1946 for (i = 0; i < numParts; i++)
1947 if (partitions[i].IsUsed())
1948 partitions[i].RandomizeUniqueGUID();
1949} // GPTData::RandomizeGUIDs()
1950
srs5694ba00fed2010-01-12 18:18:36 -05001951// Change partition type code non-interactively. Returns 1 if
1952// successful, 0 if not....
srs5694327129e2010-09-22 01:07:31 -04001953int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1954 int retval = 1;
1955
1956 if (!IsFreePartNum(partNum)) {
1957 partitions[partNum].SetType(theGUID);
1958 } else retval = 0;
1959 return retval;
1960} // GPTData::ChangePartType()
1961
srs56949ba54212010-05-18 23:24:02 -04001962// Recompute the CHS values of all the MBR partitions. Used to reset
1963// CHS values that some BIOSes require, despite the fact that the
1964// resulting CHS values violate the GPT standard.
1965void GPTData::RecomputeCHS(void) {
1966 int i;
1967
1968 for (i = 0; i < 4; i++)
1969 protectiveMBR.RecomputeCHS(i);
1970} // GPTData::RecomputeCHS()
1971
srs56941d1448a2009-12-31 21:20:19 -05001972// Adjust sector number so that it falls on a sector boundary that's a
1973// multiple of sectorAlignment. This is done to improve the performance
1974// of Western Digital Advanced Format disks and disks with similar
1975// technology from other companies, which use 4096-byte sectors
1976// internally although they translate to 512-byte sectors for the
1977// benefit of the OS. If partitions aren't properly aligned on these
1978// disks, some filesystem data structures can span multiple physical
1979// sectors, degrading performance. This function should be called
1980// only on the FIRST sector of the partition, not the last!
1981// This function returns 1 if the alignment was altered, 0 if it
1982// was unchanged.
1983int GPTData::Align(uint64_t* sector) {
1984 int retval = 0, sectorOK = 0;
srs569400b6d7a2011-06-26 22:40:06 -04001985 uint64_t earlier, later, testSector;
srs56941d1448a2009-12-31 21:20:19 -05001986
1987 if ((*sector % sectorAlignment) != 0) {
srs56941d1448a2009-12-31 21:20:19 -05001988 earlier = (*sector / sectorAlignment) * sectorAlignment;
1989 later = earlier + (uint64_t) sectorAlignment;
1990
1991 // Check to see that every sector between the earlier one and the
1992 // requested one is clear, and that it's not too early....
1993 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001994 sectorOK = 1;
1995 testSector = earlier;
1996 do {
1997 sectorOK = IsFree(testSector++);
1998 } while ((sectorOK == 1) && (testSector < *sector));
1999 if (sectorOK == 1) {
2000 *sector = earlier;
srs56945a081752010-09-24 20:39:41 -04002001 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05002002 } // if
2003 } // if firstUsableLBA check
2004
2005 // If couldn't move the sector earlier, try to move it later instead....
2006 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2007 sectorOK = 1;
2008 testSector = later;
2009 do {
2010 sectorOK = IsFree(testSector--);
2011 } while ((sectorOK == 1) && (testSector > *sector));
2012 if (sectorOK == 1) {
2013 *sector = later;
srs56945a081752010-09-24 20:39:41 -04002014 retval = 1;
srs56941d1448a2009-12-31 21:20:19 -05002015 } // if
2016 } // if
srs56941d1448a2009-12-31 21:20:19 -05002017 } // if
2018 return retval;
2019} // GPTData::Align()
2020
srs5694e4ac11e2009-08-31 10:13:04 -04002021/********************************************************
2022 * *
2023 * Functions that return data about GPT data structures *
2024 * (most of these are inline in gpt.h) *
2025 * *
2026 ********************************************************/
2027
2028// Find the low and high used partition numbers (numbered from 0).
2029// Return value is the number of partitions found. Note that the
2030// *low and *high values are both set to 0 when no partitions
2031// are found, as well as when a single partition in the first
2032// position exists. Thus, the return value is the only way to
2033// tell when no partitions exist.
2034int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2035 uint32_t i;
2036 int numFound = 0;
2037
srs56940283dae2010-04-28 16:44:34 -04002038 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04002039 *high = 0;
srs56949a46b042011-03-15 00:34:10 -04002040 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002041 if (partitions[i].IsUsed()) { // it exists
srs56949a46b042011-03-15 00:34:10 -04002042 *high = i; // since we're counting up, set the high value
2043 // Set the low value only if it's not yet found...
2044 if (*low == (numParts + 1)) *low = i;
2045 numFound++;
2046 } // if
2047 } // for
srs5694e4ac11e2009-08-31 10:13:04 -04002048
2049 // Above will leave *low pointing to its "not found" value if no partitions
2050 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04002051 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04002052 *low = 0;
2053 return numFound;
2054} // GPTData::GetPartRange()
2055
srs569408bb0da2010-02-19 17:19:55 -05002056// Returns the value of the first free partition, or -1 if none is
2057// unused.
2058int GPTData::FindFirstFreePart(void) {
2059 int i = 0;
2060
2061 if (partitions != NULL) {
srs56949a46b042011-03-15 00:34:10 -04002062 while ((i < (int) numParts) && (partitions[i].IsUsed()))
srs569408bb0da2010-02-19 17:19:55 -05002063 i++;
srs56940283dae2010-04-28 16:44:34 -04002064 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05002065 i = -1;
2066 } else i = -1;
2067 return i;
2068} // GPTData::FindFirstFreePart()
2069
srs5694978041c2009-09-21 20:51:47 -04002070// Returns the number of defined partitions.
2071uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05002072 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04002073
srs56940283dae2010-04-28 16:44:34 -04002074 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05002075 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04002076 counted++;
2077 } // for
2078 return counted;
2079} // GPTData::CountParts()
2080
srs5694e4ac11e2009-08-31 10:13:04 -04002081/****************************************************
2082 * *
2083 * Functions that return data about disk free space *
2084 * *
2085 ****************************************************/
2086
2087// Find the first available block after the starting point; returns 0 if
2088// there are no available blocks left
2089uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2090 uint64_t first;
2091 uint32_t i;
2092 int firstMoved = 0;
2093
2094 // Begin from the specified starting point or from the first usable
2095 // LBA, whichever is greater...
2096 if (start < mainHeader.firstUsableLBA)
2097 first = mainHeader.firstUsableLBA;
2098 else
2099 first = start;
2100
2101 // ...now search through all partitions; if first is within an
2102 // existing partition, move it to the next sector after that
2103 // partition and repeat. If first was moved, set firstMoved
2104 // flag; repeat until firstMoved is not set, so as to catch
2105 // cases where partitions are out of sequential order....
2106 do {
2107 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002108 for (i = 0; i < numParts; i++) {
srs5694e69e6802012-01-20 22:37:12 -05002109 if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002110 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002111 first = partitions[i].GetLastLBA() + 1;
2112 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002113 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002114 } // for
2115 } while (firstMoved == 1);
2116 if (first > mainHeader.lastUsableLBA)
2117 first = 0;
2118 return (first);
2119} // GPTData::FindFirstAvailable()
2120
2121// Finds the first available sector in the largest block of unallocated
2122// space on the disk. Returns 0 if there are no available blocks left
2123uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002124 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002125
2126 start = 0;
2127 do {
2128 firstBlock = FindFirstAvailable(start);
2129 if (firstBlock != UINT32_C(0)) { // something's free...
2130 lastBlock = FindLastInFree(firstBlock);
2131 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2132 if (segmentSize > selectedSize) {
2133 selectedSize = segmentSize;
2134 selectedSegment = firstBlock;
2135 } // if
2136 start = lastBlock + 1;
2137 } // if
2138 } while (firstBlock != 0);
2139 return selectedSegment;
2140} // GPTData::FindFirstInLargest()
2141
srs5694cb76c672010-02-11 22:22:22 -05002142// Find the last available block on the disk.
srs5694f5dfbfa2013-02-14 20:47:14 -05002143// Returns 0 if there are no available sectors
srs5694cb76c672010-02-11 22:22:22 -05002144uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002145 uint64_t last;
2146 uint32_t i;
2147 int lastMoved = 0;
2148
2149 // Start by assuming the last usable LBA is available....
2150 last = mainHeader.lastUsableLBA;
2151
2152 // ...now, similar to algorithm in FindFirstAvailable(), search
2153 // through all partitions, moving last when it's in an existing
2154 // partition. Set the lastMoved flag so we repeat to catch cases
2155 // where partitions are out of logical order.
2156 do {
2157 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002158 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002159 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002160 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002161 last = partitions[i].GetFirstLBA() - 1;
2162 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002163 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002164 } // for
2165 } while (lastMoved == 1);
2166 if (last < mainHeader.firstUsableLBA)
2167 last = 0;
2168 return (last);
2169} // GPTData::FindLastAvailable()
2170
2171// Find the last available block in the free space pointed to by start.
2172uint64_t GPTData::FindLastInFree(uint64_t start) {
2173 uint64_t nearestStart;
2174 uint32_t i;
2175
2176 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002177 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002178 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002179 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002180 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002181 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002182 } // for
2183 return (nearestStart);
2184} // GPTData::FindLastInFree()
2185
2186// Finds the total number of free blocks, the number of segments in which
2187// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002188uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002189 uint64_t start = UINT64_C(0); // starting point for each search
2190 uint64_t totalFound = UINT64_C(0); // running total
2191 uint64_t firstBlock; // first block in a segment
2192 uint64_t lastBlock; // last block in a segment
2193 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002194 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002195
2196 *largestSegment = UINT64_C(0);
srs5694c54e9b42010-05-01 21:04:23 -04002197 if (diskSize > 0) {
2198 do {
2199 firstBlock = FindFirstAvailable(start);
2200 if (firstBlock != UINT64_C(0)) { // something's free...
2201 lastBlock = FindLastInFree(firstBlock);
2202 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2203 if (segmentSize > *largestSegment) {
2204 *largestSegment = segmentSize;
2205 } // if
2206 totalFound += segmentSize;
2207 num++;
2208 start = lastBlock + 1;
srs5694e4ac11e2009-08-31 10:13:04 -04002209 } // if
srs5694c54e9b42010-05-01 21:04:23 -04002210 } while (firstBlock != 0);
2211 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002212 *numSegments = num;
2213 return totalFound;
2214} // GPTData::FindFreeBlocks()
2215
srs569455d92612010-03-07 22:16:07 -05002216// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2217// If it's allocated, return the partition number to which it's allocated
2218// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2219// returned in partNum if the sector is in use by basic GPT data structures.)
2220int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002221 int isFree = 1;
2222 uint32_t i;
2223
srs56940283dae2010-04-28 16:44:34 -04002224 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002225 if ((sector >= partitions[i].GetFirstLBA()) &&
2226 (sector <= partitions[i].GetLastLBA())) {
2227 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002228 if (partNum != NULL)
2229 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002230 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002231 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002232 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002233 (sector > mainHeader.lastUsableLBA)) {
2234 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002235 if (partNum != NULL)
2236 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002237 } // if
2238 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002239} // GPTData::IsFree()
2240
srs5694815fb652011-03-18 12:35:56 -04002241// Returns 1 if partNum is unused AND if it's a legal value.
srs5694ba00fed2010-01-12 18:18:36 -05002242int GPTData::IsFreePartNum(uint32_t partNum) {
srs569401f7f082011-03-15 23:53:31 -04002243 return ((partNum < numParts) && (partitions != NULL) &&
2244 (!partitions[partNum].IsUsed()));
srs5694ba00fed2010-01-12 18:18:36 -05002245} // GPTData::IsFreePartNum()
2246
srs5694815fb652011-03-18 12:35:56 -04002247// Returns 1 if partNum is in use.
2248int GPTData::IsUsedPartNum(uint32_t partNum) {
2249 return ((partNum < numParts) && (partitions != NULL) &&
2250 (partitions[partNum].IsUsed()));
2251} // GPTData::IsUsedPartNum()
srs5694a8582cf2010-03-19 14:21:59 -04002252
2253/***********************************************************
2254 * *
2255 * Change how functions work or return information on them *
2256 * *
2257 ***********************************************************/
2258
2259// Set partition alignment value; partitions will begin on multiples of
2260// the specified value
2261void GPTData::SetAlignment(uint32_t n) {
srs56940873e9d2010-10-07 13:00:45 -04002262 if (n > 0)
2263 sectorAlignment = n;
2264 else
2265 cerr << "Attempt to set partition alignment to 0!\n";
srs5694a8582cf2010-03-19 14:21:59 -04002266} // GPTData::SetAlignment()
2267
2268// Compute sector alignment based on the current partitions (if any). Each
2269// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56940873e9d2010-10-07 13:00:45 -04002270// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2271// sector size), but not by the previously-located alignment value, then the
2272// alignment value is adjusted down. If the computed alignment is less than 8
2273// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
srs5694d8eed462012-12-15 01:55:21 -05002274// is a safety measure for Advanced Format drives. If no partitions are
2275// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
srs56940873e9d2010-10-07 13:00:45 -04002276// adjustment of that based on the current sector size). The result is that new
srs56948a4ddfc2010-03-21 19:05:49 -04002277// drives are aligned to 2048-sector multiples but the program won't complain
2278// about other alignments on existing disks unless a smaller-than-8 alignment
srs5694d8eed462012-12-15 01:55:21 -05002279// is used on big disks (as safety for Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002280// Returns the computed alignment value.
2281uint32_t GPTData::ComputeAlignment(void) {
2282 uint32_t i = 0, found, exponent = 31;
srs5694ab4b0432010-09-25 20:39:52 -04002283 uint32_t align = DEFAULT_ALIGNMENT;
srs5694a8582cf2010-03-19 14:21:59 -04002284
srs56940873e9d2010-10-07 13:00:45 -04002285 if (blockSize > 0)
2286 align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2287 exponent = (uint32_t) log2(align);
srs56940283dae2010-04-28 16:44:34 -04002288 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002289 if (partitions[i].IsUsed()) {
2290 found = 0;
2291 while (!found) {
srs56940873e9d2010-10-07 13:00:45 -04002292 align = UINT64_C(1) << exponent;
srs5694a8582cf2010-03-19 14:21:59 -04002293 if ((partitions[i].GetFirstLBA() % align) == 0) {
2294 found = 1;
2295 } else {
2296 exponent--;
2297 } // if/else
2298 } // while
2299 } // if
2300 } // for
srs56940873e9d2010-10-07 13:00:45 -04002301 if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2302 align = MIN_AF_ALIGNMENT;
2303 sectorAlignment = align;
srs5694a8582cf2010-03-19 14:21:59 -04002304 return align;
2305} // GPTData::ComputeAlignment()
2306
srs5694e4ac11e2009-08-31 10:13:04 -04002307/********************************
2308 * *
2309 * Endianness support functions *
2310 * *
2311 ********************************/
2312
srs56942a9f5da2009-08-26 00:48:01 -04002313void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002314 ReverseBytes(&header->signature, 8);
2315 ReverseBytes(&header->revision, 4);
2316 ReverseBytes(&header->headerSize, 4);
2317 ReverseBytes(&header->headerCRC, 4);
2318 ReverseBytes(&header->reserved, 4);
2319 ReverseBytes(&header->currentLBA, 8);
2320 ReverseBytes(&header->backupLBA, 8);
2321 ReverseBytes(&header->firstUsableLBA, 8);
2322 ReverseBytes(&header->lastUsableLBA, 8);
2323 ReverseBytes(&header->partitionEntriesLBA, 8);
2324 ReverseBytes(&header->numParts, 4);
2325 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2326 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002327 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002328} // GPTData::ReverseHeaderBytes()
2329
srs56940283dae2010-04-28 16:44:34 -04002330// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002331void GPTData::ReversePartitionBytes() {
2332 uint32_t i;
2333
srs56940283dae2010-04-28 16:44:34 -04002334 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002335 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002336 } // for
2337} // GPTData::ReversePartitionBytes()
2338
srs56949ddc14b2010-08-22 22:44:42 -04002339// Validate partition number
2340bool GPTData::ValidPartNum (const uint32_t partNum) {
2341 if (partNum >= numParts) {
srs56945a081752010-09-24 20:39:41 -04002342 cerr << "Partition number out of range: " << partNum << "\n";
srs56949ddc14b2010-08-22 22:44:42 -04002343 return false;
2344 } // if
2345 return true;
2346} // GPTData::ValidPartNum
2347
srs56945a081752010-09-24 20:39:41 -04002348// Return a single partition for inspection (not modification!) by other
2349// functions.
2350const GPTPart & GPTData::operator[](uint32_t partNum) const {
2351 if (partNum >= numParts) {
srs5694815fb652011-03-18 12:35:56 -04002352 cerr << "Partition number out of range (" << partNum << " requested, but only "
2353 << numParts << " available)\n";
2354 exit(1);
2355 } // if
2356 if (partitions == NULL) {
2357 cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2358 exit(1);
srs56945a081752010-09-24 20:39:41 -04002359 } // if
2360 return partitions[partNum];
2361} // operator[]
2362
2363// Return (not for modification!) the disk's GUID value
2364const GUIDData & GPTData::GetDiskGUID(void) const {
2365 return mainHeader.diskGUID;
2366} // GPTData::GetDiskGUID()
2367
srs56949ddc14b2010-08-22 22:44:42 -04002368// Manage attributes for a partition, based on commands passed to this function.
2369// (Function is non-interactive.)
2370// Returns 1 if a modification command succeeded, 0 if the command should not have
2371// modified data, and -1 if a modification command failed.
2372int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2373 int retval = 0;
2374 Attributes theAttr;
2375
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002376 if (partNum >= (int) numParts) {
2377 cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2378 retval = -1;
srs56949ddc14b2010-08-22 22:44:42 -04002379 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002380 if (command == "show") {
2381 ShowAttributes(partNum);
2382 } else if (command == "get") {
2383 GetAttribute(partNum, bits);
srs56949ddc14b2010-08-22 22:44:42 -04002384 } else {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002385 theAttr = partitions[partNum].GetAttributes();
2386 if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2387 partitions[partNum].SetAttributes(theAttr.GetAttributes());
2388 retval = 1;
2389 } else {
2390 retval = -1;
2391 } // if/else
2392 } // if/elseif/else
2393 } // if/else invalid partition #
srs56949ddc14b2010-08-22 22:44:42 -04002394
2395 return retval;
2396} // GPTData::ManageAttributes()
2397
2398// Show all attributes for a specified partition....
2399void GPTData::ShowAttributes(const uint32_t partNum) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002400 if ((partNum < numParts) && partitions[partNum].IsUsed())
srs5694e69e6802012-01-20 22:37:12 -05002401 partitions[partNum].ShowAttributes(partNum);
srs56949ddc14b2010-08-22 22:44:42 -04002402} // GPTData::ShowAttributes
2403
2404// Show whether a single attribute bit is set (terse output)...
2405void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
Roderick W. Smith24bba6e2013-10-12 19:07:16 -04002406 if (partNum < numParts)
2407 partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
srs56949ddc14b2010-08-22 22:44:42 -04002408} // GPTData::GetAttribute
2409
2410
srs56942a9f5da2009-08-26 00:48:01 -04002411/******************************************
2412 * *
2413 * Additional non-class support functions *
2414 * *
2415 ******************************************/
2416
srs5694e7b4ff92009-08-18 13:16:10 -04002417// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2418// never fail these tests, but the struct types may fail depending on compile options.
2419// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2420// sizes.
2421int SizesOK(void) {
2422 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002423
2424 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002425 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002426 allOK = 0;
2427 } // if
2428 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002429 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002430 allOK = 0;
2431 } // if
2432 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002433 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002434 allOK = 0;
2435 } // if
2436 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002437 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002438 allOK = 0;
2439 } // if
2440 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002441 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002442 allOK = 0;
2443 } // if
srs5694978041c2009-09-21 20:51:47 -04002444 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002445 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002446 allOK = 0;
2447 } // if
2448 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002449 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002450 allOK = 0;
2451 } // if
srs5694221e0872009-08-29 15:00:31 -04002452 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002453 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002454 allOK = 0;
2455 } // if
srs56946699b012010-02-04 00:55:30 -05002456 if (sizeof(GUIDData) != 16) {
2457 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2458 allOK = 0;
2459 } // if
2460 if (sizeof(PartType) != 16) {
Roderick W. Smith84aaff62014-02-17 16:17:11 -05002461 cerr << "PartType is " << sizeof(PartType) << " bytes, should be 16 bytes; aborting!\n";
srs56946699b012010-02-04 00:55:30 -05002462 allOK = 0;
2463 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04002464 return (allOK);
2465} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002466