blob: 12aece13c34e544ad2f6c0b3d9f684ad60597704 [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
srs5694221e0872009-08-29 15:00:31 -04006/* This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
7 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040013#include <stdlib.h>
14#include <stdint.h>
15#include <fcntl.h>
16#include <string.h>
srs5694a8582cf2010-03-19 14:21:59 -040017#include <math.h>
srs5694e7b4ff92009-08-18 13:16:10 -040018#include <time.h>
19#include <sys/stat.h>
20#include <errno.h>
srs5694fed16d02010-01-27 23:03:40 -050021#include <iostream>
srs5694e7b4ff92009-08-18 13:16:10 -040022#include "crc32.h"
23#include "gpt.h"
srs5694221e0872009-08-29 15:00:31 -040024#include "bsd.h"
srs5694e7b4ff92009-08-18 13:16:10 -040025#include "support.h"
26#include "parttypes.h"
27#include "attributes.h"
srs5694546a9c72010-01-26 16:00:26 -050028#include "diskio.h"
srs569455d92612010-03-07 22:16:07 -050029#include "partnotes.h"
srs5694e7b4ff92009-08-18 13:16:10 -040030
31using namespace std;
32
33/****************************************
34 * *
35 * GPTData class and related structures *
36 * *
37 ****************************************/
38
srs5694e4ac11e2009-08-31 10:13:04 -040039// Default constructor
srs5694e7b4ff92009-08-18 13:16:10 -040040GPTData::GPTData(void) {
41 blockSize = SECTOR_SIZE; // set a default
42 diskSize = 0;
43 partitions = NULL;
44 state = gpt_valid;
srs5694fed16d02010-01-27 23:03:40 -050045 device = "";
srs56945d58fe02010-01-03 20:57:08 -050046 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040047 mainCrcOk = 0;
48 secondCrcOk = 0;
49 mainPartsCrcOk = 0;
50 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040051 apmFound = 0;
52 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050053 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050054 beQuiet = 0;
55 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040056 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050057 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040058 numParts = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040059 SetGPTSize(NUM_GPT_ENTRIES);
60} // GPTData default constructor
61
62// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050063GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040064 blockSize = SECTOR_SIZE; // set a default
65 diskSize = 0;
66 partitions = NULL;
67 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050068 device = "";
srs56945d58fe02010-01-03 20:57:08 -050069 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040070 mainCrcOk = 0;
71 secondCrcOk = 0;
72 mainPartsCrcOk = 0;
73 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040074 apmFound = 0;
75 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050076 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050077 beQuiet = 0;
78 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040079 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050080 mainHeader.numParts = 0;
srs56940283dae2010-04-28 16:44:34 -040081 numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050082 if (!LoadPartitions(filename))
83 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050084} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040085
srs5694e4ac11e2009-08-31 10:13:04 -040086// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040087GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050088 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040089} // GPTData destructor
90
srs5694e4ac11e2009-08-31 10:13:04 -040091/*********************************************************************
92 * *
93 * Begin functions that verify data, or that adjust the verification *
94 * information (compute CRCs, rebuild headers) *
95 * *
96 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040097
srs5694e4ac11e2009-08-31 10:13:04 -040098// Perform detailed verification, reporting on any problems found, but
99// do *NOT* recover from these problems. Returns the total number of
100// problems identified.
101int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -0500102 int problems = 0;
103 uint32_t i, numSegments;
104 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400105
106 // First, check for CRC errors in the GPT data....
107 if (!mainCrcOk) {
108 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500109 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
110 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
111 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
112 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400113 } // if
114 if (!mainPartsCrcOk) {
115 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500116 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
117 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
118 << "transformation menu). This report may be a false alarm if you've already\n"
119 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400120 } // if
121 if (!secondCrcOk) {
122 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500123 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
124 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
125 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
126 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400127 } // if
128 if (!secondPartsCrcOk) {
129 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500130 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
131 << "be corrupt. This program will automatically create a new backup partition\n"
132 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400133 } // if
134
srs5694978041c2009-09-21 20:51:47 -0400135 // Now check that the main and backup headers both point to themselves....
136 if (mainHeader.currentLBA != 1) {
137 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500138 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
139 << "is being automatically corrected, but it may be a symptom of more serious\n"
140 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400141 mainHeader.currentLBA = 1;
142 } // if
143 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
144 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500145 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
146 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
147 << "option on the experts' menu to adjust the secondary header's and partition\n"
148 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400149 } // if
150
151 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400152 if (mainHeader.currentLBA != secondHeader.backupLBA) {
153 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500154 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
155 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
156 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400157 } // if
158 if (mainHeader.backupLBA != secondHeader.currentLBA) {
159 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500160 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
161 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
162 << secondHeader.currentLBA << ").\n"
163 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400164 } // if
165 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
166 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500167 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
168 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
169 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400170 } // if
171 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
172 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500173 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
174 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
175 << secondHeader.lastUsableLBA << ")\n"
176 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400177 } // if
srs56946699b012010-02-04 00:55:30 -0500178 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400179 problems++;
srs56946699b012010-02-04 00:55:30 -0500180 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500181 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500182 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500183 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
184 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400185 } // if
186 if (mainHeader.numParts != secondHeader.numParts) {
187 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500188 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
189 << ") doesn't\nmatch the backup GPT header's number of partitions ("
190 << secondHeader.numParts << ")\n"
191 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400192 } // if
193 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
194 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500195 cout << "\nProblem: main GPT header's size of partition entries ("
196 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
197 << "match the backup GPT header's size of partition entries ("
198 << secondHeader.sizeOfPartitionEntries << ")\n"
199 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
200 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400201 } // if
202
203 // Now check for a few other miscellaneous problems...
204 // Check that the disk size will hold the data...
205 if (mainHeader.backupLBA > diskSize) {
206 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500207 cout << "\nProblem: Disk is too small to hold all the data!\n"
208 << "(Disk size is " << diskSize << " sectors, needs to be "
209 << mainHeader.backupLBA << " sectors.)\n"
210 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400211 } // if
212
213 // Check for overlapping partitions....
214 problems += FindOverlaps();
215
srs569455d92612010-03-07 22:16:07 -0500216 // Check for insane partitions (start after end, hugely big, etc.)
217 problems += FindInsanePartitions();
218
srs5694e4ac11e2009-08-31 10:13:04 -0400219 // Check for mismatched MBR and GPT partitions...
220 problems += FindHybridMismatches();
221
222 // Verify that partitions don't run into GPT data areas....
223 problems += CheckGPTSize();
224
srs56941d1448a2009-12-31 21:20:19 -0500225 // Check that partitions are aligned on proper boundaries (for WD Advanced
226 // Format and similar disks)....
srs56940283dae2010-04-28 16:44:34 -0400227 for (i = 0; i < numParts; i++) {
srs56941d1448a2009-12-31 21:20:19 -0500228 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500229 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
230 << sectorAlignment << "-sector boundary. This may\nresult "
231 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500232 } // if
233 } // for
234
srs5694e4ac11e2009-08-31 10:13:04 -0400235 // Now compute available space, but only if no problems found, since
236 // problems could affect the results
237 if (problems == 0) {
238 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500239 cout << "No problems found. " << totalFree << " free sectors ("
240 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
241 << numSegments << "\nsegments, the largest of which is "
242 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
srs56940283dae2010-04-28 16:44:34 -0400243 << ") in size.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400244 } else {
srs56940a697312010-01-28 21:10:52 -0500245 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400246 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400247
248 return (problems);
249} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400250
251// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400252// do, issues a warning but takes no action. Returns number of problems
253// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400254int GPTData::CheckGPTSize(void) {
255 uint64_t overlap, firstUsedBlock, lastUsedBlock;
256 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400257 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400258
259 // first, locate the first & last used blocks
260 firstUsedBlock = UINT64_MAX;
261 lastUsedBlock = 0;
srs56940283dae2010-04-28 16:44:34 -0400262 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400263 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400264 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400265 firstUsedBlock = partitions[i].GetFirstLBA();
266 if (partitions[i].GetLastLBA() > lastUsedBlock)
267 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400268 } // for
269
270 // If the disk size is 0 (the default), then it means that various
271 // variables aren't yet set, so the below tests will be useless;
272 // therefore we should skip everything
273 if (diskSize != 0) {
274 if (mainHeader.firstUsableLBA > firstUsedBlock) {
275 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500276 cout << "Warning! Main partition table overlaps the first partition by "
277 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400278 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500279 cout << "Try reducing the partition table size by " << overlap * 4
280 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400281 } else {
srs5694fed16d02010-01-27 23:03:40 -0500282 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400283 } // if/else
284 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400285 } // Problem at start of disk
286 if (mainHeader.lastUsableLBA < lastUsedBlock) {
287 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500288 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500289 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400290 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500291 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400292 } else {
srs5694fed16d02010-01-27 23:03:40 -0500293 cout << "Try reducing the partition table size by " << overlap * 4
294 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400295 } // if/else
296 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400297 } // Problem at end of disk
298 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400299 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400300} // GPTData::CheckGPTSize()
301
srs5694e7b4ff92009-08-18 13:16:10 -0400302// Check the validity of the GPT header. Returns 1 if the main header
303// is valid, 2 if the backup header is valid, 3 if both are valid, and
304// 0 if neither is valid. Note that this function just checks the GPT
305// signature and revision numbers, not CRCs or other data.
306int GPTData::CheckHeaderValidity(void) {
307 int valid = 3;
308
srs5694fed16d02010-01-27 23:03:40 -0500309 cout.setf(ios::uppercase);
310 cout.fill('0');
311
312 // Note: failed GPT signature checks produce no error message because
313 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400314 if (mainHeader.signature != GPT_SIGNATURE) {
315 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400316 } else if ((mainHeader.revision != 0x00010000) && valid) {
317 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500318 cout << "Unsupported GPT version in main header; read 0x";
319 cout.width(8);
320 cout << hex << mainHeader.revision << ", should be\n0x";
321 cout.width(8);
322 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400323 } // if/else/if
324
325 if (secondHeader.signature != GPT_SIGNATURE) {
326 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400327 } else if ((secondHeader.revision != 0x00010000) && valid) {
328 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500329 cout << "Unsupported GPT version in backup header; read 0x";
330 cout.width(8);
331 cout << hex << secondHeader.revision << ", should be\n0x";
332 cout.width(8);
333 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400334 } // if/else/if
335
srs56942a9f5da2009-08-26 00:48:01 -0400336 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400337 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400338 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400339 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400340 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500341 } // if
srs5694fed16d02010-01-27 23:03:40 -0500342 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400343
srs5694fed16d02010-01-27 23:03:40 -0500344 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400345} // GPTData::CheckHeaderValidity()
346
347// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500348// Note: Must be called with header in LITTLE-ENDIAN
349// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400350int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400351 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400352
srs56942a9f5da2009-08-26 00:48:01 -0400353 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400354 // computation to be valid
355 oldCRC = header->headerCRC;
356 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400357 hSize = header->headerSize;
358
359 // If big-endian system, reverse byte order
360 if (IsLittleEndian() == 0) {
361 ReverseBytes(&oldCRC, 4);
362 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400363
364 // Initialize CRC functions...
365 chksum_crc32gentab();
366
367 // Compute CRC, restore original, and return result of comparison
368 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400369 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400370 return (oldCRC == newCRC);
371} // GPTData::CheckHeaderCRC()
372
srs56946699b012010-02-04 00:55:30 -0500373// Recompute all the CRCs. Must be called before saving if any changes have
374// been made. Must be called on platform-ordered data (this function reverses
375// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400376void GPTData::RecomputeCRCs(void) {
srs56940283dae2010-04-28 16:44:34 -0400377 uint32_t crc, hSize;
srs56942a9f5da2009-08-26 00:48:01 -0400378 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400379
380 // Initialize CRC functions...
381 chksum_crc32gentab();
382
srs56946699b012010-02-04 00:55:30 -0500383 // Save some key data from header before reversing byte order....
srs5694978041c2009-09-21 20:51:47 -0400384 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500385
386 if ((littleEndian = IsLittleEndian()) == 0) {
387 ReversePartitionBytes();
388 ReverseHeaderBytes(&mainHeader);
389 ReverseHeaderBytes(&secondHeader);
390 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400391
srs5694e7b4ff92009-08-18 13:16:10 -0400392 // Compute CRC of partition tables & store in main and secondary headers
srs56940283dae2010-04-28 16:44:34 -0400393 crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400394 mainHeader.partitionEntriesCRC = crc;
395 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400396 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400397 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
398 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400399 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400400
401 // Zero out GPT tables' own CRCs (required for correct computation)
402 mainHeader.headerCRC = 0;
403 secondHeader.headerCRC = 0;
404
405 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400406 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400407 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400408 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400409 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400410 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400411 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400412 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400413 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500414
415 if ((littleEndian = IsLittleEndian()) == 0) {
416 ReverseHeaderBytes(&mainHeader);
417 ReverseHeaderBytes(&secondHeader);
418 ReversePartitionBytes();
419 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400420} // GPTData::RecomputeCRCs()
421
srs5694e7b4ff92009-08-18 13:16:10 -0400422// Rebuild the main GPT header, using the secondary header as a model.
423// Typically called when the main header has been found to be corrupt.
424void GPTData::RebuildMainHeader(void) {
425 int i;
426
427 mainHeader.signature = GPT_SIGNATURE;
428 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400429 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400430 mainHeader.headerCRC = UINT32_C(0);
431 mainHeader.reserved = secondHeader.reserved;
432 mainHeader.currentLBA = secondHeader.backupLBA;
433 mainHeader.backupLBA = secondHeader.currentLBA;
434 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
435 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500436 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400437 mainHeader.partitionEntriesLBA = UINT64_C(2);
438 mainHeader.numParts = secondHeader.numParts;
439 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
440 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
441 for (i = 0 ; i < GPT_RESERVED; i++)
442 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500443 mainCrcOk = secondCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400444 SetGPTSize(mainHeader.numParts);
srs5694e7b4ff92009-08-18 13:16:10 -0400445} // GPTData::RebuildMainHeader()
446
447// Rebuild the secondary GPT header, using the main header as a model.
448void GPTData::RebuildSecondHeader(void) {
449 int i;
450
451 secondHeader.signature = GPT_SIGNATURE;
452 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400453 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400454 secondHeader.headerCRC = UINT32_C(0);
455 secondHeader.reserved = mainHeader.reserved;
456 secondHeader.currentLBA = mainHeader.backupLBA;
457 secondHeader.backupLBA = mainHeader.currentLBA;
458 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
459 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500460 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400461 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
462 secondHeader.numParts = mainHeader.numParts;
463 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
464 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
465 for (i = 0 ; i < GPT_RESERVED; i++)
466 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500467 secondCrcOk = mainCrcOk;
srs56940283dae2010-04-28 16:44:34 -0400468 SetGPTSize(secondHeader.numParts);
srs5694e4ac11e2009-08-31 10:13:04 -0400469} // GPTData::RebuildSecondHeader()
470
471// Search for hybrid MBR entries that have no corresponding GPT partition.
472// Returns number of such mismatches found
473int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500474 int i, found, numFound = 0;
475 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400476 uint64_t mbrFirst, mbrLast;
477
478 for (i = 0; i < 4; i++) {
479 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
480 j = 0;
481 found = 0;
482 do {
483 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
484 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
485 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
486 (partitions[j].GetLastLBA() == mbrLast))
487 found = 1;
488 j++;
srs56940283dae2010-04-28 16:44:34 -0400489 } while ((!found) && (j < numParts));
srs5694e4ac11e2009-08-31 10:13:04 -0400490 if (!found) {
491 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500492 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
493 << i + 1 << ", of type 0x";
494 cout.fill('0');
495 cout.setf(ios::uppercase);
496 cout.width(2);
497 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
498 << "has no corresponding GPT partition! You may continue, but this condition\n"
499 << "might cause data loss in the future!\a\n" << dec;
500 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400501 } // if
502 } // if
503 } // for
504 return numFound;
505} // GPTData::FindHybridMismatches
506
507// Find overlapping partitions and warn user about them. Returns number of
508// overlapping partitions.
509int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500510 int problems = 0;
511 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400512
srs56940283dae2010-04-28 16:44:34 -0400513 for (i = 1; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -0400514 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500515 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400516 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500517 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
518 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
519 << " to " << partitions[i].GetLastLBA() << "\n";
520 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
521 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400522 } // if
523 } // for j...
524 } // for i...
525 return problems;
526} // GPTData::FindOverlaps()
527
srs569455d92612010-03-07 22:16:07 -0500528// Find partitions that are insane -- they start after they end or are too
529// big for the disk. (The latter should duplicate detection of overlaps
530// with GPT backup data structures, but better to err on the side of
531// redundant tests than to miss something....)
532int GPTData::FindInsanePartitions(void) {
533 uint32_t i;
534 int problems = 0;
535
srs56940283dae2010-04-28 16:44:34 -0400536 for (i = 0; i < numParts; i++) {
srs569455d92612010-03-07 22:16:07 -0500537 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
538 problems++;
srs56940283dae2010-04-28 16:44:34 -0400539 cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
srs569455d92612010-03-07 22:16:07 -0500540 } // if
541 if (partitions[i].GetLastLBA() >= diskSize) {
542 problems++;
srs56940283dae2010-04-28 16:44:34 -0400543 cout << "\nProblem: partition " << i + 1<< " is too big for the disk.\n";
srs569455d92612010-03-07 22:16:07 -0500544 } // if
545 } // for
546 return problems;
547} // GPTData::FindInsanePartitions(void)
548
549
srs5694e4ac11e2009-08-31 10:13:04 -0400550/******************************************************************
551 * *
552 * Begin functions that load data from disk or save data to disk. *
553 * *
554 ******************************************************************/
555
556// Scan for partition data. This function loads the MBR data (regular MBR or
557// protective MBR) and loads BSD disklabel data (which is probably invalid).
558// It also looks for APM data, forces a load of GPT data, and summarizes
559// the results.
srs5694546a9c72010-01-26 16:00:26 -0500560void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400561 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400562
563 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500564 protectiveMBR.ReadMBRData(&myDisk);
565 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400566
567 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500568 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500569
570 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500571 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500572 protectiveMBR.ShowState();
573 bsdDisklabel.ShowState();
574 ShowAPMState(); // Show whether there's an Apple Partition Map present
575 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500576 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500577 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400578
579 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500580 cout << "\n*******************************************************************\n"
581 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500582 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500583 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500584 } // if
srs5694fed16d02010-01-27 23:03:40 -0500585 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400586 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400587} // GPTData::PartitionScan()
588
589// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500590int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500591 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500592 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500593 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400594
srs5694546a9c72010-01-26 16:00:26 -0500595 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500596 err = myDisk.OpenForWrite(deviceFilename);
597 if ((err == 0) && (!justLooking)) {
598 cout << "\aNOTE: Write test failed with error number " << errno
599 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
600#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
601 cout << "You may be able to enable writes by exiting this program, typing\n"
602 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
603 << "program.\n";
604#endif
605 cout << "\n";
606 } // if
607 myDisk.Close(); // Close and re-open read-only in case of bugs
608 } else allOK = 0; // if
609
610 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400611 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500612 diskSize = myDisk.DiskSize(&err);
613 blockSize = (uint32_t) myDisk.GetBlockSize();
srs5694fed16d02010-01-27 23:03:40 -0500614 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500615 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400616
srs5694ba00fed2010-01-12 18:18:36 -0500617 whichWasUsed = UseWhichPartitions();
618 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400619 case use_mbr:
620 XFormPartitions();
621 break;
622 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500623 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400624// bsdDisklabel.DisplayBSDData();
625 ClearGPTData();
626 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500627 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400628 break;
629 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500630 mbrState = protectiveMBR.GetValidity();
631 if ((mbrState == invalid) || (mbrState == mbr))
632 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400633 break;
634 case use_new:
635 ClearGPTData();
636 protectiveMBR.MakeProtectiveMBR();
637 break;
srs56943c0af382010-01-15 19:19:18 -0500638 case use_abort:
639 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500640 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500641 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400642 } // switch
643
srs569455d92612010-03-07 22:16:07 -0500644 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500645 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500646 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400647 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400648 } else {
649 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400650 } // if/else
651 return (allOK);
652} // GPTData::LoadPartitions()
653
654// Loads the GPT, as much as possible. Returns 1 if this seems to have
655// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500656int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500657 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400658
srs5694cb76c672010-02-11 22:22:22 -0500659 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400660
srs5694cb76c672010-02-11 22:22:22 -0500661 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
662 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
663 } else {
srs569408bb0da2010-02-19 17:19:55 -0500664 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
665 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500666 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
667 << "secondary header from the last sector of the disk! You should use 'v' to\n"
668 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
669 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500670 } // if/else
671 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400672 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400673
674 // Return valid headers code: 0 = both headers bad; 1 = main header
675 // good, backup bad; 2 = backup header good, main header bad;
676 // 3 = both headers good. Note these codes refer to valid GPT
677 // signatures and version numbers; more subtle problems will elude
678 // this check!
679 validHeaders = CheckHeaderValidity();
680
681 // Read partitions (from primary array)
682 if (validHeaders > 0) { // if at least one header is OK....
683 // GPT appears to be valid....
684 state = gpt_valid;
685
686 // We're calling the GPT valid, but there's a possibility that one
687 // of the two headers is corrupt. If so, use the one that seems to
688 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500689 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500690 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
691 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400692 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500693 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400694 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500695 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500696 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
697 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500698 RebuildMainHeader();
699 state = gpt_corrupt;
700 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400701 } // if/else/if
702
srs5694546a9c72010-01-26 16:00:26 -0500703 // Figure out which partition table to load....
704 // Load the main partition table, since either its header's CRC is OK or the
705 // backup header's CRC is not OK....
706 if (mainCrcOk || !secondCrcOk) {
707 if (LoadMainTable() == 0)
708 allOK = 0;
709 } else { // bad main header CRC and backup header CRC is OK
710 state = gpt_corrupt;
711 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500712 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500713 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500714 } else { // backup table bad, bad main header CRC, but try main table in desperation....
715 if (LoadMainTable() == 0) {
716 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500717 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500718 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500719 } // if
720 } // if/else (LoadSecondTableAsMain())
721 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400722
srs5694cb76c672010-02-11 22:22:22 -0500723 if (loadedTable == 1)
724 secondPartsCrcOk = CheckTable(&secondHeader);
725 else if (loadedTable == 2)
726 mainPartsCrcOk = CheckTable(&mainHeader);
727 else
728 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400729
srs5694546a9c72010-01-26 16:00:26 -0500730 // Problem with main partition table; if backup is OK, use it instead....
731 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
732 state = gpt_corrupt;
733 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500734 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500735 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
736 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500737 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500738
srs5694e4ac11e2009-08-31 10:13:04 -0400739 // Check for valid CRCs and warn if there are problems
740 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
741 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500742 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400743 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500744 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400745 } else {
746 state = gpt_invalid;
747 } // if/else
748 return allOK;
749} // GPTData::ForceLoadGPTData()
750
srs5694247657a2009-11-26 18:36:12 -0500751// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400752// main GPT header in memory MUST be valid for this call to do anything
753// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500754// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400755int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500756 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400757} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400758
759// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500760// table. Used in repair functions, and when starting up if the main
761// partition table is damaged.
762// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
763int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500764 return LoadPartitionTable(secondHeader, myDisk);
765} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400766
srs5694cb76c672010-02-11 22:22:22 -0500767// Load a single GPT header (main or backup) from the specified disk device and
768// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
769// value appropriately.
770// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
771// failure.
772int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
773 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500774 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500775
776 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500777 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500778 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
779 allOK = 0;
780 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500781 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500782
srs56941c6f8b02010-02-21 11:09:20 -0500783 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500784 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500785 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500786 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500787
srs56940283dae2010-04-28 16:44:34 -0400788 if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500789 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500790 }
srs56941c6f8b02010-02-21 11:09:20 -0500791
792 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500793 return allOK;
794} // GPTData::LoadHeader
795
796// Load a partition table (either main or secondary) from the specified disk,
797// using header as a reference for what to load. If sector != 0 (the default
798// is 0), loads from the specified sector; otherwise loads from the sector
799// indicated in header.
800// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
801int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
802 uint32_t sizeOfParts, newCRC;
803 int retval;
804
805 if (disk.OpenForRead()) {
806 if (sector == 0) {
807 retval = disk.Seek(header.partitionEntriesLBA);
808 } else {
809 retval = disk.Seek(sector);
810 } // if/else
srs569455d92612010-03-07 22:16:07 -0500811 if (retval == 1)
812 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500813 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500814 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
815 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500816 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500817 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500818 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400819 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500820 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400821 if (IsLittleEndian() == 0)
822 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500823 if (!mainPartsCrcOk) {
824 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400825 } // if
826 } else {
srs5694cb76c672010-02-11 22:22:22 -0500827 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400828 } // if/else
829 } else {
srs5694fed16d02010-01-27 23:03:40 -0500830 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500831 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500832 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400833 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500834 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500835} // GPTData::LoadPartitionsTable()
836
837// Check the partition table pointed to by header, but don't keep it
838// around.
839// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
840int GPTData::CheckTable(struct GPTHeader *header) {
841 uint32_t sizeOfParts, newCRC;
842 uint8_t *storage;
843 int newCrcOk = 0;
844
srs56940283dae2010-04-28 16:44:34 -0400845 // Load partition table into temporary storage to check
srs5694cb76c672010-02-11 22:22:22 -0500846 // its CRC and store the results, then discard this temporary
847 // storage, since we don't use it in any but recovery operations
848 if (myDisk.Seek(header->partitionEntriesLBA)) {
srs56940283dae2010-04-28 16:44:34 -0400849 sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
srs5694cb76c672010-02-11 22:22:22 -0500850 storage = new uint8_t[sizeOfParts];
851 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
srs56940283dae2010-04-28 16:44:34 -0400852 cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
srs5694cb76c672010-02-11 22:22:22 -0500853 } else {
854 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
855 newCrcOk = (newCRC == header->partitionEntriesCRC);
856 } // if/else
857 delete[] storage;
858 } // if
859 return newCrcOk;
860} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400861
srs5694e7b4ff92009-08-18 13:16:10 -0400862// Writes GPT (and protective MBR) to disk. Returns 1 on successful
863// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500864int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500865 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500866 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400867
srs56946699b012010-02-04 00:55:30 -0500868 littleEndian = IsLittleEndian();
869
srs5694fed16d02010-01-27 23:03:40 -0500870 if (device == "") {
871 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400872 } // if
873
874 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500875
876 // This test should only fail on read-only disks....
877 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500878 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500879 allOK = 0;
880 } // if
881
srs5694e7b4ff92009-08-18 13:16:10 -0400882 // Is there enough space to hold the GPT headers and partition tables,
883 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400884 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400885 allOK = 0;
886 } // if
887
888 // Check that disk is really big enough to handle this...
889 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500890 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
891 << "problem (or it might not). Aborting!\n(Disk size is "
892 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400893 allOK = 0;
894 } // if
srs5694247657a2009-11-26 18:36:12 -0500895 // Check that second header is properly placed. Warn and ask if this should
896 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500897 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500898 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
899 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500900 if (GetYN() == 'Y') {
901 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500902 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500903 } else {
srs5694fed16d02010-01-27 23:03:40 -0500904 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500905 } // if correction requested
906 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400907
srs569455d92612010-03-07 22:16:07 -0500908 // Check for overlapping or insane partitions....
909 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400910 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500911 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400912 } // if
913
914 // Check for mismatched MBR and GPT data, but let it pass if found
915 // (function displays warning message)
916 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400917
918 RecomputeCRCs();
919
srs5694ba00fed2010-01-12 18:18:36 -0500920 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500921 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
922 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500923 answer = GetYN();
924 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500925 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400926 } else {
927 allOK = 0;
928 } // if/else
929 } // if
930
931 // Do it!
932 if (allOK) {
srs56948a4ddfc2010-03-21 19:05:49 -0400933 if (myDisk.OpenForWrite(device)) {
934 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -0500935 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
936 if (!allOK)
937 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
938 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400939
940 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -0400941 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
942
943 // Now write the main partition tables...
944 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
945
946 // Now write the main GPT header...
947 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
948
949 // To top it off, write the protective MBR...
950 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400951
952 // re-read the partition table
953 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500954 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400955 } // if
956
957 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500958 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400959 } else {
srs5694fed16d02010-01-27 23:03:40 -0500960 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -0400961 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400962 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -0400963
srs5694546a9c72010-01-26 16:00:26 -0500964 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } else {
srs5694fed16d02010-01-27 23:03:40 -0500966 cerr << "Unable to open device " << device << " for writing! Errno is "
967 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400968 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400969 } // if/else
970 } else {
srs5694fed16d02010-01-27 23:03:40 -0500971 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400972 } // if
973
974 return (allOK);
975} // GPTData::SaveGPTData()
976
977// Save GPT data to a backup file. This function does much less error
978// checking than SaveGPTData(). It can therefore preserve many types of
979// corruption for later analysis; however, it preserves only the MBR,
980// the main GPT header, the backup GPT header, and the main partition
981// table; it discards the backup partition table, since it should be
982// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500983int GPTData::SaveGPTBackup(const string & filename) {
984 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500985 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400986
srs5694546a9c72010-01-26 16:00:26 -0500987 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500988 // Recomputing the CRCs is likely to alter them, which could be bad
989 // if the intent is to save a potentially bad GPT for later analysis;
990 // but if we don't do this, we get bogus errors when we load the
991 // backup. I'm favoring misses over false alarms....
992 RecomputeCRCs();
993
srs5694546a9c72010-01-26 16:00:26 -0500994 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400995
srs5694cb76c672010-02-11 22:22:22 -0500996 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500997 // MBR write closed disk, so re-open and seek to end....
998 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500999 allOK = SaveHeader(&mainHeader, backupFile, 1);
1000 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001001
srs5694e7b4ff92009-08-18 13:16:10 -04001002 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001003 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001004
srs5694cb76c672010-02-11 22:22:22 -05001005 if (allOK)
1006 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001007
1008 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001009 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001010 } else {
srs5694fed16d02010-01-27 23:03:40 -05001011 cerr << "Warning! An error was reported when writing the backup file.\n"
1012 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001013 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001014 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001015 } else {
srs5694fed16d02010-01-27 23:03:40 -05001016 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001017 allOK = 0;
1018 } // if/else
1019 return allOK;
1020} // GPTData::SaveGPTBackup()
1021
srs5694cb76c672010-02-11 22:22:22 -05001022// Write a GPT header (main or backup) to the specified sector. Used by both
1023// the SaveGPTData() and SaveGPTBackup() functions.
1024// Should be passed an architecture-appropriate header (DO NOT call
1025// ReverseHeaderBytes() on the header before calling this function)
1026// Returns 1 on success, 0 on failure
1027int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1028 int littleEndian, allOK = 1;
1029
1030 littleEndian = IsLittleEndian();
1031 if (!littleEndian)
1032 ReverseHeaderBytes(header);
1033 if (disk.Seek(sector)) {
1034 if (disk.Write(header, 512) == -1)
1035 allOK = 0;
1036 } else allOK = 0; // if (disk.Seek()...)
1037 if (!littleEndian)
1038 ReverseHeaderBytes(header);
1039 return allOK;
1040} // GPTData::SaveHeader()
1041
1042// Save the partitions to the specified sector. Used by both the SaveGPTData()
1043// and SaveGPTBackup() functions.
1044// Should be passed an architecture-appropriate header (DO NOT call
1045// ReverseHeaderBytes() on the header before calling this function)
1046// Returns 1 on success, 0 on failure
1047int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1048 int littleEndian, allOK = 1;
1049
1050 littleEndian = IsLittleEndian();
1051 if (disk.Seek(sector)) {
1052 if (!littleEndian)
1053 ReversePartitionBytes();
srs56940283dae2010-04-28 16:44:34 -04001054 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
srs5694cb76c672010-02-11 22:22:22 -05001055 allOK = 0;
1056 if (!littleEndian)
1057 ReversePartitionBytes();
1058 } else allOK = 0; // if (myDisk.Seek()...)
1059 return allOK;
1060} // GPTData::SavePartitionTable()
1061
srs5694e7b4ff92009-08-18 13:16:10 -04001062// Load GPT data from a backup file created by SaveGPTBackup(). This function
1063// does minimal error checking. It returns 1 if it completed successfully,
1064// 0 if there was a problem. In the latter case, it creates a new empty
1065// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001066int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001067 int allOK = 1, val, err;
srs56940283dae2010-04-28 16:44:34 -04001068 uint32_t sizeOfEntries;
srs5694cb76c672010-02-11 22:22:22 -05001069 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001070 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001071
srs5694546a9c72010-01-26 16:00:26 -05001072 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001073 if (IsLittleEndian() == 0)
1074 littleEndian = 0;
1075
srs5694e7b4ff92009-08-18 13:16:10 -04001076 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001077 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001078
srs5694cb76c672010-02-11 22:22:22 -05001079 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001080
srs5694cb76c672010-02-11 22:22:22 -05001081 // Check backup file size and rebuild second header if file is right
1082 // size to be direct dd copy of MBR, main header, and main partition
1083 // table; if other size, treat it like a GPT fdisk-generated backup
1084 // file
1085 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1086 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1087 if (shortBackup) {
1088 RebuildSecondHeader();
1089 secondCrcOk = mainCrcOk;
1090 } else {
1091 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1092 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001093
srs5694e7b4ff92009-08-18 13:16:10 -04001094 // Return valid headers code: 0 = both headers bad; 1 = main header
1095 // good, backup bad; 2 = backup header good, main header bad;
1096 // 3 = both headers good. Note these codes refer to valid GPT
1097 // signatures and version numbers; more subtle problems will elude
1098 // this check!
1099 if ((val = CheckHeaderValidity()) > 0) {
1100 if (val == 2) { // only backup header seems to be good
srs56940283dae2010-04-28 16:44:34 -04001101 SetGPTSize(secondHeader.numParts);
1102// numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001103 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001104 } else { // main header is OK
srs56940283dae2010-04-28 16:44:34 -04001105 SetGPTSize(mainHeader.numParts);
1106// numParts = mainHeader.numParts;
srs5694e7b4ff92009-08-18 13:16:10 -04001107 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1108 } // if/else
1109
srs56940283dae2010-04-28 16:44:34 -04001110// SetGPTSize(numParts);
srs5694e7b4ff92009-08-18 13:16:10 -04001111
srs5694e7b4ff92009-08-18 13:16:10 -04001112 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001113 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1114 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001115 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001116 } // if
1117
srs5694cb76c672010-02-11 22:22:22 -05001118 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1119 cerr << "Warning! Read error " << errno
1120 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001121 } else {
1122 allOK = 0;
1123 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001124 // Something went badly wrong, so blank out partitions
1125 if (allOK == 0) {
1126 cerr << "Improper backup file! Clearing all partition data!\n";
1127 ClearGPTData();
1128 protectiveMBR.MakeProtectiveMBR();
1129 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001130 } else {
1131 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001132 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001133 } // if/else
1134
srs5694e7b4ff92009-08-18 13:16:10 -04001135 return allOK;
1136} // GPTData::LoadGPTBackup()
1137
srs569408bb0da2010-02-19 17:19:55 -05001138int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001139 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001140} // GPTData::SaveMBR()
1141
1142// This function destroys the on-disk GPT structures, but NOT the on-disk
1143// MBR.
1144// Returns 1 if the operation succeeds, 0 if not.
1145int GPTData::DestroyGPT(void) {
1146 int i, sum, tableSize, allOK = 1;
1147 uint8_t blankSector[512];
1148 uint8_t* emptyTable;
1149
1150 for (i = 0; i < 512; i++) {
1151 blankSector[i] = 0;
1152 } // for
1153
1154 if (myDisk.OpenForWrite()) {
1155 if (!myDisk.Seek(mainHeader.currentLBA))
1156 allOK = 0;
1157 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1158 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1159 allOK = 0;
1160 } // if
1161 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1162 allOK = 0;
srs56940283dae2010-04-28 16:44:34 -04001163 tableSize = numParts * mainHeader.sizeOfPartitionEntries;
srs569408bb0da2010-02-19 17:19:55 -05001164 emptyTable = new uint8_t[tableSize];
1165 for (i = 0; i < tableSize; i++)
1166 emptyTable[i] = 0;
1167 if (allOK) {
1168 sum = myDisk.Write(emptyTable, tableSize);
1169 if (sum != tableSize) {
1170 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1171 allOK = 0;
1172 } // if write failed
1173 } // if
1174 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1175 allOK = 0;
1176 if (allOK) {
1177 sum = myDisk.Write(emptyTable, tableSize);
1178 if (sum != tableSize) {
1179 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1180 << errno << "\n";
1181 allOK = 0;
1182 } // if wrong size written
1183 } // if
1184 if (!myDisk.Seek(secondHeader.currentLBA))
1185 allOK = 0;
1186 if (allOK) {
1187 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1188 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1189 allOK = 0;
1190 } // if
1191 } // if
1192 myDisk.DiskSync();
1193 myDisk.Close();
1194 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1195 << "other utilities.\n";
1196 delete[] emptyTable;
1197 } else {
1198 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1199 } // if/else (fd != -1)
1200 return (allOK);
1201} // GPTDataTextUI::DestroyGPT()
1202
1203// Wipe MBR data from the disk (zero it out completely)
1204// Returns 1 on success, 0 on failure.
1205int GPTData::DestroyMBR(void) {
1206 int allOK = 1, i;
1207 uint8_t blankSector[512];
1208
1209 for (i = 0; i < 512; i++)
1210 blankSector[i] = 0;
1211
1212 if (myDisk.OpenForWrite()) {
1213 if (myDisk.Seek(0)) {
1214 if (myDisk.Write(blankSector, 512) != 512)
1215 allOK = 0;
1216 } else allOK = 0;
1217 } else allOK = 0;
1218 if (!allOK)
1219 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1220 return allOK;
1221} // GPTData::DestroyMBR(void)
1222
srs5694e4ac11e2009-08-31 10:13:04 -04001223// Tell user whether Apple Partition Map (APM) was discovered....
1224void GPTData::ShowAPMState(void) {
1225 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001226 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001227 else
srs5694fed16d02010-01-27 23:03:40 -05001228 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001229} // GPTData::ShowAPMState()
1230
1231// Tell user about the state of the GPT data....
1232void GPTData::ShowGPTState(void) {
1233 switch (state) {
1234 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001235 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001236 break;
1237 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001238 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001239 break;
1240 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001241 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001242 break;
1243 default:
srs5694fed16d02010-01-27 23:03:40 -05001244 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001245 break;
1246 } // switch
1247} // GPTData::ShowGPTState()
1248
1249// Display the basic GPT data
1250void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001251 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001252 uint64_t temp, totalFree;
1253
srs5694fed16d02010-01-27 23:03:40 -05001254 cout << "Disk " << device << ": " << diskSize << " sectors, "
1255 << BytesToSI(diskSize * blockSize) << "\n";
1256 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001257 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs56940283dae2010-04-28 16:44:34 -04001258 cout << "Partition table holds up to " << numParts << " entries\n";
srs5694fed16d02010-01-27 23:03:40 -05001259 cout << "First usable sector is " << mainHeader.firstUsableLBA
1260 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001261 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001262 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001263 cout << "Total free space is " << totalFree << " sectors ("
1264 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1265 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs56940283dae2010-04-28 16:44:34 -04001266 for (i = 0; i < numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001267 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001268 } // for
1269} // GPTData::DisplayGPTData()
1270
srs5694e4ac11e2009-08-31 10:13:04 -04001271// Show detailed information on the specified partition
1272void GPTData::ShowPartDetails(uint32_t partNum) {
1273 if (partitions[partNum].GetFirstLBA() != 0) {
1274 partitions[partNum].ShowDetails(blockSize);
1275 } else {
srs5694fed16d02010-01-27 23:03:40 -05001276 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001277 } // if
1278} // GPTData::ShowPartDetails()
1279
srs5694e4ac11e2009-08-31 10:13:04 -04001280/**************************************************************************
1281 * *
1282 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1283 * (some of these functions may require user interaction) *
1284 * *
1285 **************************************************************************/
1286
srs569408bb0da2010-02-19 17:19:55 -05001287// Examines the MBR & GPT data to determine which set of data to use: the
1288// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1289// a new set of partitions (use_new). A return value of use_abort indicates
1290// that this function couldn't determine what to do. Overriding functions
1291// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001292WhichToUse GPTData::UseWhichPartitions(void) {
1293 WhichToUse which = use_new;
1294 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001295
1296 mbrState = protectiveMBR.GetValidity();
1297
1298 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001299 cout << "\n***************************************************************\n"
1300 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001301 if (!justLooking) {
srs56940283dae2010-04-28 16:44:34 -04001302 cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
srs5694fed16d02010-01-27 23:03:40 -05001303 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001304 } // if
srs5694fed16d02010-01-27 23:03:40 -05001305 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001306 which = use_mbr;
1307 } // if
1308
1309 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001310 cout << "\n**********************************************************************\n"
1311 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1312 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001313 if ((!justLooking) && (!beQuiet)) {
srs56940283dae2010-04-28 16:44:34 -04001314 cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
srs5694fed16d02010-01-27 23:03:40 -05001315 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1316 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001317 } // if
srs5694fed16d02010-01-27 23:03:40 -05001318 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001319 which = use_bsd;
1320 } // if
1321
1322 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001323 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001324 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001325 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001326 } // if
1327 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001328 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001329 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001330 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001331 } // if
1332 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001333 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001334 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001335 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001336 } // if
1337 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001338 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001339 } // if
1340
srs5694e4ac11e2009-08-31 10:13:04 -04001341 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001342 if (mbrState == gpt) {
1343 cout << "\a\a****************************************************************************\n"
1344 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1345 << "verification and recovery are STRONGLY recommended.\n"
1346 << "****************************************************************************\n";
1347 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001348 } else {
srs569408bb0da2010-02-19 17:19:55 -05001349 which = use_abort;
1350 } // if/else MBR says disk is GPT
1351 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001352
1353 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001354 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001355
1356 return which;
1357} // UseWhichPartitions()
1358
srs569408bb0da2010-02-19 17:19:55 -05001359// Convert MBR partition table into GPT form.
1360void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001361 int i, numToConvert;
1362 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001363
1364 // Clear out old data & prepare basics....
1365 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001366 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001367
1368 // Convert the smaller of the # of GPT or MBR partitions
srs56940283dae2010-04-28 16:44:34 -04001369 if (numParts > MAX_MBR_PARTS)
srs5694978041c2009-09-21 20:51:47 -04001370 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001371 else
srs56940283dae2010-04-28 16:44:34 -04001372 numToConvert = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001373
1374 for (i = 0; i < numToConvert; i++) {
1375 origType = protectiveMBR.GetType(i);
1376 // don't waste CPU time trying to convert extended, hybrid protective, or
1377 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001378 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001379 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001380 partitions[i] = protectiveMBR.AsGPT(i);
1381 } // for
1382
1383 // Convert MBR into protective MBR
1384 protectiveMBR.MakeProtectiveMBR();
1385
1386 // Record that all original CRCs were OK so as not to raise flags
1387 // when doing a disk verification
1388 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001389} // GPTData::XFormPartitions()
1390
1391// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001392// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001393// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001394int GPTData::XFormDisklabel(uint32_t partNum) {
1395 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001396 int goOn = 1, numDone = 0;
1397 BSDData disklabel;
1398
srs569408bb0da2010-02-19 17:19:55 -05001399 if (GetPartRange(&low, &high) == 0) {
1400 goOn = 0;
1401 cout << "No partitions!\n";
1402 } // if
1403 if (partNum > high) {
1404 goOn = 0;
1405 cout << "Specified partition is invalid!\n";
1406 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001407
srs569408bb0da2010-02-19 17:19:55 -05001408 // If all is OK, read the disklabel and convert it.
1409 if (goOn) {
1410 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1411 partitions[partNum].GetLastLBA());
1412 if ((goOn) && (disklabel.IsDisklabel())) {
1413 numDone = XFormDisklabel(&disklabel);
1414 if (numDone == 1)
1415 cout << "Converted 1 BSD partition.\n";
1416 else
1417 cout << "Converted " << numDone << " BSD partitions.\n";
1418 } else {
1419 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1420 } // if/else
1421 } // if
1422 if (numDone > 0) { // converted partitions; delete carrier
1423 partitions[partNum].BlankPartition();
1424 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001425 return numDone;
srs569455d92612010-03-07 22:16:07 -05001426} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001427
1428// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001429int GPTData::XFormDisklabel(BSDData* disklabel) {
1430 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001431
srs569408bb0da2010-02-19 17:19:55 -05001432 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001433 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001434 partNum = FindFirstFreePart();
1435 if (partNum >= 0) {
1436 partitions[partNum] = disklabel->AsGPT(i);
1437 if (partitions[partNum].IsUsed())
1438 numDone++;
1439 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001440 } // for
srs569408bb0da2010-02-19 17:19:55 -05001441 if (partNum == -1)
1442 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001443 } // if
1444
1445 // Record that all original CRCs were OK so as not to raise flags
1446 // when doing a disk verification
1447 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1448
1449 return numDone;
1450} // GPTData::XFormDisklabel(BSDData* disklabel)
1451
srs569408bb0da2010-02-19 17:19:55 -05001452// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1453// partition has the active/bootable flag UNset and uses the GPT fdisk
1454// type code divided by 0x0100 as the MBR type code.
1455// Returns 1 if operation was 100% successful, 0 if there were ANY
1456// problems.
srs5694978041c2009-09-21 20:51:47 -04001457int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001458 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001459
srs5694978041c2009-09-21 20:51:47 -04001460 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001461 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001462 allOK = 0;
1463 } // if
srs56940283dae2010-04-28 16:44:34 -04001464 if (gptPart >= numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001465 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001466 allOK = 0;
1467 } // if
1468 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001469 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001470 allOK = 0;
1471 } // if
1472 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1473 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1474 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001475 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1476 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001477 } // if
srs5694978041c2009-09-21 20:51:47 -04001478 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001479 (uint32_t) partitions[gptPart].GetLengthLBA(),
1480 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001481 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001482 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1483 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1484 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001485 allOK = 0;
1486 } // if/else
1487 return allOK;
1488} // GPTData::OnePartToMBR()
1489
srs569455d92612010-03-07 22:16:07 -05001490// Convert partitions to MBR form (primary and logical) and return
1491// the number done. Partitions are specified in a PartNotes variable,
1492// which includes pointers to GPT partition numbers. A partition number
1493// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1494// location in the table, and MBR_EMPTY means not to create a partition
1495// in that table position. If the partition type entry for a partition
1496// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001497// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001498// protective partitions or extended partitions.
1499int GPTData::PartsToMBR(PartNotes & notes) {
1500 int mbrNum = 0, numConverted = 0;
1501 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001502
srs569455d92612010-03-07 22:16:07 -05001503 protectiveMBR.EmptyMBR();
1504 protectiveMBR.SetDiskSize(diskSize);
1505 notes.Rewind();
1506 while (notes.GetNextInfo(&convInfo) >= 0) {
1507 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1508 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1509 if (convInfo.hexCode != 0)
1510 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1511 if (convInfo.active)
1512 protectiveMBR.SetPartBootable(mbrNum);
1513 mbrNum++;
1514 } // if
1515 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1516 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1517 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1518 protectiveMBR.SetHybrid();
1519 } else {
1520 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1521 } // if/else
1522 mbrNum++;
1523 } // if EFI GPT partition specified
1524 } // for
1525 // Now do logical partition(s)...
1526 protectiveMBR.SetDisk(&myDisk);
1527 numConverted += protectiveMBR.CreateLogicals(notes);
1528// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001529 return numConverted;
1530} // GPTData::PartsToMBR()
1531
srs5694e4ac11e2009-08-31 10:13:04 -04001532
1533/**********************************************************************
1534 * *
1535 * Functions that adjust GPT data structures WITHOUT user interaction *
1536 * (they may display information for the user's benefit, though) *
1537 * *
1538 **********************************************************************/
1539
1540// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001541// necessary, copies data if it already exists. Returns 1 if all goes
1542// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001543int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001544 GPTPart* newParts;
1545 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001546 uint32_t i, high, copyNum;
1547 int allOK = 1;
1548
1549 // First, adjust numEntries upward, if necessary, to get a number
1550 // that fills the allocated sectors
1551 i = blockSize / GPT_SIZE;
1552 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001553 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001554 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001555 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001556 } // if
1557
srs5694247657a2009-11-26 18:36:12 -05001558 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001559 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001560 // partition table, which causes problems when loading data from a RAID
1561 // array that's been expanded because this function is called when loading
1562 // data.
srs56940283dae2010-04-28 16:44:34 -04001563 if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001564 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001565 if (newParts != NULL) {
1566 if (partitions != NULL) { // existing partitions; copy them over
1567 GetPartRange(&i, &high);
1568 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001569 cout << "The highest-numbered partition is " << high + 1
1570 << ", which is greater than the requested\n"
1571 << "partition table size of " << numEntries
1572 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001573 allOK = 0;
1574 } else { // go ahead with copy
srs56940283dae2010-04-28 16:44:34 -04001575 if (numEntries < numParts)
srs5694247657a2009-11-26 18:36:12 -05001576 copyNum = numEntries;
1577 else
srs56940283dae2010-04-28 16:44:34 -04001578 copyNum = numParts;
srs5694247657a2009-11-26 18:36:12 -05001579 for (i = 0; i < copyNum; i++) {
1580 newParts[i] = partitions[i];
1581 } // for
1582 trash = partitions;
1583 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001584 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001585 } // if
1586 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001587 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001588 } // if/else existing partitions
srs56940283dae2010-04-28 16:44:34 -04001589 numParts = numEntries;
srs5694247657a2009-11-26 18:36:12 -05001590 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1591 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1592 MoveSecondHeaderToEnd();
1593 if (diskSize > 0)
1594 CheckGPTSize();
1595 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001596 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001597 allOK = 0;
1598 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001599 } // if/else
srs56940283dae2010-04-28 16:44:34 -04001600 mainHeader.numParts = numParts;
1601 secondHeader.numParts = numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001602 return (allOK);
1603} // GPTData::SetGPTSize()
1604
1605// Blank the partition array
1606void GPTData::BlankPartitions(void) {
1607 uint32_t i;
1608
srs56940283dae2010-04-28 16:44:34 -04001609 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001610 partitions[i].BlankPartition();
1611 } // for
1612} // GPTData::BlankPartitions()
1613
srs5694ba00fed2010-01-12 18:18:36 -05001614// Delete a partition by number. Returns 1 if successful,
1615// 0 if there was a problem. Returns 1 if partition was in
1616// range, 0 if it was out of range.
1617int GPTData::DeletePartition(uint32_t partNum) {
1618 uint64_t startSector, length;
srs56940283dae2010-04-28 16:44:34 -04001619 uint32_t low, high, numUsedParts, retval = 1;;
srs5694ba00fed2010-01-12 18:18:36 -05001620
srs56940283dae2010-04-28 16:44:34 -04001621 numUsedParts = GetPartRange(&low, &high);
1622 if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
srs5694ba00fed2010-01-12 18:18:36 -05001623 // In case there's a protective MBR, look for & delete matching
1624 // MBR partition....
1625 startSector = partitions[partNum].GetFirstLBA();
1626 length = partitions[partNum].GetLengthLBA();
1627 protectiveMBR.DeleteByLocation(startSector, length);
1628
1629 // Now delete the GPT partition
1630 partitions[partNum].BlankPartition();
1631 } else {
srs5694fed16d02010-01-27 23:03:40 -05001632 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001633 retval = 0;
1634 } // if/else
1635 return retval;
1636} // GPTData::DeletePartition(uint32_t partNum)
1637
srs569408bb0da2010-02-19 17:19:55 -05001638// Non-interactively create a partition.
1639// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001640uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001641 int retval = 1; // assume there'll be no problems
1642
1643 if (IsFreePartNum(partNum)) {
1644 Align(&startSector); // Align sector to correct multiple
1645 if (IsFree(startSector) && (startSector <= endSector)) {
1646 if (FindLastInFree(startSector) >= endSector) {
1647 partitions[partNum].SetFirstLBA(startSector);
1648 partitions[partNum].SetLastLBA(endSector);
1649 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001650 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001651 } else retval = 0; // if free space until endSector
1652 } else retval = 0; // if startSector is free
1653 } else retval = 0; // if legal partition number
1654 return retval;
1655} // GPTData::CreatePartition(partNum, startSector, endSector)
1656
srs5694e4ac11e2009-08-31 10:13:04 -04001657// Sort the GPT entries, eliminating gaps and making for a logical
1658// ordering. Relies on QuickSortGPT() for the bulk of the work
1659void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001660 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001661
1662 // First, find the last partition with data, so as not to
1663 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001664 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001665
1666 // Now swap empties with the last partitions, to simplify the logic
1667 // in the Quicksort function....
1668 i = 0;
1669 while (i < lastPart) {
1670 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001671 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001672 do {
1673 lastPart--;
1674 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001675 } // if
1676 i++;
1677 } // while
1678
srs5694546a9c72010-01-26 16:00:26 -05001679 // If there are more empties than partitions in the range from 0 to lastPart,
1680 // the above leaves lastPart set too high, so we've got to adjust it to
1681 // prevent empties from migrating to the top of the list....
1682 GetPartRange(&firstPart, &lastPart);
1683
srs5694e4ac11e2009-08-31 10:13:04 -04001684 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001685 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001686} // GPTData::SortGPT()
1687
srs569408bb0da2010-02-19 17:19:55 -05001688// Recursive quick sort algorithm for GPT partitions. Note that if there
1689// are any empties in the specified range, they'll be sorted to the
1690// start, resulting in a sorted set of partitions that begins with
1691// partition 2, 3, or higher.
1692void GPTData::QuickSortGPT(int start, int finish) {
1693 uint64_t starterValue; // starting location of median partition
1694 int left, right;
1695
1696 left = start;
1697 right = finish;
1698 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1699 do {
1700 while (partitions[left].GetFirstLBA() < starterValue)
1701 left++;
1702 while (partitions[right].GetFirstLBA() > starterValue)
1703 right--;
1704 if (left <= right)
1705 SwapPartitions(left++, right--);
1706 } while (left <= right);
1707 if (start < right) QuickSortGPT(start, right);
1708 if (finish > left) QuickSortGPT(left, finish);
1709} // GPTData::QuickSortGPT()
1710
1711// Swap the contents of two partitions.
1712// Returns 1 if successful, 0 if either partition is out of range
1713// (that is, not a legal number; either or both can be empty).
1714// Note that if partNum1 = partNum2 and this number is in range,
1715// it will be considered successful.
1716int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1717 GPTPart temp;
1718 int allOK = 1;
1719
srs56940283dae2010-04-28 16:44:34 -04001720 if ((partNum1 < numParts) && (partNum2 < numParts)) {
srs569408bb0da2010-02-19 17:19:55 -05001721 if (partNum1 != partNum2) {
1722 temp = partitions[partNum1];
1723 partitions[partNum1] = partitions[partNum2];
1724 partitions[partNum2] = temp;
1725 } // if
1726 } else allOK = 0; // partition numbers are valid
1727 return allOK;
1728} // GPTData::SwapPartitions()
1729
srs5694e4ac11e2009-08-31 10:13:04 -04001730// Set up data structures for entirely new set of partitions on the
1731// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001732// Note that this function does NOT clear the protectiveMBR data
1733// structure, since it may hold the original MBR partitions if the
1734// program was launched on an MBR disk, and those may need to be
1735// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001736int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001737 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001738
1739 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001740 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001741 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001742 partitions = NULL;
1743 SetGPTSize(NUM_GPT_ENTRIES);
1744
1745 // Now initialize a bunch of stuff that's static....
1746 mainHeader.signature = GPT_SIGNATURE;
1747 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001748 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001749 mainHeader.reserved = 0;
1750 mainHeader.currentLBA = UINT64_C(1);
1751 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1752 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1753 for (i = 0; i < GPT_RESERVED; i++) {
1754 mainHeader.reserved2[i] = '\0';
1755 } // for
srs56948a4ddfc2010-03-21 19:05:49 -04001756 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001757
1758 // Now some semi-static items (computed based on end of disk)
1759 mainHeader.backupLBA = diskSize - UINT64_C(1);
1760 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1761
1762 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001763 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001764
1765 // Copy main header to backup header
1766 RebuildSecondHeader();
1767
1768 // Blank out the partitions array....
1769 BlankPartitions();
1770
1771 // Flag all CRCs as being OK....
1772 mainCrcOk = 1;
1773 secondCrcOk = 1;
1774 mainPartsCrcOk = 1;
1775 secondPartsCrcOk = 1;
1776
1777 return (goOn);
1778} // GPTData::ClearGPTData()
1779
srs5694247657a2009-11-26 18:36:12 -05001780// Set the location of the second GPT header data to the end of the disk.
1781// Used internally and called by the 'e' option on the recovery &
1782// transformation menu, to help users of RAID arrays who add disk space
1783// to their arrays.
1784void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001785 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1786 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1787 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1788} // GPTData::FixSecondHeaderLocation()
1789
srs56940a697312010-01-28 21:10:52 -05001790int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001791 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001792
1793 if (!IsFreePartNum(partNum)) {
1794 partitions[partNum].SetName(theName);
1795 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001796
1797 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001798} // GPTData::SetName
1799
1800// Set the disk GUID to the specified value. Note that the header CRCs must
1801// be recomputed after calling this function.
1802void GPTData::SetDiskGUID(GUIDData newGUID) {
1803 mainHeader.diskGUID = newGUID;
1804 secondHeader.diskGUID = newGUID;
1805} // SetDiskGUID()
1806
1807// Set the unique GUID of the specified partition. Returns 1 on
1808// successful completion, 0 if there were problems (invalid
1809// partition number).
1810int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1811 int retval = 0;
1812
srs56940283dae2010-04-28 16:44:34 -04001813 if (pn < numParts) {
srs5694e4ac11e2009-08-31 10:13:04 -04001814 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1815 partitions[pn].SetUniqueGUID(theGUID);
1816 retval = 1;
1817 } // if
1818 } // if
1819 return retval;
1820} // GPTData::SetPartitionGUID()
1821
srs5694ba00fed2010-01-12 18:18:36 -05001822// Change partition type code non-interactively. Returns 1 if
1823// successful, 0 if not....
1824int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1825 int retval = 1;
1826
1827 if (!IsFreePartNum(partNum)) {
1828 partitions[partNum].SetType(hexCode);
1829 } else retval = 0;
1830 return retval;
1831} // GPTData::ChangePartType()
1832
srs56941d1448a2009-12-31 21:20:19 -05001833// Adjust sector number so that it falls on a sector boundary that's a
1834// multiple of sectorAlignment. This is done to improve the performance
1835// of Western Digital Advanced Format disks and disks with similar
1836// technology from other companies, which use 4096-byte sectors
1837// internally although they translate to 512-byte sectors for the
1838// benefit of the OS. If partitions aren't properly aligned on these
1839// disks, some filesystem data structures can span multiple physical
1840// sectors, degrading performance. This function should be called
1841// only on the FIRST sector of the partition, not the last!
1842// This function returns 1 if the alignment was altered, 0 if it
1843// was unchanged.
1844int GPTData::Align(uint64_t* sector) {
1845 int retval = 0, sectorOK = 0;
1846 uint64_t earlier, later, testSector, original;
1847
1848 if ((*sector % sectorAlignment) != 0) {
1849 original = *sector;
1850 retval = 1;
1851 earlier = (*sector / sectorAlignment) * sectorAlignment;
1852 later = earlier + (uint64_t) sectorAlignment;
1853
1854 // Check to see that every sector between the earlier one and the
1855 // requested one is clear, and that it's not too early....
1856 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001857 sectorOK = 1;
1858 testSector = earlier;
1859 do {
1860 sectorOK = IsFree(testSector++);
1861 } while ((sectorOK == 1) && (testSector < *sector));
1862 if (sectorOK == 1) {
1863 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001864 } // if
1865 } // if firstUsableLBA check
1866
1867 // If couldn't move the sector earlier, try to move it later instead....
1868 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1869 sectorOK = 1;
1870 testSector = later;
1871 do {
1872 sectorOK = IsFree(testSector--);
1873 } while ((sectorOK == 1) && (testSector > *sector));
1874 if (sectorOK == 1) {
1875 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001876 } // if
1877 } // if
1878
1879 // If sector was changed successfully, inform the user of this fact.
1880 // Otherwise, notify the user that it couldn't be done....
1881 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001882 cout << "Information: Moved requested sector from " << original << " to "
srs56948a4ddfc2010-03-21 19:05:49 -04001883 << *sector << " in\norder to align on " << sectorAlignment
1884 << "-sector boundaries.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001885 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001886 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001887 } else {
srs5694fed16d02010-01-27 23:03:40 -05001888 cout << "Information: Sector not aligned on " << sectorAlignment
1889 << "-sector boundary and could not be moved.\n"
1890 << "If you're using a Western Digital Advanced Format or similar disk with\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001891 << "underlying 4096-byte sectors or certain types of RAID array, performance\n"
1892 << "may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001893 retval = 0;
1894 } // if/else
1895 } // if
1896 return retval;
1897} // GPTData::Align()
1898
srs5694e4ac11e2009-08-31 10:13:04 -04001899/********************************************************
1900 * *
1901 * Functions that return data about GPT data structures *
1902 * (most of these are inline in gpt.h) *
1903 * *
1904 ********************************************************/
1905
1906// Find the low and high used partition numbers (numbered from 0).
1907// Return value is the number of partitions found. Note that the
1908// *low and *high values are both set to 0 when no partitions
1909// are found, as well as when a single partition in the first
1910// position exists. Thus, the return value is the only way to
1911// tell when no partitions exist.
1912int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1913 uint32_t i;
1914 int numFound = 0;
1915
srs56940283dae2010-04-28 16:44:34 -04001916 *low = numParts + 1; // code for "not found"
srs5694e4ac11e2009-08-31 10:13:04 -04001917 *high = 0;
srs56940283dae2010-04-28 16:44:34 -04001918 if (numParts > 0) { // only try if partition table exists...
1919 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001920 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1921 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001922 // Set the low value only if it's not yet found...
srs56940283dae2010-04-28 16:44:34 -04001923 if (*low == (numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001924 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001925 } // if
1926 } // for
1927 } // if
1928
1929 // Above will leave *low pointing to its "not found" value if no partitions
1930 // are defined, so reset to 0 if this is the case....
srs56940283dae2010-04-28 16:44:34 -04001931 if (*low == (numParts + 1))
srs5694e4ac11e2009-08-31 10:13:04 -04001932 *low = 0;
1933 return numFound;
1934} // GPTData::GetPartRange()
1935
srs569408bb0da2010-02-19 17:19:55 -05001936// Returns the value of the first free partition, or -1 if none is
1937// unused.
1938int GPTData::FindFirstFreePart(void) {
1939 int i = 0;
1940
1941 if (partitions != NULL) {
srs56940283dae2010-04-28 16:44:34 -04001942 while ((partitions[i].IsUsed()) && (i < (int) numParts))
srs569408bb0da2010-02-19 17:19:55 -05001943 i++;
srs56940283dae2010-04-28 16:44:34 -04001944 if (i >= (int) numParts)
srs569408bb0da2010-02-19 17:19:55 -05001945 i = -1;
1946 } else i = -1;
1947 return i;
1948} // GPTData::FindFirstFreePart()
1949
srs5694978041c2009-09-21 20:51:47 -04001950// Returns the number of defined partitions.
1951uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001952 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001953
srs56940283dae2010-04-28 16:44:34 -04001954 for (i = 0; i < numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001955 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001956 counted++;
1957 } // for
1958 return counted;
1959} // GPTData::CountParts()
1960
srs5694e4ac11e2009-08-31 10:13:04 -04001961/****************************************************
1962 * *
1963 * Functions that return data about disk free space *
1964 * *
1965 ****************************************************/
1966
1967// Find the first available block after the starting point; returns 0 if
1968// there are no available blocks left
1969uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1970 uint64_t first;
1971 uint32_t i;
1972 int firstMoved = 0;
1973
1974 // Begin from the specified starting point or from the first usable
1975 // LBA, whichever is greater...
1976 if (start < mainHeader.firstUsableLBA)
1977 first = mainHeader.firstUsableLBA;
1978 else
1979 first = start;
1980
1981 // ...now search through all partitions; if first is within an
1982 // existing partition, move it to the next sector after that
1983 // partition and repeat. If first was moved, set firstMoved
1984 // flag; repeat until firstMoved is not set, so as to catch
1985 // cases where partitions are out of sequential order....
1986 do {
1987 firstMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04001988 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04001989 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001990 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001991 first = partitions[i].GetLastLBA() + 1;
1992 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001993 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001994 } // for
1995 } while (firstMoved == 1);
1996 if (first > mainHeader.lastUsableLBA)
1997 first = 0;
1998 return (first);
1999} // GPTData::FindFirstAvailable()
2000
2001// Finds the first available sector in the largest block of unallocated
2002// space on the disk. Returns 0 if there are no available blocks left
2003uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002004 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002005
2006 start = 0;
2007 do {
2008 firstBlock = FindFirstAvailable(start);
2009 if (firstBlock != UINT32_C(0)) { // something's free...
2010 lastBlock = FindLastInFree(firstBlock);
2011 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2012 if (segmentSize > selectedSize) {
2013 selectedSize = segmentSize;
2014 selectedSegment = firstBlock;
2015 } // if
2016 start = lastBlock + 1;
2017 } // if
2018 } while (firstBlock != 0);
2019 return selectedSegment;
2020} // GPTData::FindFirstInLargest()
2021
srs5694cb76c672010-02-11 22:22:22 -05002022// Find the last available block on the disk.
2023// Returns 0 if there are no available partitions
2024uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002025 uint64_t last;
2026 uint32_t i;
2027 int lastMoved = 0;
2028
2029 // Start by assuming the last usable LBA is available....
2030 last = mainHeader.lastUsableLBA;
2031
2032 // ...now, similar to algorithm in FindFirstAvailable(), search
2033 // through all partitions, moving last when it's in an existing
2034 // partition. Set the lastMoved flag so we repeat to catch cases
2035 // where partitions are out of logical order.
2036 do {
2037 lastMoved = 0;
srs56940283dae2010-04-28 16:44:34 -04002038 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002039 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002040 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002041 last = partitions[i].GetFirstLBA() - 1;
2042 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002043 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002044 } // for
2045 } while (lastMoved == 1);
2046 if (last < mainHeader.firstUsableLBA)
2047 last = 0;
2048 return (last);
2049} // GPTData::FindLastAvailable()
2050
2051// Find the last available block in the free space pointed to by start.
2052uint64_t GPTData::FindLastInFree(uint64_t start) {
2053 uint64_t nearestStart;
2054 uint32_t i;
2055
2056 nearestStart = mainHeader.lastUsableLBA;
srs56940283dae2010-04-28 16:44:34 -04002057 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002058 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002059 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002060 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002061 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002062 } // for
2063 return (nearestStart);
2064} // GPTData::FindLastInFree()
2065
2066// Finds the total number of free blocks, the number of segments in which
2067// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002068uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002069 uint64_t start = UINT64_C(0); // starting point for each search
2070 uint64_t totalFound = UINT64_C(0); // running total
2071 uint64_t firstBlock; // first block in a segment
2072 uint64_t lastBlock; // last block in a segment
2073 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002074 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002075
2076 *largestSegment = UINT64_C(0);
2077 do {
2078 firstBlock = FindFirstAvailable(start);
2079 if (firstBlock != UINT64_C(0)) { // something's free...
2080 lastBlock = FindLastInFree(firstBlock);
2081 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2082 if (segmentSize > *largestSegment) {
2083 *largestSegment = segmentSize;
2084 } // if
2085 totalFound += segmentSize;
2086 num++;
2087 start = lastBlock + 1;
2088 } // if
2089 } while (firstBlock != 0);
2090 *numSegments = num;
2091 return totalFound;
2092} // GPTData::FindFreeBlocks()
2093
srs569455d92612010-03-07 22:16:07 -05002094// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2095// If it's allocated, return the partition number to which it's allocated
2096// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2097// returned in partNum if the sector is in use by basic GPT data structures.)
2098int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002099 int isFree = 1;
2100 uint32_t i;
2101
srs56940283dae2010-04-28 16:44:34 -04002102 for (i = 0; i < numParts; i++) {
srs5694e4ac11e2009-08-31 10:13:04 -04002103 if ((sector >= partitions[i].GetFirstLBA()) &&
2104 (sector <= partitions[i].GetLastLBA())) {
2105 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002106 if (partNum != NULL)
2107 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002108 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002109 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002110 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002111 (sector > mainHeader.lastUsableLBA)) {
2112 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002113 if (partNum != NULL)
2114 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002115 } // if
2116 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002117} // GPTData::IsFree()
2118
srs5694ba00fed2010-01-12 18:18:36 -05002119// Returns 1 if partNum is unused.
2120int GPTData::IsFreePartNum(uint32_t partNum) {
2121 int retval = 1;
2122
srs56940283dae2010-04-28 16:44:34 -04002123 if ((partNum < numParts) && (partitions != NULL)) {
srs569408bb0da2010-02-19 17:19:55 -05002124 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002125 retval = 0;
2126 } // if partition is in use
2127 } else retval = 0;
2128
2129 return retval;
2130} // GPTData::IsFreePartNum()
2131
srs5694a8582cf2010-03-19 14:21:59 -04002132
2133/***********************************************************
2134 * *
2135 * Change how functions work or return information on them *
2136 * *
2137 ***********************************************************/
2138
2139// Set partition alignment value; partitions will begin on multiples of
2140// the specified value
2141void GPTData::SetAlignment(uint32_t n) {
2142 uint32_t l2;
2143
2144 sectorAlignment = n;
2145 l2 = (uint32_t) log2(n);
srs5694a8582cf2010-03-19 14:21:59 -04002146} // GPTData::SetAlignment()
2147
2148// Compute sector alignment based on the current partitions (if any). Each
2149// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56948a4ddfc2010-03-21 19:05:49 -04002150// value less than or equal to the DEFAULT_ALIGNMENT value, but not by the
2151// previously-located alignment value, then the alignment value is adjusted
2152// down. If the computed alignment is less than 8 and the disk is bigger than
2153// SMALLEST_ADVANCED_FORMAT, resets it to 8. This is a safety measure for WD
2154// Advanced Format and similar drives. If no partitions are defined, the
2155// alignment value is set to DEFAULT_ALIGNMENT (2048). The result is that new
2156// drives are aligned to 2048-sector multiples but the program won't complain
2157// about other alignments on existing disks unless a smaller-than-8 alignment
2158// is used on small disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002159// Returns the computed alignment value.
2160uint32_t GPTData::ComputeAlignment(void) {
2161 uint32_t i = 0, found, exponent = 31;
2162 uint64_t align = DEFAULT_ALIGNMENT;
2163
srs56948a4ddfc2010-03-21 19:05:49 -04002164 exponent = (uint32_t) log2(DEFAULT_ALIGNMENT);
srs56940283dae2010-04-28 16:44:34 -04002165 for (i = 0; i < numParts; i++) {
srs5694a8582cf2010-03-19 14:21:59 -04002166 if (partitions[i].IsUsed()) {
2167 found = 0;
2168 while (!found) {
2169 align = PowerOf2(exponent);
2170 if ((partitions[i].GetFirstLBA() % align) == 0) {
2171 found = 1;
2172 } else {
2173 exponent--;
2174 } // if/else
2175 } // while
2176 } // if
2177 } // for
2178 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2179 align = 8;
srs5694a8582cf2010-03-19 14:21:59 -04002180 SetAlignment(align);
2181 return align;
2182} // GPTData::ComputeAlignment()
2183
srs5694e4ac11e2009-08-31 10:13:04 -04002184/********************************
2185 * *
2186 * Endianness support functions *
2187 * *
2188 ********************************/
2189
srs56942a9f5da2009-08-26 00:48:01 -04002190void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002191 ReverseBytes(&header->signature, 8);
2192 ReverseBytes(&header->revision, 4);
2193 ReverseBytes(&header->headerSize, 4);
2194 ReverseBytes(&header->headerCRC, 4);
2195 ReverseBytes(&header->reserved, 4);
2196 ReverseBytes(&header->currentLBA, 8);
2197 ReverseBytes(&header->backupLBA, 8);
2198 ReverseBytes(&header->firstUsableLBA, 8);
2199 ReverseBytes(&header->lastUsableLBA, 8);
2200 ReverseBytes(&header->partitionEntriesLBA, 8);
2201 ReverseBytes(&header->numParts, 4);
2202 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2203 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002204 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002205} // GPTData::ReverseHeaderBytes()
2206
srs56940283dae2010-04-28 16:44:34 -04002207// Reverse byte order for all partitions.
srs56942a9f5da2009-08-26 00:48:01 -04002208void GPTData::ReversePartitionBytes() {
2209 uint32_t i;
2210
srs56940283dae2010-04-28 16:44:34 -04002211 for (i = 0; i < numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002212 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002213 } // for
2214} // GPTData::ReversePartitionBytes()
2215
2216/******************************************
2217 * *
2218 * Additional non-class support functions *
2219 * *
2220 ******************************************/
2221
srs5694e7b4ff92009-08-18 13:16:10 -04002222// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2223// never fail these tests, but the struct types may fail depending on compile options.
2224// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2225// sizes.
2226int SizesOK(void) {
2227 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002228
2229 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002230 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002231 allOK = 0;
2232 } // if
2233 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002234 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002235 allOK = 0;
2236 } // if
2237 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002238 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002239 allOK = 0;
2240 } // if
2241 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002242 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002243 allOK = 0;
2244 } // if
2245 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002246 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002247 allOK = 0;
2248 } // if
srs5694978041c2009-09-21 20:51:47 -04002249 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002250 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002251 allOK = 0;
2252 } // if
2253 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002254 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002255 allOK = 0;
2256 } // if
srs5694221e0872009-08-29 15:00:31 -04002257 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002258 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002259 allOK = 0;
2260 } // if
srs56946699b012010-02-04 00:55:30 -05002261 if (sizeof(GUIDData) != 16) {
2262 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2263 allOK = 0;
2264 } // if
2265 if (sizeof(PartType) != 16) {
2266 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2267 allOK = 0;
2268 } // if
srs5694fed16d02010-01-27 23:03:40 -05002269 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002270 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002271 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2272 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002273 } // if
2274 return (allOK);
2275} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002276