blob: a407d3764691f18b41bc0a0286a28e2cff7948bc [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;
srs5694e7b4ff92009-08-18 13:16:10 -040058 SetGPTSize(NUM_GPT_ENTRIES);
59} // GPTData default constructor
60
61// The following constructor loads GPT data from a device file
srs5694fed16d02010-01-27 23:03:40 -050062GPTData::GPTData(string filename) {
srs5694e7b4ff92009-08-18 13:16:10 -040063 blockSize = SECTOR_SIZE; // set a default
64 diskSize = 0;
65 partitions = NULL;
66 state = gpt_invalid;
srs5694fed16d02010-01-27 23:03:40 -050067 device = "";
srs56945d58fe02010-01-03 20:57:08 -050068 justLooking = 0;
srs5694e7b4ff92009-08-18 13:16:10 -040069 mainCrcOk = 0;
70 secondCrcOk = 0;
71 mainPartsCrcOk = 0;
72 secondPartsCrcOk = 0;
srs5694221e0872009-08-29 15:00:31 -040073 apmFound = 0;
74 bsdFound = 0;
srs56941d1448a2009-12-31 21:20:19 -050075 sectorAlignment = 8; // Align partitions on 4096-byte boundaries by default
srs5694ba00fed2010-01-12 18:18:36 -050076 beQuiet = 0;
77 whichWasUsed = use_new;
srs5694e7b4ff92009-08-18 13:16:10 -040078 srand((unsigned int) time(NULL));
srs56941e093722010-01-05 00:14:19 -050079 mainHeader.numParts = 0;
srs56943c0af382010-01-15 19:19:18 -050080 if (!LoadPartitions(filename))
81 exit(2);
srs5694fed16d02010-01-27 23:03:40 -050082} // GPTData(string filename) constructor
srs5694e7b4ff92009-08-18 13:16:10 -040083
srs5694e4ac11e2009-08-31 10:13:04 -040084// Destructor
srs5694e7b4ff92009-08-18 13:16:10 -040085GPTData::~GPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -050086 delete[] partitions;
srs5694e7b4ff92009-08-18 13:16:10 -040087} // GPTData destructor
88
srs5694e4ac11e2009-08-31 10:13:04 -040089/*********************************************************************
90 * *
91 * Begin functions that verify data, or that adjust the verification *
92 * information (compute CRCs, rebuild headers) *
93 * *
94 *********************************************************************/
srs5694e7b4ff92009-08-18 13:16:10 -040095
srs5694e4ac11e2009-08-31 10:13:04 -040096// Perform detailed verification, reporting on any problems found, but
97// do *NOT* recover from these problems. Returns the total number of
98// problems identified.
99int GPTData::Verify(void) {
srs5694e321d442010-01-29 17:44:04 -0500100 int problems = 0;
101 uint32_t i, numSegments;
102 uint64_t totalFree, largestSegment;
srs5694e4ac11e2009-08-31 10:13:04 -0400103
104 // First, check for CRC errors in the GPT data....
105 if (!mainCrcOk) {
106 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500107 cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
108 << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
109 << "header ('b' on the recovery & transformation menu). This report may be a false\n"
110 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400111 } // if
112 if (!mainPartsCrcOk) {
113 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500114 cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
115 << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
116 << "transformation menu). This report may be a false alarm if you've already\n"
117 << "corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400118 } // if
119 if (!secondCrcOk) {
120 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500121 cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
122 << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
123 << "header ('d' on the recovery & transformation menu). This report may be a false\n"
124 << "alarm if you've already corrected other problems.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400125 } // if
126 if (!secondPartsCrcOk) {
127 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500128 cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
129 << "be corrupt. This program will automatically create a new backup partition\n"
130 << "table when you save your partitions.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400131 } // if
132
srs5694978041c2009-09-21 20:51:47 -0400133 // Now check that the main and backup headers both point to themselves....
134 if (mainHeader.currentLBA != 1) {
135 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500136 cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
137 << "is being automatically corrected, but it may be a symptom of more serious\n"
138 << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
srs5694978041c2009-09-21 20:51:47 -0400139 mainHeader.currentLBA = 1;
140 } // if
141 if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
142 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500143 cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
144 << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
145 << "option on the experts' menu to adjust the secondary header's and partition\n"
146 << "table's locations.\n";
srs5694978041c2009-09-21 20:51:47 -0400147 } // if
148
149 // Now check that critical main and backup GPT entries match each other
srs5694e4ac11e2009-08-31 10:13:04 -0400150 if (mainHeader.currentLBA != secondHeader.backupLBA) {
151 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500152 cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
153 << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
154 << secondHeader.backupLBA << ").\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400155 } // if
156 if (mainHeader.backupLBA != secondHeader.currentLBA) {
157 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500158 cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
159 << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
160 << secondHeader.currentLBA << ").\n"
161 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400162 } // if
163 if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
164 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500165 cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
166 << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
167 << secondHeader.firstUsableLBA << ")\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400168 } // if
169 if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
170 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500171 cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
172 << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
173 << secondHeader.lastUsableLBA << ")\n"
174 << "The 'e' option on the experts' menu can probably fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400175 } // if
srs56946699b012010-02-04 00:55:30 -0500176 if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400177 problems++;
srs56946699b012010-02-04 00:55:30 -0500178 cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID.AsString()
srs5694fed16d02010-01-27 23:03:40 -0500179 << ") doesn't\nmatch the backup GPT header's disk GUID ("
srs56946699b012010-02-04 00:55:30 -0500180 << secondHeader.diskGUID.AsString() << ")\n"
srs5694fed16d02010-01-27 23:03:40 -0500181 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
182 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400183 } // if
184 if (mainHeader.numParts != secondHeader.numParts) {
185 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500186 cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
187 << ") doesn't\nmatch the backup GPT header's number of partitions ("
188 << secondHeader.numParts << ")\n"
189 << "Resizing the partition table ('s' on the experts' menu) may help.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400190 } // if
191 if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
192 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500193 cout << "\nProblem: main GPT header's size of partition entries ("
194 << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
195 << "match the backup GPT header's size of partition entries ("
196 << secondHeader.sizeOfPartitionEntries << ")\n"
197 << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
198 << "select one or the other header.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400199 } // if
200
201 // Now check for a few other miscellaneous problems...
202 // Check that the disk size will hold the data...
203 if (mainHeader.backupLBA > diskSize) {
204 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500205 cout << "\nProblem: Disk is too small to hold all the data!\n"
206 << "(Disk size is " << diskSize << " sectors, needs to be "
207 << mainHeader.backupLBA << " sectors.)\n"
208 << "The 'e' option on the experts' menu may fix this problem.\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400209 } // if
210
211 // Check for overlapping partitions....
212 problems += FindOverlaps();
213
srs569455d92612010-03-07 22:16:07 -0500214 // Check for insane partitions (start after end, hugely big, etc.)
215 problems += FindInsanePartitions();
216
srs5694e4ac11e2009-08-31 10:13:04 -0400217 // Check for mismatched MBR and GPT partitions...
218 problems += FindHybridMismatches();
219
220 // Verify that partitions don't run into GPT data areas....
221 problems += CheckGPTSize();
222
srs56941d1448a2009-12-31 21:20:19 -0500223 // Check that partitions are aligned on proper boundaries (for WD Advanced
224 // Format and similar disks)....
225 for (i = 0; i < mainHeader.numParts; i++) {
226 if ((partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
srs5694fed16d02010-01-27 23:03:40 -0500227 cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
228 << sectorAlignment << "-sector boundary. This may\nresult "
229 << "in degraded performance on some modern (2009 and later) hard disks.\n";
srs56941d1448a2009-12-31 21:20:19 -0500230 } // if
231 } // for
232
srs5694e4ac11e2009-08-31 10:13:04 -0400233 // Now compute available space, but only if no problems found, since
234 // problems could affect the results
235 if (problems == 0) {
236 totalFree = FindFreeBlocks(&numSegments, &largestSegment);
srs5694fed16d02010-01-27 23:03:40 -0500237 cout << "No problems found. " << totalFree << " free sectors ("
238 << BytesToSI(totalFree * (uint64_t) blockSize) << ") available in "
239 << numSegments << "\nsegments, the largest of which is "
240 << largestSegment << " (" << BytesToSI(largestSegment * (uint64_t) blockSize)
241 << ") in size\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400242 } else {
srs56940a697312010-01-28 21:10:52 -0500243 cout << "\nIdentified " << problems << " problems!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400244 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -0400245
246 return (problems);
247} // GPTData::Verify()
srs5694e7b4ff92009-08-18 13:16:10 -0400248
249// Checks to see if the GPT tables overrun existing partitions; if they
srs5694221e0872009-08-29 15:00:31 -0400250// do, issues a warning but takes no action. Returns number of problems
251// detected (0 if OK, 1 to 2 if problems).
srs5694e7b4ff92009-08-18 13:16:10 -0400252int GPTData::CheckGPTSize(void) {
253 uint64_t overlap, firstUsedBlock, lastUsedBlock;
254 uint32_t i;
srs5694221e0872009-08-29 15:00:31 -0400255 int numProbs = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400256
257 // first, locate the first & last used blocks
258 firstUsedBlock = UINT64_MAX;
259 lastUsedBlock = 0;
260 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -0400261 if ((partitions[i].GetFirstLBA() < firstUsedBlock) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400262 (partitions[i].GetFirstLBA() != 0))
srs5694221e0872009-08-29 15:00:31 -0400263 firstUsedBlock = partitions[i].GetFirstLBA();
264 if (partitions[i].GetLastLBA() > lastUsedBlock)
265 lastUsedBlock = partitions[i].GetLastLBA();
srs5694e7b4ff92009-08-18 13:16:10 -0400266 } // for
267
268 // If the disk size is 0 (the default), then it means that various
269 // variables aren't yet set, so the below tests will be useless;
270 // therefore we should skip everything
271 if (diskSize != 0) {
272 if (mainHeader.firstUsableLBA > firstUsedBlock) {
273 overlap = mainHeader.firstUsableLBA - firstUsedBlock;
srs5694fed16d02010-01-27 23:03:40 -0500274 cout << "Warning! Main partition table overlaps the first partition by "
275 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400276 if (firstUsedBlock > 2) {
srs5694fed16d02010-01-27 23:03:40 -0500277 cout << "Try reducing the partition table size by " << overlap * 4
278 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400279 } else {
srs5694fed16d02010-01-27 23:03:40 -0500280 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400281 } // if/else
282 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400283 } // Problem at start of disk
284 if (mainHeader.lastUsableLBA < lastUsedBlock) {
285 overlap = lastUsedBlock - mainHeader.lastUsableLBA;
srs569455d92612010-03-07 22:16:07 -0500286 cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
srs5694fed16d02010-01-27 23:03:40 -0500287 << overlap << " blocks!\n";
srs5694221e0872009-08-29 15:00:31 -0400288 if (lastUsedBlock > (diskSize - 2)) {
srs5694fed16d02010-01-27 23:03:40 -0500289 cout << "You will need to delete this partition or resize it in another utility.\n";
srs5694221e0872009-08-29 15:00:31 -0400290 } else {
srs5694fed16d02010-01-27 23:03:40 -0500291 cout << "Try reducing the partition table size by " << overlap * 4
292 << " entries.\n(Use the 's' item on the experts' menu.)\n";
srs5694221e0872009-08-29 15:00:31 -0400293 } // if/else
294 numProbs++;
srs5694e7b4ff92009-08-18 13:16:10 -0400295 } // Problem at end of disk
296 } // if (diskSize != 0)
srs5694221e0872009-08-29 15:00:31 -0400297 return numProbs;
srs5694e7b4ff92009-08-18 13:16:10 -0400298} // GPTData::CheckGPTSize()
299
srs5694e7b4ff92009-08-18 13:16:10 -0400300// Check the validity of the GPT header. Returns 1 if the main header
301// is valid, 2 if the backup header is valid, 3 if both are valid, and
302// 0 if neither is valid. Note that this function just checks the GPT
303// signature and revision numbers, not CRCs or other data.
304int GPTData::CheckHeaderValidity(void) {
305 int valid = 3;
306
srs5694fed16d02010-01-27 23:03:40 -0500307 cout.setf(ios::uppercase);
308 cout.fill('0');
309
310 // Note: failed GPT signature checks produce no error message because
311 // a message is displayed in the ReversePartitionBytes() function
srs5694e7b4ff92009-08-18 13:16:10 -0400312 if (mainHeader.signature != GPT_SIGNATURE) {
313 valid -= 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400314 } else if ((mainHeader.revision != 0x00010000) && valid) {
315 valid -= 1;
srs5694fed16d02010-01-27 23:03:40 -0500316 cout << "Unsupported GPT version in main header; read 0x";
317 cout.width(8);
318 cout << hex << mainHeader.revision << ", should be\n0x";
319 cout.width(8);
320 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400321 } // if/else/if
322
323 if (secondHeader.signature != GPT_SIGNATURE) {
324 valid -= 2;
srs5694e7b4ff92009-08-18 13:16:10 -0400325 } else if ((secondHeader.revision != 0x00010000) && valid) {
326 valid -= 2;
srs5694fed16d02010-01-27 23:03:40 -0500327 cout << "Unsupported GPT version in backup header; read 0x";
328 cout.width(8);
329 cout << hex << secondHeader.revision << ", should be\n0x";
330 cout.width(8);
331 cout << UINT32_C(0x00010000) << dec << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400332 } // if/else/if
333
srs56942a9f5da2009-08-26 00:48:01 -0400334 // If MBR bad, check for an Apple disk signature
srs5694e35eb1b2009-09-14 00:29:34 -0400335 if ((protectiveMBR.GetValidity() == invalid) &&
srs5694e4ac11e2009-08-31 10:13:04 -0400336 (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
srs56942a9f5da2009-08-26 00:48:01 -0400337 (mainHeader.signature << 32) == APM_SIGNATURE2)) {
srs5694221e0872009-08-29 15:00:31 -0400338 apmFound = 1; // Will display warning message later
srs56943f2fe992009-11-24 18:28:18 -0500339 } // if
srs5694fed16d02010-01-27 23:03:40 -0500340 cout.fill(' ');
srs56942a9f5da2009-08-26 00:48:01 -0400341
srs5694fed16d02010-01-27 23:03:40 -0500342 return valid;
srs5694e7b4ff92009-08-18 13:16:10 -0400343} // GPTData::CheckHeaderValidity()
344
345// Check the header CRC to see if it's OK...
srs5694cb76c672010-02-11 22:22:22 -0500346// Note: Must be called with header in LITTLE-ENDIAN
347// (x86, x86-64, etc.) byte order.
srs5694e7b4ff92009-08-18 13:16:10 -0400348int GPTData::CheckHeaderCRC(struct GPTHeader* header) {
srs5694978041c2009-09-21 20:51:47 -0400349 uint32_t oldCRC, newCRC, hSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400350
srs56942a9f5da2009-08-26 00:48:01 -0400351 // Back up old header CRC and then blank it, since it must be 0 for
srs5694e7b4ff92009-08-18 13:16:10 -0400352 // computation to be valid
353 oldCRC = header->headerCRC;
354 header->headerCRC = UINT32_C(0);
srs5694978041c2009-09-21 20:51:47 -0400355 hSize = header->headerSize;
356
357 // If big-endian system, reverse byte order
358 if (IsLittleEndian() == 0) {
359 ReverseBytes(&oldCRC, 4);
360 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400361
362 // Initialize CRC functions...
363 chksum_crc32gentab();
364
365 // Compute CRC, restore original, and return result of comparison
366 newCRC = chksum_crc32((unsigned char*) header, HEADER_SIZE);
srs5694978041c2009-09-21 20:51:47 -0400367 header->headerCRC = oldCRC;
srs5694e7b4ff92009-08-18 13:16:10 -0400368 return (oldCRC == newCRC);
369} // GPTData::CheckHeaderCRC()
370
srs56946699b012010-02-04 00:55:30 -0500371// Recompute all the CRCs. Must be called before saving if any changes have
372// been made. Must be called on platform-ordered data (this function reverses
373// byte order and then undoes that reversal.)
srs5694e7b4ff92009-08-18 13:16:10 -0400374void GPTData::RecomputeCRCs(void) {
srs5694978041c2009-09-21 20:51:47 -0400375 uint32_t crc, hSize, trueNumParts;
srs56942a9f5da2009-08-26 00:48:01 -0400376 int littleEndian = 1;
srs5694e7b4ff92009-08-18 13:16:10 -0400377
378 // Initialize CRC functions...
379 chksum_crc32gentab();
380
srs56946699b012010-02-04 00:55:30 -0500381 // Save some key data from header before reversing byte order....
382 trueNumParts = mainHeader.numParts;
srs5694978041c2009-09-21 20:51:47 -0400383 hSize = mainHeader.headerSize;
srs56946699b012010-02-04 00:55:30 -0500384
385 if ((littleEndian = IsLittleEndian()) == 0) {
386 ReversePartitionBytes();
387 ReverseHeaderBytes(&mainHeader);
388 ReverseHeaderBytes(&secondHeader);
389 } // if
srs56942a9f5da2009-08-26 00:48:01 -0400390
srs5694e7b4ff92009-08-18 13:16:10 -0400391 // Compute CRC of partition tables & store in main and secondary headers
srs56942a9f5da2009-08-26 00:48:01 -0400392 crc = chksum_crc32((unsigned char*) partitions, trueNumParts * GPT_SIZE);
srs5694e7b4ff92009-08-18 13:16:10 -0400393 mainHeader.partitionEntriesCRC = crc;
394 secondHeader.partitionEntriesCRC = crc;
srs56942a9f5da2009-08-26 00:48:01 -0400395 if (littleEndian == 0) {
srs5694221e0872009-08-29 15:00:31 -0400396 ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
397 ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
srs56942a9f5da2009-08-26 00:48:01 -0400398 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400399
400 // Zero out GPT tables' own CRCs (required for correct computation)
401 mainHeader.headerCRC = 0;
402 secondHeader.headerCRC = 0;
403
404 // Compute & store CRCs of main & secondary headers...
srs5694978041c2009-09-21 20:51:47 -0400405 crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400406 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400407 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400408 mainHeader.headerCRC = crc;
srs5694978041c2009-09-21 20:51:47 -0400409 crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
srs56942a9f5da2009-08-26 00:48:01 -0400410 if (littleEndian == 0)
srs5694221e0872009-08-29 15:00:31 -0400411 ReverseBytes(&crc, 4);
srs5694e7b4ff92009-08-18 13:16:10 -0400412 secondHeader.headerCRC = crc;
srs56946699b012010-02-04 00:55:30 -0500413
414 if ((littleEndian = IsLittleEndian()) == 0) {
415 ReverseHeaderBytes(&mainHeader);
416 ReverseHeaderBytes(&secondHeader);
417 ReversePartitionBytes();
418 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400419} // GPTData::RecomputeCRCs()
420
srs5694e7b4ff92009-08-18 13:16:10 -0400421// Rebuild the main GPT header, using the secondary header as a model.
422// Typically called when the main header has been found to be corrupt.
423void GPTData::RebuildMainHeader(void) {
424 int i;
425
426 mainHeader.signature = GPT_SIGNATURE;
427 mainHeader.revision = secondHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400428 mainHeader.headerSize = secondHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400429 mainHeader.headerCRC = UINT32_C(0);
430 mainHeader.reserved = secondHeader.reserved;
431 mainHeader.currentLBA = secondHeader.backupLBA;
432 mainHeader.backupLBA = secondHeader.currentLBA;
433 mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
434 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500435 mainHeader.diskGUID = secondHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400436 mainHeader.partitionEntriesLBA = UINT64_C(2);
437 mainHeader.numParts = secondHeader.numParts;
438 mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
439 mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
440 for (i = 0 ; i < GPT_RESERVED; i++)
441 mainHeader.reserved2[i] = secondHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500442 mainCrcOk = secondCrcOk;
srs5694e7b4ff92009-08-18 13:16:10 -0400443} // GPTData::RebuildMainHeader()
444
445// Rebuild the secondary GPT header, using the main header as a model.
446void GPTData::RebuildSecondHeader(void) {
447 int i;
448
449 secondHeader.signature = GPT_SIGNATURE;
450 secondHeader.revision = mainHeader.revision;
srs5694978041c2009-09-21 20:51:47 -0400451 secondHeader.headerSize = mainHeader.headerSize;
srs5694e7b4ff92009-08-18 13:16:10 -0400452 secondHeader.headerCRC = UINT32_C(0);
453 secondHeader.reserved = mainHeader.reserved;
454 secondHeader.currentLBA = mainHeader.backupLBA;
455 secondHeader.backupLBA = mainHeader.currentLBA;
456 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
457 secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
srs56946699b012010-02-04 00:55:30 -0500458 secondHeader.diskGUID = mainHeader.diskGUID;
srs5694e7b4ff92009-08-18 13:16:10 -0400459 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
460 secondHeader.numParts = mainHeader.numParts;
461 secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
462 secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
463 for (i = 0 ; i < GPT_RESERVED; i++)
464 secondHeader.reserved2[i] = mainHeader.reserved2[i];
srs5694546a9c72010-01-26 16:00:26 -0500465 secondCrcOk = mainCrcOk;
srs5694e4ac11e2009-08-31 10:13:04 -0400466} // GPTData::RebuildSecondHeader()
467
468// Search for hybrid MBR entries that have no corresponding GPT partition.
469// Returns number of such mismatches found
470int GPTData::FindHybridMismatches(void) {
srs5694e321d442010-01-29 17:44:04 -0500471 int i, found, numFound = 0;
472 uint32_t j;
srs5694e4ac11e2009-08-31 10:13:04 -0400473 uint64_t mbrFirst, mbrLast;
474
475 for (i = 0; i < 4; i++) {
476 if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
477 j = 0;
478 found = 0;
479 do {
480 mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
481 mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
482 if ((partitions[j].GetFirstLBA() == mbrFirst) &&
483 (partitions[j].GetLastLBA() == mbrLast))
484 found = 1;
485 j++;
486 } while ((!found) && (j < mainHeader.numParts));
487 if (!found) {
488 numFound++;
srs5694fed16d02010-01-27 23:03:40 -0500489 cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
490 << i + 1 << ", of type 0x";
491 cout.fill('0');
492 cout.setf(ios::uppercase);
493 cout.width(2);
494 cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
495 << "has no corresponding GPT partition! You may continue, but this condition\n"
496 << "might cause data loss in the future!\a\n" << dec;
497 cout.fill(' ');
srs5694e4ac11e2009-08-31 10:13:04 -0400498 } // if
499 } // if
500 } // for
501 return numFound;
502} // GPTData::FindHybridMismatches
503
504// Find overlapping partitions and warn user about them. Returns number of
505// overlapping partitions.
506int GPTData::FindOverlaps(void) {
srs5694e321d442010-01-29 17:44:04 -0500507 int problems = 0;
508 uint32_t i, j;
srs5694e4ac11e2009-08-31 10:13:04 -0400509
510 for (i = 1; i < mainHeader.numParts; i++) {
511 for (j = 0; j < i; j++) {
srs56940a697312010-01-28 21:10:52 -0500512 if (partitions[i].DoTheyOverlap(partitions[j])) {
srs5694e4ac11e2009-08-31 10:13:04 -0400513 problems++;
srs5694fed16d02010-01-27 23:03:40 -0500514 cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
515 cout << " Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
516 << " to " << partitions[i].GetLastLBA() << "\n";
517 cout << " Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
518 << " to " << partitions[j].GetLastLBA() << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400519 } // if
520 } // for j...
521 } // for i...
522 return problems;
523} // GPTData::FindOverlaps()
524
srs569455d92612010-03-07 22:16:07 -0500525// Find partitions that are insane -- they start after they end or are too
526// big for the disk. (The latter should duplicate detection of overlaps
527// with GPT backup data structures, but better to err on the side of
528// redundant tests than to miss something....)
529int GPTData::FindInsanePartitions(void) {
530 uint32_t i;
531 int problems = 0;
532
533 for (i = 0; i < mainHeader.numParts; i++) {
534 if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
535 problems++;
536 cout << "\nProblem: partition " << i << " ends before it begins.\n";
537 } // if
538 if (partitions[i].GetLastLBA() >= diskSize) {
539 problems++;
540 cout << "\nProblem: partition " << i << " is too big for the disk.\n";
541 } // if
542 } // for
543 return problems;
544} // GPTData::FindInsanePartitions(void)
545
546
srs5694e4ac11e2009-08-31 10:13:04 -0400547/******************************************************************
548 * *
549 * Begin functions that load data from disk or save data to disk. *
550 * *
551 ******************************************************************/
552
553// Scan for partition data. This function loads the MBR data (regular MBR or
554// protective MBR) and loads BSD disklabel data (which is probably invalid).
555// It also looks for APM data, forces a load of GPT data, and summarizes
556// the results.
srs5694546a9c72010-01-26 16:00:26 -0500557void GPTData::PartitionScan(void) {
srs5694e4ac11e2009-08-31 10:13:04 -0400558 BSDData bsdDisklabel;
srs5694e4ac11e2009-08-31 10:13:04 -0400559
560 // Read the MBR & check for BSD disklabel
srs5694546a9c72010-01-26 16:00:26 -0500561 protectiveMBR.ReadMBRData(&myDisk);
562 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400563
564 // Load the GPT data, whether or not it's valid
srs5694546a9c72010-01-26 16:00:26 -0500565 ForceLoadGPTData();
srs5694ba00fed2010-01-12 18:18:36 -0500566
567 if (!beQuiet) {
srs5694fed16d02010-01-27 23:03:40 -0500568 cout << "Partition table scan:\n";
srs5694ba00fed2010-01-12 18:18:36 -0500569 protectiveMBR.ShowState();
570 bsdDisklabel.ShowState();
571 ShowAPMState(); // Show whether there's an Apple Partition Map present
572 ShowGPTState(); // Show GPT status
srs5694fed16d02010-01-27 23:03:40 -0500573 cout << "\n";
srs5694ba00fed2010-01-12 18:18:36 -0500574 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400575
576 if (apmFound) {
srs5694fed16d02010-01-27 23:03:40 -0500577 cout << "\n*******************************************************************\n"
578 << "This disk appears to contain an Apple-format (APM) partition table!\n";
srs56945d58fe02010-01-03 20:57:08 -0500579 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500580 cout << "It will be destroyed if you continue!\n";
srs56945d58fe02010-01-03 20:57:08 -0500581 } // if
srs5694fed16d02010-01-27 23:03:40 -0500582 cout << "*******************************************************************\n\n\a";
srs5694e4ac11e2009-08-31 10:13:04 -0400583 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400584} // GPTData::PartitionScan()
585
586// Read GPT data from a disk.
srs56940a697312010-01-28 21:10:52 -0500587int GPTData::LoadPartitions(const string & deviceFilename) {
srs569408bb0da2010-02-19 17:19:55 -0500588 BSDData bsdDisklabel;
srs5694e321d442010-01-29 17:44:04 -0500589 int err, allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -0500590 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -0400591
srs5694546a9c72010-01-26 16:00:26 -0500592 if (myDisk.OpenForRead(deviceFilename)) {
srs569455d92612010-03-07 22:16:07 -0500593 err = myDisk.OpenForWrite(deviceFilename);
594 if ((err == 0) && (!justLooking)) {
595 cout << "\aNOTE: Write test failed with error number " << errno
596 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
597#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
598 cout << "You may be able to enable writes by exiting this program, typing\n"
599 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
600 << "program.\n";
601#endif
602 cout << "\n";
603 } // if
604 myDisk.Close(); // Close and re-open read-only in case of bugs
605 } else allOK = 0; // if
606
607 if (allOK && myDisk.OpenForRead(deviceFilename)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400608 // store disk information....
srs5694546a9c72010-01-26 16:00:26 -0500609 diskSize = myDisk.DiskSize(&err);
610 blockSize = (uint32_t) myDisk.GetBlockSize();
611 sectorAlignment = myDisk.FindAlignment();
srs5694fed16d02010-01-27 23:03:40 -0500612 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500613 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400614
srs5694ba00fed2010-01-12 18:18:36 -0500615 whichWasUsed = UseWhichPartitions();
616 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400617 case use_mbr:
618 XFormPartitions();
619 break;
620 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500621 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400622// bsdDisklabel.DisplayBSDData();
623 ClearGPTData();
624 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500625 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400626 break;
627 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500628 mbrState = protectiveMBR.GetValidity();
629 if ((mbrState == invalid) || (mbrState == mbr))
630 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400631 break;
632 case use_new:
633 ClearGPTData();
634 protectiveMBR.MakeProtectiveMBR();
635 break;
srs56943c0af382010-01-15 19:19:18 -0500636 case use_abort:
637 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500638 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500639 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400640 } // switch
641
srs569455d92612010-03-07 22:16:07 -0500642 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500643 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500644 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400645 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400646 } else {
647 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400648 } // if/else
649 return (allOK);
650} // GPTData::LoadPartitions()
651
652// Loads the GPT, as much as possible. Returns 1 if this seems to have
653// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500654int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500655 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400656
srs5694cb76c672010-02-11 22:22:22 -0500657 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400658
srs5694cb76c672010-02-11 22:22:22 -0500659 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
660 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
661 } else {
srs569408bb0da2010-02-19 17:19:55 -0500662 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
663 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500664 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
665 << "secondary header from the last sector of the disk! You should use 'v' to\n"
666 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
667 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500668 } // if/else
669 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400670 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400671
672 // Return valid headers code: 0 = both headers bad; 1 = main header
673 // good, backup bad; 2 = backup header good, main header bad;
674 // 3 = both headers good. Note these codes refer to valid GPT
675 // signatures and version numbers; more subtle problems will elude
676 // this check!
677 validHeaders = CheckHeaderValidity();
678
679 // Read partitions (from primary array)
680 if (validHeaders > 0) { // if at least one header is OK....
681 // GPT appears to be valid....
682 state = gpt_valid;
683
684 // We're calling the GPT valid, but there's a possibility that one
685 // of the two headers is corrupt. If so, use the one that seems to
686 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500687 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500688 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
689 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400690 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500691 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400692 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500693 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500694 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
695 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500696 RebuildMainHeader();
697 state = gpt_corrupt;
698 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400699 } // if/else/if
700
srs5694546a9c72010-01-26 16:00:26 -0500701 // Figure out which partition table to load....
702 // Load the main partition table, since either its header's CRC is OK or the
703 // backup header's CRC is not OK....
704 if (mainCrcOk || !secondCrcOk) {
705 if (LoadMainTable() == 0)
706 allOK = 0;
707 } else { // bad main header CRC and backup header CRC is OK
708 state = gpt_corrupt;
709 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500710 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500711 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500712 } else { // backup table bad, bad main header CRC, but try main table in desperation....
713 if (LoadMainTable() == 0) {
714 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500715 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500716 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500717 } // if
718 } // if/else (LoadSecondTableAsMain())
719 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400720
srs5694cb76c672010-02-11 22:22:22 -0500721 if (loadedTable == 1)
722 secondPartsCrcOk = CheckTable(&secondHeader);
723 else if (loadedTable == 2)
724 mainPartsCrcOk = CheckTable(&mainHeader);
725 else
726 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400727
srs5694546a9c72010-01-26 16:00:26 -0500728 // Problem with main partition table; if backup is OK, use it instead....
729 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
730 state = gpt_corrupt;
731 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500732 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500733 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
734 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500735 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500736
srs5694e4ac11e2009-08-31 10:13:04 -0400737 // Check for valid CRCs and warn if there are problems
738 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
739 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500740 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400741 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500742 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400743 } else {
744 state = gpt_invalid;
745 } // if/else
746 return allOK;
747} // GPTData::ForceLoadGPTData()
748
srs5694247657a2009-11-26 18:36:12 -0500749// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400750// main GPT header in memory MUST be valid for this call to do anything
751// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500752// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400753int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500754 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400755} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400756
757// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500758// table. Used in repair functions, and when starting up if the main
759// partition table is damaged.
760// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
761int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500762 return LoadPartitionTable(secondHeader, myDisk);
763} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400764
srs5694cb76c672010-02-11 22:22:22 -0500765// Load a single GPT header (main or backup) from the specified disk device and
766// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
767// value appropriately.
768// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
769// failure.
770int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
771 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500772 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500773
774 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500775 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500776 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
777 allOK = 0;
778 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500779 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500780
srs56941c6f8b02010-02-21 11:09:20 -0500781 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500782 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500783 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500784 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500785
srs569455d92612010-03-07 22:16:07 -0500786 if (allOK && (mainHeader.numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500787 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500788 }
srs56941c6f8b02010-02-21 11:09:20 -0500789
790 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500791 return allOK;
792} // GPTData::LoadHeader
793
794// Load a partition table (either main or secondary) from the specified disk,
795// using header as a reference for what to load. If sector != 0 (the default
796// is 0), loads from the specified sector; otherwise loads from the sector
797// indicated in header.
798// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
799int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
800 uint32_t sizeOfParts, newCRC;
801 int retval;
802
803 if (disk.OpenForRead()) {
804 if (sector == 0) {
805 retval = disk.Seek(header.partitionEntriesLBA);
806 } else {
807 retval = disk.Seek(sector);
808 } // if/else
srs569455d92612010-03-07 22:16:07 -0500809 if (retval == 1)
810 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500811 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500812 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
813 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500814 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500815 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500816 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400817 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500818 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400819 if (IsLittleEndian() == 0)
820 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500821 if (!mainPartsCrcOk) {
822 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400823 } // if
824 } else {
srs5694cb76c672010-02-11 22:22:22 -0500825 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400826 } // if/else
827 } else {
srs5694fed16d02010-01-27 23:03:40 -0500828 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500829 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500830 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400831 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500832 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500833} // GPTData::LoadPartitionsTable()
834
835// Check the partition table pointed to by header, but don't keep it
836// around.
837// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
838int GPTData::CheckTable(struct GPTHeader *header) {
839 uint32_t sizeOfParts, newCRC;
840 uint8_t *storage;
841 int newCrcOk = 0;
842
843 // Load backup partition table into temporary storage to check
844 // its CRC and store the results, then discard this temporary
845 // storage, since we don't use it in any but recovery operations
846 if (myDisk.Seek(header->partitionEntriesLBA)) {
847 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
848 storage = new uint8_t[sizeOfParts];
849 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
850 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
851 } else {
852 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
853 newCrcOk = (newCRC == header->partitionEntriesCRC);
854 } // if/else
855 delete[] storage;
856 } // if
857 return newCrcOk;
858} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400859
srs5694e7b4ff92009-08-18 13:16:10 -0400860// Writes GPT (and protective MBR) to disk. Returns 1 on successful
861// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500862int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500863 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500864 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400865
srs56946699b012010-02-04 00:55:30 -0500866 littleEndian = IsLittleEndian();
867
srs5694fed16d02010-01-27 23:03:40 -0500868 if (device == "") {
869 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400870 } // if
871
872 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500873
874 // This test should only fail on read-only disks....
875 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500876 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500877 allOK = 0;
878 } // if
879
srs5694e7b4ff92009-08-18 13:16:10 -0400880 // Is there enough space to hold the GPT headers and partition tables,
881 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400882 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400883 allOK = 0;
884 } // if
885
886 // Check that disk is really big enough to handle this...
887 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500888 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
889 << "problem (or it might not). Aborting!\n(Disk size is "
890 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400891 allOK = 0;
892 } // if
srs5694247657a2009-11-26 18:36:12 -0500893 // Check that second header is properly placed. Warn and ask if this should
894 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500895 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500896 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
897 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500898 if (GetYN() == 'Y') {
899 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500900 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500901 } else {
srs5694fed16d02010-01-27 23:03:40 -0500902 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500903 } // if correction requested
904 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400905
srs569455d92612010-03-07 22:16:07 -0500906 // Check for overlapping or insane partitions....
907 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400908 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500909 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400910 } // if
911
912 // Check for mismatched MBR and GPT data, but let it pass if found
913 // (function displays warning message)
914 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400915
916 RecomputeCRCs();
917
srs5694ba00fed2010-01-12 18:18:36 -0500918 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500919 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
920 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500921 answer = GetYN();
922 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500923 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400924 } else {
925 allOK = 0;
926 } // if/else
927 } // if
928
929 // Do it!
930 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500931 // First, write the protective MBR...
932 allOK = protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400933
srs5694546a9c72010-01-26 16:00:26 -0500934 if (allOK && myDisk.OpenForWrite(device)) {
srs5694e7b4ff92009-08-18 13:16:10 -0400935 // Now write the main GPT header...
srs5694cb76c672010-02-11 22:22:22 -0500936 allOK = SaveHeader(&mainHeader, myDisk, 1);
srs5694e7b4ff92009-08-18 13:16:10 -0400937
938 // Now write the main partition tables...
srs5694e4ac11e2009-08-31 10:13:04 -0400939 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500940 allOK = SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
srs56941e093722010-01-05 00:14:19 -0500941 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400942
943 // Now seek to near the end to write the secondary GPT....
srs5694cb76c672010-02-11 22:22:22 -0500944 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
945 if (!allOK)
946 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
947 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400948
949 // Now write the secondary GPT header...
srs56941e093722010-01-05 00:14:19 -0500950 if (allOK) {
srs5694cb76c672010-02-11 22:22:22 -0500951 allOK = SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
srs56946699b012010-02-04 00:55:30 -0500952 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400953
954 // re-read the partition table
955 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500956 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400957 } // if
958
959 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500960 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400961 } else {
srs5694fed16d02010-01-27 23:03:40 -0500962 cerr << "Warning! An error was reported when writing the partition table! This error\n"
963 << "MIGHT be harmless, but you may have trashed the disk! Use parted and, if\n"
964 << "necessary, restore your original partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400965 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500966 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400967 } else {
srs5694fed16d02010-01-27 23:03:40 -0500968 cerr << "Unable to open device " << device << " for writing! Errno is "
969 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400970 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400971 } // if/else
972 } else {
srs5694fed16d02010-01-27 23:03:40 -0500973 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400974 } // if
975
976 return (allOK);
977} // GPTData::SaveGPTData()
978
979// Save GPT data to a backup file. This function does much less error
980// checking than SaveGPTData(). It can therefore preserve many types of
981// corruption for later analysis; however, it preserves only the MBR,
982// the main GPT header, the backup GPT header, and the main partition
983// table; it discards the backup partition table, since it should be
984// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500985int GPTData::SaveGPTBackup(const string & filename) {
986 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500987 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400988
srs5694546a9c72010-01-26 16:00:26 -0500989 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500990 // Recomputing the CRCs is likely to alter them, which could be bad
991 // if the intent is to save a potentially bad GPT for later analysis;
992 // but if we don't do this, we get bogus errors when we load the
993 // backup. I'm favoring misses over false alarms....
994 RecomputeCRCs();
995
srs5694546a9c72010-01-26 16:00:26 -0500996 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400997
srs5694cb76c672010-02-11 22:22:22 -0500998 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500999 // MBR write closed disk, so re-open and seek to end....
1000 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -05001001 allOK = SaveHeader(&mainHeader, backupFile, 1);
1002 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -04001003
srs5694e7b4ff92009-08-18 13:16:10 -04001004 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001005 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001006
srs5694cb76c672010-02-11 22:22:22 -05001007 if (allOK)
1008 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001009
1010 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001011 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001012 } else {
srs5694fed16d02010-01-27 23:03:40 -05001013 cerr << "Warning! An error was reported when writing the backup file.\n"
1014 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001015 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001016 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001017 } else {
srs5694fed16d02010-01-27 23:03:40 -05001018 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001019 allOK = 0;
1020 } // if/else
1021 return allOK;
1022} // GPTData::SaveGPTBackup()
1023
srs5694cb76c672010-02-11 22:22:22 -05001024// Write a GPT header (main or backup) to the specified sector. Used by both
1025// the SaveGPTData() and SaveGPTBackup() functions.
1026// Should be passed an architecture-appropriate header (DO NOT call
1027// ReverseHeaderBytes() on the header before calling this function)
1028// Returns 1 on success, 0 on failure
1029int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1030 int littleEndian, allOK = 1;
1031
1032 littleEndian = IsLittleEndian();
1033 if (!littleEndian)
1034 ReverseHeaderBytes(header);
1035 if (disk.Seek(sector)) {
1036 if (disk.Write(header, 512) == -1)
1037 allOK = 0;
1038 } else allOK = 0; // if (disk.Seek()...)
1039 if (!littleEndian)
1040 ReverseHeaderBytes(header);
1041 return allOK;
1042} // GPTData::SaveHeader()
1043
1044// Save the partitions to the specified sector. Used by both the SaveGPTData()
1045// and SaveGPTBackup() functions.
1046// Should be passed an architecture-appropriate header (DO NOT call
1047// ReverseHeaderBytes() on the header before calling this function)
1048// Returns 1 on success, 0 on failure
1049int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1050 int littleEndian, allOK = 1;
1051
1052 littleEndian = IsLittleEndian();
1053 if (disk.Seek(sector)) {
1054 if (!littleEndian)
1055 ReversePartitionBytes();
1056 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1057 allOK = 0;
1058 if (!littleEndian)
1059 ReversePartitionBytes();
1060 } else allOK = 0; // if (myDisk.Seek()...)
1061 return allOK;
1062} // GPTData::SavePartitionTable()
1063
srs5694e7b4ff92009-08-18 13:16:10 -04001064// Load GPT data from a backup file created by SaveGPTBackup(). This function
1065// does minimal error checking. It returns 1 if it completed successfully,
1066// 0 if there was a problem. In the latter case, it creates a new empty
1067// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001068int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001069 int allOK = 1, val, err;
1070 uint32_t numParts, sizeOfEntries;
1071 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001072 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001073
srs5694546a9c72010-01-26 16:00:26 -05001074 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001075 if (IsLittleEndian() == 0)
1076 littleEndian = 0;
1077
srs5694e7b4ff92009-08-18 13:16:10 -04001078 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001079 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001080
srs5694cb76c672010-02-11 22:22:22 -05001081 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001082
srs5694cb76c672010-02-11 22:22:22 -05001083 // Check backup file size and rebuild second header if file is right
1084 // size to be direct dd copy of MBR, main header, and main partition
1085 // table; if other size, treat it like a GPT fdisk-generated backup
1086 // file
1087 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1088 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1089 if (shortBackup) {
1090 RebuildSecondHeader();
1091 secondCrcOk = mainCrcOk;
1092 } else {
1093 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1094 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001095
srs5694e7b4ff92009-08-18 13:16:10 -04001096 // Return valid headers code: 0 = both headers bad; 1 = main header
1097 // good, backup bad; 2 = backup header good, main header bad;
1098 // 3 = both headers good. Note these codes refer to valid GPT
1099 // signatures and version numbers; more subtle problems will elude
1100 // this check!
1101 if ((val = CheckHeaderValidity()) > 0) {
1102 if (val == 2) { // only backup header seems to be good
1103 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001104 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001105 } else { // main header is OK
1106 numParts = mainHeader.numParts;
1107 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1108 } // if/else
1109
1110 SetGPTSize(numParts);
1111
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;
1163 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
1164 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";
srs5694fed16d02010-01-27 23:03:40 -05001258 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1259 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);
srs5694fed16d02010-01-27 23:03:40 -05001262 cout << "Total free space is " << totalFree << " sectors ("
1263 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1264 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001265 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001266 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001267 } // for
1268} // GPTData::DisplayGPTData()
1269
srs5694e4ac11e2009-08-31 10:13:04 -04001270// Show detailed information on the specified partition
1271void GPTData::ShowPartDetails(uint32_t partNum) {
1272 if (partitions[partNum].GetFirstLBA() != 0) {
1273 partitions[partNum].ShowDetails(blockSize);
1274 } else {
srs5694fed16d02010-01-27 23:03:40 -05001275 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001276 } // if
1277} // GPTData::ShowPartDetails()
1278
srs5694e4ac11e2009-08-31 10:13:04 -04001279/**************************************************************************
1280 * *
1281 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1282 * (some of these functions may require user interaction) *
1283 * *
1284 **************************************************************************/
1285
srs569408bb0da2010-02-19 17:19:55 -05001286// Examines the MBR & GPT data to determine which set of data to use: the
1287// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1288// a new set of partitions (use_new). A return value of use_abort indicates
1289// that this function couldn't determine what to do. Overriding functions
1290// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001291WhichToUse GPTData::UseWhichPartitions(void) {
1292 WhichToUse which = use_new;
1293 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001294
1295 mbrState = protectiveMBR.GetValidity();
1296
1297 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001298 cout << "\n***************************************************************\n"
1299 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001300 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001301 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1302 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001303 } // if
srs5694fed16d02010-01-27 23:03:40 -05001304 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001305 which = use_mbr;
1306 } // if
1307
1308 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001309 cout << "\n**********************************************************************\n"
1310 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1311 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001312 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001313 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1314 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1315 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001316 } // if
srs5694fed16d02010-01-27 23:03:40 -05001317 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001318 which = use_bsd;
1319 } // if
1320
1321 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001322 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001323 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001324 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001325 } // if
1326 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001327 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001328 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001329 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001330 } // if
1331 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001332 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001333 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001334 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001335 } // if
1336 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001337 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001338 } // if
1339
srs5694e4ac11e2009-08-31 10:13:04 -04001340 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001341 if (mbrState == gpt) {
1342 cout << "\a\a****************************************************************************\n"
1343 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1344 << "verification and recovery are STRONGLY recommended.\n"
1345 << "****************************************************************************\n";
1346 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001347 } else {
srs569408bb0da2010-02-19 17:19:55 -05001348 which = use_abort;
1349 } // if/else MBR says disk is GPT
1350 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001351
1352 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001353 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001354
1355 return which;
1356} // UseWhichPartitions()
1357
srs569408bb0da2010-02-19 17:19:55 -05001358// Convert MBR partition table into GPT form.
1359void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001360 int i, numToConvert;
1361 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001362
1363 // Clear out old data & prepare basics....
1364 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001365 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001366
1367 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001368 if (mainHeader.numParts > (MAX_MBR_PARTS))
1369 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001370 else
1371 numToConvert = mainHeader.numParts;
1372
1373 for (i = 0; i < numToConvert; i++) {
1374 origType = protectiveMBR.GetType(i);
1375 // don't waste CPU time trying to convert extended, hybrid protective, or
1376 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001377 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001378 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001379 partitions[i] = protectiveMBR.AsGPT(i);
1380 } // for
1381
1382 // Convert MBR into protective MBR
1383 protectiveMBR.MakeProtectiveMBR();
1384
1385 // Record that all original CRCs were OK so as not to raise flags
1386 // when doing a disk verification
1387 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001388} // GPTData::XFormPartitions()
1389
1390// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001391// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001392// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001393int GPTData::XFormDisklabel(uint32_t partNum) {
1394 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001395 int goOn = 1, numDone = 0;
1396 BSDData disklabel;
1397
srs569408bb0da2010-02-19 17:19:55 -05001398 if (GetPartRange(&low, &high) == 0) {
1399 goOn = 0;
1400 cout << "No partitions!\n";
1401 } // if
1402 if (partNum > high) {
1403 goOn = 0;
1404 cout << "Specified partition is invalid!\n";
1405 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001406
srs569408bb0da2010-02-19 17:19:55 -05001407 // If all is OK, read the disklabel and convert it.
1408 if (goOn) {
1409 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1410 partitions[partNum].GetLastLBA());
1411 if ((goOn) && (disklabel.IsDisklabel())) {
1412 numDone = XFormDisklabel(&disklabel);
1413 if (numDone == 1)
1414 cout << "Converted 1 BSD partition.\n";
1415 else
1416 cout << "Converted " << numDone << " BSD partitions.\n";
1417 } else {
1418 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1419 } // if/else
1420 } // if
1421 if (numDone > 0) { // converted partitions; delete carrier
1422 partitions[partNum].BlankPartition();
1423 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001424 return numDone;
srs569455d92612010-03-07 22:16:07 -05001425} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001426
1427// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001428int GPTData::XFormDisklabel(BSDData* disklabel) {
1429 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001430
srs569408bb0da2010-02-19 17:19:55 -05001431 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001432 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001433 partNum = FindFirstFreePart();
1434 if (partNum >= 0) {
1435 partitions[partNum] = disklabel->AsGPT(i);
1436 if (partitions[partNum].IsUsed())
1437 numDone++;
1438 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001439 } // for
srs569408bb0da2010-02-19 17:19:55 -05001440 if (partNum == -1)
1441 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001442 } // if
1443
1444 // Record that all original CRCs were OK so as not to raise flags
1445 // when doing a disk verification
1446 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1447
1448 return numDone;
1449} // GPTData::XFormDisklabel(BSDData* disklabel)
1450
srs569408bb0da2010-02-19 17:19:55 -05001451// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1452// partition has the active/bootable flag UNset and uses the GPT fdisk
1453// type code divided by 0x0100 as the MBR type code.
1454// Returns 1 if operation was 100% successful, 0 if there were ANY
1455// problems.
srs5694978041c2009-09-21 20:51:47 -04001456int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001457 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001458
srs5694978041c2009-09-21 20:51:47 -04001459 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001460 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001461 allOK = 0;
1462 } // if
1463 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001464 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001465 allOK = 0;
1466 } // if
1467 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001468 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001469 allOK = 0;
1470 } // if
1471 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1472 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1473 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001474 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1475 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001476 } // if
srs5694978041c2009-09-21 20:51:47 -04001477 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001478 (uint32_t) partitions[gptPart].GetLengthLBA(),
1479 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001480 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001481 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1482 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1483 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001484 allOK = 0;
1485 } // if/else
1486 return allOK;
1487} // GPTData::OnePartToMBR()
1488
srs569455d92612010-03-07 22:16:07 -05001489// Convert partitions to MBR form (primary and logical) and return
1490// the number done. Partitions are specified in a PartNotes variable,
1491// which includes pointers to GPT partition numbers. A partition number
1492// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1493// location in the table, and MBR_EMPTY means not to create a partition
1494// in that table position. If the partition type entry for a partition
1495// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001496// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001497// protective partitions or extended partitions.
1498int GPTData::PartsToMBR(PartNotes & notes) {
1499 int mbrNum = 0, numConverted = 0;
1500 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001501
srs569455d92612010-03-07 22:16:07 -05001502 protectiveMBR.EmptyMBR();
1503 protectiveMBR.SetDiskSize(diskSize);
1504 notes.Rewind();
1505 while (notes.GetNextInfo(&convInfo) >= 0) {
1506 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1507 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1508 if (convInfo.hexCode != 0)
1509 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1510 if (convInfo.active)
1511 protectiveMBR.SetPartBootable(mbrNum);
1512 mbrNum++;
1513 } // if
1514 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1515 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1516 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1517 protectiveMBR.SetHybrid();
1518 } else {
1519 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1520 } // if/else
1521 mbrNum++;
1522 } // if EFI GPT partition specified
1523 } // for
1524 // Now do logical partition(s)...
1525 protectiveMBR.SetDisk(&myDisk);
1526 numConverted += protectiveMBR.CreateLogicals(notes);
1527// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001528 return numConverted;
1529} // GPTData::PartsToMBR()
1530
srs5694e4ac11e2009-08-31 10:13:04 -04001531
1532/**********************************************************************
1533 * *
1534 * Functions that adjust GPT data structures WITHOUT user interaction *
1535 * (they may display information for the user's benefit, though) *
1536 * *
1537 **********************************************************************/
1538
1539// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001540// necessary, copies data if it already exists. Returns 1 if all goes
1541// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001542int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001543 GPTPart* newParts;
1544 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001545 uint32_t i, high, copyNum;
1546 int allOK = 1;
1547
1548 // First, adjust numEntries upward, if necessary, to get a number
1549 // that fills the allocated sectors
1550 i = blockSize / GPT_SIZE;
1551 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001552 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001553 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001554 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001555 } // if
1556
srs5694247657a2009-11-26 18:36:12 -05001557 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001558 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001559 // partition table, which causes problems when loading data from a RAID
1560 // array that's been expanded because this function is called when loading
1561 // data.
srs569455d92612010-03-07 22:16:07 -05001562 if (((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1563 || (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
1575 if (numEntries < mainHeader.numParts)
1576 copyNum = numEntries;
1577 else
1578 copyNum = mainHeader.numParts;
1579 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
1589 mainHeader.numParts = numEntries;
1590 secondHeader.numParts = numEntries;
1591 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1592 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1593 MoveSecondHeaderToEnd();
1594 if (diskSize > 0)
1595 CheckGPTSize();
1596 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001597 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001598 allOK = 0;
1599 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001600 } // if/else
1601 return (allOK);
1602} // GPTData::SetGPTSize()
1603
1604// Blank the partition array
1605void GPTData::BlankPartitions(void) {
1606 uint32_t i;
1607
1608 for (i = 0; i < mainHeader.numParts; i++) {
1609 partitions[i].BlankPartition();
1610 } // for
1611} // GPTData::BlankPartitions()
1612
srs5694ba00fed2010-01-12 18:18:36 -05001613// Delete a partition by number. Returns 1 if successful,
1614// 0 if there was a problem. Returns 1 if partition was in
1615// range, 0 if it was out of range.
1616int GPTData::DeletePartition(uint32_t partNum) {
1617 uint64_t startSector, length;
1618 uint32_t low, high, numParts, retval = 1;;
1619
1620 numParts = GetPartRange(&low, &high);
1621 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1622 // In case there's a protective MBR, look for & delete matching
1623 // MBR partition....
1624 startSector = partitions[partNum].GetFirstLBA();
1625 length = partitions[partNum].GetLengthLBA();
1626 protectiveMBR.DeleteByLocation(startSector, length);
1627
1628 // Now delete the GPT partition
1629 partitions[partNum].BlankPartition();
1630 } else {
srs5694fed16d02010-01-27 23:03:40 -05001631 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001632 retval = 0;
1633 } // if/else
1634 return retval;
1635} // GPTData::DeletePartition(uint32_t partNum)
1636
srs569408bb0da2010-02-19 17:19:55 -05001637// Non-interactively create a partition.
1638// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001639uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001640 int retval = 1; // assume there'll be no problems
1641
1642 if (IsFreePartNum(partNum)) {
1643 Align(&startSector); // Align sector to correct multiple
1644 if (IsFree(startSector) && (startSector <= endSector)) {
1645 if (FindLastInFree(startSector) >= endSector) {
1646 partitions[partNum].SetFirstLBA(startSector);
1647 partitions[partNum].SetLastLBA(endSector);
1648 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001649 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001650 } else retval = 0; // if free space until endSector
1651 } else retval = 0; // if startSector is free
1652 } else retval = 0; // if legal partition number
1653 return retval;
1654} // GPTData::CreatePartition(partNum, startSector, endSector)
1655
srs5694e4ac11e2009-08-31 10:13:04 -04001656// Sort the GPT entries, eliminating gaps and making for a logical
1657// ordering. Relies on QuickSortGPT() for the bulk of the work
1658void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001659 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001660
1661 // First, find the last partition with data, so as not to
1662 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001663 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001664
1665 // Now swap empties with the last partitions, to simplify the logic
1666 // in the Quicksort function....
1667 i = 0;
1668 while (i < lastPart) {
1669 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001670 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001671 do {
1672 lastPart--;
1673 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001674 } // if
1675 i++;
1676 } // while
1677
srs5694546a9c72010-01-26 16:00:26 -05001678 // If there are more empties than partitions in the range from 0 to lastPart,
1679 // the above leaves lastPart set too high, so we've got to adjust it to
1680 // prevent empties from migrating to the top of the list....
1681 GetPartRange(&firstPart, &lastPart);
1682
srs5694e4ac11e2009-08-31 10:13:04 -04001683 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001684 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001685} // GPTData::SortGPT()
1686
srs569408bb0da2010-02-19 17:19:55 -05001687// Recursive quick sort algorithm for GPT partitions. Note that if there
1688// are any empties in the specified range, they'll be sorted to the
1689// start, resulting in a sorted set of partitions that begins with
1690// partition 2, 3, or higher.
1691void GPTData::QuickSortGPT(int start, int finish) {
1692 uint64_t starterValue; // starting location of median partition
1693 int left, right;
1694
1695 left = start;
1696 right = finish;
1697 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1698 do {
1699 while (partitions[left].GetFirstLBA() < starterValue)
1700 left++;
1701 while (partitions[right].GetFirstLBA() > starterValue)
1702 right--;
1703 if (left <= right)
1704 SwapPartitions(left++, right--);
1705 } while (left <= right);
1706 if (start < right) QuickSortGPT(start, right);
1707 if (finish > left) QuickSortGPT(left, finish);
1708} // GPTData::QuickSortGPT()
1709
1710// Swap the contents of two partitions.
1711// Returns 1 if successful, 0 if either partition is out of range
1712// (that is, not a legal number; either or both can be empty).
1713// Note that if partNum1 = partNum2 and this number is in range,
1714// it will be considered successful.
1715int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1716 GPTPart temp;
1717 int allOK = 1;
1718
1719 if ((partNum1 < mainHeader.numParts) && (partNum2 < mainHeader.numParts)) {
1720 if (partNum1 != partNum2) {
1721 temp = partitions[partNum1];
1722 partitions[partNum1] = partitions[partNum2];
1723 partitions[partNum2] = temp;
1724 } // if
1725 } else allOK = 0; // partition numbers are valid
1726 return allOK;
1727} // GPTData::SwapPartitions()
1728
srs5694e4ac11e2009-08-31 10:13:04 -04001729// Set up data structures for entirely new set of partitions on the
1730// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001731// Note that this function does NOT clear the protectiveMBR data
1732// structure, since it may hold the original MBR partitions if the
1733// program was launched on an MBR disk, and those may need to be
1734// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001735int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001736 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001737
1738 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001739 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001740 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001741 partitions = NULL;
1742 SetGPTSize(NUM_GPT_ENTRIES);
1743
1744 // Now initialize a bunch of stuff that's static....
1745 mainHeader.signature = GPT_SIGNATURE;
1746 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001747 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001748 mainHeader.reserved = 0;
1749 mainHeader.currentLBA = UINT64_C(1);
1750 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1751 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1752 for (i = 0; i < GPT_RESERVED; i++) {
1753 mainHeader.reserved2[i] = '\0';
1754 } // for
1755
1756 // Now some semi-static items (computed based on end of disk)
1757 mainHeader.backupLBA = diskSize - UINT64_C(1);
1758 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1759
1760 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001761 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001762
1763 // Copy main header to backup header
1764 RebuildSecondHeader();
1765
1766 // Blank out the partitions array....
1767 BlankPartitions();
1768
1769 // Flag all CRCs as being OK....
1770 mainCrcOk = 1;
1771 secondCrcOk = 1;
1772 mainPartsCrcOk = 1;
1773 secondPartsCrcOk = 1;
1774
1775 return (goOn);
1776} // GPTData::ClearGPTData()
1777
srs5694247657a2009-11-26 18:36:12 -05001778// Set the location of the second GPT header data to the end of the disk.
1779// Used internally and called by the 'e' option on the recovery &
1780// transformation menu, to help users of RAID arrays who add disk space
1781// to their arrays.
1782void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001783 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1784 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1785 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1786} // GPTData::FixSecondHeaderLocation()
1787
srs56940a697312010-01-28 21:10:52 -05001788int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001789 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001790
1791 if (!IsFreePartNum(partNum)) {
1792 partitions[partNum].SetName(theName);
1793 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001794
1795 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001796} // GPTData::SetName
1797
1798// Set the disk GUID to the specified value. Note that the header CRCs must
1799// be recomputed after calling this function.
1800void GPTData::SetDiskGUID(GUIDData newGUID) {
1801 mainHeader.diskGUID = newGUID;
1802 secondHeader.diskGUID = newGUID;
1803} // SetDiskGUID()
1804
1805// Set the unique GUID of the specified partition. Returns 1 on
1806// successful completion, 0 if there were problems (invalid
1807// partition number).
1808int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1809 int retval = 0;
1810
1811 if (pn < mainHeader.numParts) {
1812 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1813 partitions[pn].SetUniqueGUID(theGUID);
1814 retval = 1;
1815 } // if
1816 } // if
1817 return retval;
1818} // GPTData::SetPartitionGUID()
1819
srs5694ba00fed2010-01-12 18:18:36 -05001820// Change partition type code non-interactively. Returns 1 if
1821// successful, 0 if not....
1822int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1823 int retval = 1;
1824
1825 if (!IsFreePartNum(partNum)) {
1826 partitions[partNum].SetType(hexCode);
1827 } else retval = 0;
1828 return retval;
1829} // GPTData::ChangePartType()
1830
srs56941d1448a2009-12-31 21:20:19 -05001831// Adjust sector number so that it falls on a sector boundary that's a
1832// multiple of sectorAlignment. This is done to improve the performance
1833// of Western Digital Advanced Format disks and disks with similar
1834// technology from other companies, which use 4096-byte sectors
1835// internally although they translate to 512-byte sectors for the
1836// benefit of the OS. If partitions aren't properly aligned on these
1837// disks, some filesystem data structures can span multiple physical
1838// sectors, degrading performance. This function should be called
1839// only on the FIRST sector of the partition, not the last!
1840// This function returns 1 if the alignment was altered, 0 if it
1841// was unchanged.
1842int GPTData::Align(uint64_t* sector) {
1843 int retval = 0, sectorOK = 0;
1844 uint64_t earlier, later, testSector, original;
1845
1846 if ((*sector % sectorAlignment) != 0) {
1847 original = *sector;
1848 retval = 1;
1849 earlier = (*sector / sectorAlignment) * sectorAlignment;
1850 later = earlier + (uint64_t) sectorAlignment;
1851
1852 // Check to see that every sector between the earlier one and the
1853 // requested one is clear, and that it's not too early....
1854 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001855 sectorOK = 1;
1856 testSector = earlier;
1857 do {
1858 sectorOK = IsFree(testSector++);
1859 } while ((sectorOK == 1) && (testSector < *sector));
1860 if (sectorOK == 1) {
1861 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001862 } // if
1863 } // if firstUsableLBA check
1864
1865 // If couldn't move the sector earlier, try to move it later instead....
1866 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1867 sectorOK = 1;
1868 testSector = later;
1869 do {
1870 sectorOK = IsFree(testSector--);
1871 } while ((sectorOK == 1) && (testSector > *sector));
1872 if (sectorOK == 1) {
1873 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001874 } // if
1875 } // if
1876
1877 // If sector was changed successfully, inform the user of this fact.
1878 // Otherwise, notify the user that it couldn't be done....
1879 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001880 cout << "Information: Moved requested sector from " << original << " to "
1881 << *sector << " for\nalignment purposes.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001882 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001883 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001884 } else {
srs5694fed16d02010-01-27 23:03:40 -05001885 cout << "Information: Sector not aligned on " << sectorAlignment
1886 << "-sector boundary and could not be moved.\n"
1887 << "If you're using a Western Digital Advanced Format or similar disk with\n"
1888 << "underlying 4096-byte sectors, performance may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001889 retval = 0;
1890 } // if/else
1891 } // if
1892 return retval;
1893} // GPTData::Align()
1894
srs5694e4ac11e2009-08-31 10:13:04 -04001895/********************************************************
1896 * *
1897 * Functions that return data about GPT data structures *
1898 * (most of these are inline in gpt.h) *
1899 * *
1900 ********************************************************/
1901
1902// Find the low and high used partition numbers (numbered from 0).
1903// Return value is the number of partitions found. Note that the
1904// *low and *high values are both set to 0 when no partitions
1905// are found, as well as when a single partition in the first
1906// position exists. Thus, the return value is the only way to
1907// tell when no partitions exist.
1908int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1909 uint32_t i;
1910 int numFound = 0;
1911
1912 *low = mainHeader.numParts + 1; // code for "not found"
1913 *high = 0;
1914 if (mainHeader.numParts > 0) { // only try if partition table exists...
1915 for (i = 0; i < mainHeader.numParts; i++) {
1916 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1917 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001918 // Set the low value only if it's not yet found...
srs5694e4ac11e2009-08-31 10:13:04 -04001919 if (*low == (mainHeader.numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001920 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001921 } // if
1922 } // for
1923 } // if
1924
1925 // Above will leave *low pointing to its "not found" value if no partitions
1926 // are defined, so reset to 0 if this is the case....
1927 if (*low == (mainHeader.numParts + 1))
1928 *low = 0;
1929 return numFound;
1930} // GPTData::GetPartRange()
1931
srs569408bb0da2010-02-19 17:19:55 -05001932// Returns the value of the first free partition, or -1 if none is
1933// unused.
1934int GPTData::FindFirstFreePart(void) {
1935 int i = 0;
1936
1937 if (partitions != NULL) {
1938 while ((partitions[i].IsUsed()) && (i < (int) mainHeader.numParts))
1939 i++;
1940 if (i >= (int) mainHeader.numParts)
1941 i = -1;
1942 } else i = -1;
1943 return i;
1944} // GPTData::FindFirstFreePart()
1945
srs5694978041c2009-09-21 20:51:47 -04001946// Returns the number of defined partitions.
1947uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001948 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001949
1950 for (i = 0; i < mainHeader.numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001951 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001952 counted++;
1953 } // for
1954 return counted;
1955} // GPTData::CountParts()
1956
srs5694e4ac11e2009-08-31 10:13:04 -04001957/****************************************************
1958 * *
1959 * Functions that return data about disk free space *
1960 * *
1961 ****************************************************/
1962
1963// Find the first available block after the starting point; returns 0 if
1964// there are no available blocks left
1965uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1966 uint64_t first;
1967 uint32_t i;
1968 int firstMoved = 0;
1969
1970 // Begin from the specified starting point or from the first usable
1971 // LBA, whichever is greater...
1972 if (start < mainHeader.firstUsableLBA)
1973 first = mainHeader.firstUsableLBA;
1974 else
1975 first = start;
1976
1977 // ...now search through all partitions; if first is within an
1978 // existing partition, move it to the next sector after that
1979 // partition and repeat. If first was moved, set firstMoved
1980 // flag; repeat until firstMoved is not set, so as to catch
1981 // cases where partitions are out of sequential order....
1982 do {
1983 firstMoved = 0;
1984 for (i = 0; i < mainHeader.numParts; i++) {
1985 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001986 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001987 first = partitions[i].GetLastLBA() + 1;
1988 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001989 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001990 } // for
1991 } while (firstMoved == 1);
1992 if (first > mainHeader.lastUsableLBA)
1993 first = 0;
1994 return (first);
1995} // GPTData::FindFirstAvailable()
1996
1997// Finds the first available sector in the largest block of unallocated
1998// space on the disk. Returns 0 if there are no available blocks left
1999uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04002000 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002001
2002 start = 0;
2003 do {
2004 firstBlock = FindFirstAvailable(start);
2005 if (firstBlock != UINT32_C(0)) { // something's free...
2006 lastBlock = FindLastInFree(firstBlock);
2007 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2008 if (segmentSize > selectedSize) {
2009 selectedSize = segmentSize;
2010 selectedSegment = firstBlock;
2011 } // if
2012 start = lastBlock + 1;
2013 } // if
2014 } while (firstBlock != 0);
2015 return selectedSegment;
2016} // GPTData::FindFirstInLargest()
2017
srs5694cb76c672010-02-11 22:22:22 -05002018// Find the last available block on the disk.
2019// Returns 0 if there are no available partitions
2020uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002021 uint64_t last;
2022 uint32_t i;
2023 int lastMoved = 0;
2024
2025 // Start by assuming the last usable LBA is available....
2026 last = mainHeader.lastUsableLBA;
2027
2028 // ...now, similar to algorithm in FindFirstAvailable(), search
2029 // through all partitions, moving last when it's in an existing
2030 // partition. Set the lastMoved flag so we repeat to catch cases
2031 // where partitions are out of logical order.
2032 do {
2033 lastMoved = 0;
2034 for (i = 0; i < mainHeader.numParts; i++) {
2035 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002036 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002037 last = partitions[i].GetFirstLBA() - 1;
2038 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002039 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002040 } // for
2041 } while (lastMoved == 1);
2042 if (last < mainHeader.firstUsableLBA)
2043 last = 0;
2044 return (last);
2045} // GPTData::FindLastAvailable()
2046
2047// Find the last available block in the free space pointed to by start.
2048uint64_t GPTData::FindLastInFree(uint64_t start) {
2049 uint64_t nearestStart;
2050 uint32_t i;
2051
2052 nearestStart = mainHeader.lastUsableLBA;
2053 for (i = 0; i < mainHeader.numParts; i++) {
2054 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002055 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002056 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002057 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002058 } // for
2059 return (nearestStart);
2060} // GPTData::FindLastInFree()
2061
2062// Finds the total number of free blocks, the number of segments in which
2063// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002064uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002065 uint64_t start = UINT64_C(0); // starting point for each search
2066 uint64_t totalFound = UINT64_C(0); // running total
2067 uint64_t firstBlock; // first block in a segment
2068 uint64_t lastBlock; // last block in a segment
2069 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002070 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002071
2072 *largestSegment = UINT64_C(0);
2073 do {
2074 firstBlock = FindFirstAvailable(start);
2075 if (firstBlock != UINT64_C(0)) { // something's free...
2076 lastBlock = FindLastInFree(firstBlock);
2077 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2078 if (segmentSize > *largestSegment) {
2079 *largestSegment = segmentSize;
2080 } // if
2081 totalFound += segmentSize;
2082 num++;
2083 start = lastBlock + 1;
2084 } // if
2085 } while (firstBlock != 0);
2086 *numSegments = num;
2087 return totalFound;
2088} // GPTData::FindFreeBlocks()
2089
srs569455d92612010-03-07 22:16:07 -05002090// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2091// If it's allocated, return the partition number to which it's allocated
2092// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2093// returned in partNum if the sector is in use by basic GPT data structures.)
2094int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002095 int isFree = 1;
2096 uint32_t i;
2097
2098 for (i = 0; i < mainHeader.numParts; i++) {
2099 if ((sector >= partitions[i].GetFirstLBA()) &&
2100 (sector <= partitions[i].GetLastLBA())) {
2101 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002102 if (partNum != NULL)
2103 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002104 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002105 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002106 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002107 (sector > mainHeader.lastUsableLBA)) {
2108 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002109 if (partNum != NULL)
2110 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002111 } // if
2112 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002113} // GPTData::IsFree()
2114
srs5694ba00fed2010-01-12 18:18:36 -05002115// Returns 1 if partNum is unused.
2116int GPTData::IsFreePartNum(uint32_t partNum) {
2117 int retval = 1;
2118
srs569408bb0da2010-02-19 17:19:55 -05002119 if ((partNum < mainHeader.numParts) && (partitions != NULL)) {
2120 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002121 retval = 0;
2122 } // if partition is in use
2123 } else retval = 0;
2124
2125 return retval;
2126} // GPTData::IsFreePartNum()
2127
srs5694a8582cf2010-03-19 14:21:59 -04002128
2129/***********************************************************
2130 * *
2131 * Change how functions work or return information on them *
2132 * *
2133 ***********************************************************/
2134
2135// Set partition alignment value; partitions will begin on multiples of
2136// the specified value
2137void GPTData::SetAlignment(uint32_t n) {
2138 uint32_t l2;
2139
2140 sectorAlignment = n;
2141 l2 = (uint32_t) log2(n);
2142 if (PowerOf2(l2) != n)
2143 cout << "Information: Your alignment value is not a power of 2.\n";
2144} // GPTData::SetAlignment()
2145
2146// Compute sector alignment based on the current partitions (if any). Each
2147// partition's starting LBA is examined, and if it's divisible by a power-of-2
2148// value less than the maximum found so far (or 2^31 for the first partition
2149// found), then the alignment value is adjusted down. If the computed
2150// alignment is less than 8 and the disk is bigger than SMALLEST_ADVANCED_FORMAT,
2151// resets it to 8. This is a safety measure for WD Advanced Format and
2152// similar drives. If no partitions are defined, the alignment value is set
2153// to DEFAULT_ALIGNMENT (2048). The result is that new drives are aligned to
2154// 2048-sector multiples but the program won't complain about other alignments
2155// on existing disks unless a smaller-than-8 alignment is used on small disks
2156// (as safety for WD Advanced Format drives).
2157// Returns the computed alignment value.
2158uint32_t GPTData::ComputeAlignment(void) {
2159 uint32_t i = 0, found, exponent = 31;
2160 uint64_t align = DEFAULT_ALIGNMENT;
2161
2162 for (i = 0; i < mainHeader.numParts; i++) {
2163 if (partitions[i].IsUsed()) {
2164 found = 0;
2165 while (!found) {
2166 align = PowerOf2(exponent);
2167 if ((partitions[i].GetFirstLBA() % align) == 0) {
2168 found = 1;
2169 } else {
2170 exponent--;
2171 } // if/else
2172 } // while
2173 } // if
2174 } // for
2175 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2176 align = 8;
2177// cout << "Setting alignment to " << align << "\n";
2178 SetAlignment(align);
2179 return align;
2180} // GPTData::ComputeAlignment()
2181
srs5694e4ac11e2009-08-31 10:13:04 -04002182/********************************
2183 * *
2184 * Endianness support functions *
2185 * *
2186 ********************************/
2187
srs56942a9f5da2009-08-26 00:48:01 -04002188void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002189 ReverseBytes(&header->signature, 8);
2190 ReverseBytes(&header->revision, 4);
2191 ReverseBytes(&header->headerSize, 4);
2192 ReverseBytes(&header->headerCRC, 4);
2193 ReverseBytes(&header->reserved, 4);
2194 ReverseBytes(&header->currentLBA, 8);
2195 ReverseBytes(&header->backupLBA, 8);
2196 ReverseBytes(&header->firstUsableLBA, 8);
2197 ReverseBytes(&header->lastUsableLBA, 8);
2198 ReverseBytes(&header->partitionEntriesLBA, 8);
2199 ReverseBytes(&header->numParts, 4);
2200 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2201 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002202 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002203} // GPTData::ReverseHeaderBytes()
2204
2205// IMPORTANT NOTE: This function requires non-reversed mainHeader
2206// structure!
2207void GPTData::ReversePartitionBytes() {
2208 uint32_t i;
2209
2210 // Check GPT signature on big-endian systems; this will mismatch
2211 // if the function is called out of order. Unfortunately, it'll also
2212 // mismatch if there's data corruption.
2213 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002214 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2215 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002216 } // if signature mismatch....
2217 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002218 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002219 } // for
2220} // GPTData::ReversePartitionBytes()
2221
2222/******************************************
2223 * *
2224 * Additional non-class support functions *
2225 * *
2226 ******************************************/
2227
srs5694e7b4ff92009-08-18 13:16:10 -04002228// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2229// never fail these tests, but the struct types may fail depending on compile options.
2230// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2231// sizes.
2232int SizesOK(void) {
2233 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002234
2235 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002236 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002237 allOK = 0;
2238 } // if
2239 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002240 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002241 allOK = 0;
2242 } // if
2243 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002244 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002245 allOK = 0;
2246 } // if
2247 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002248 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002249 allOK = 0;
2250 } // if
2251 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002252 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002253 allOK = 0;
2254 } // if
srs5694978041c2009-09-21 20:51:47 -04002255 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002256 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002257 allOK = 0;
2258 } // if
2259 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002260 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002261 allOK = 0;
2262 } // if
srs5694221e0872009-08-29 15:00:31 -04002263 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002264 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002265 allOK = 0;
2266 } // if
srs56946699b012010-02-04 00:55:30 -05002267 if (sizeof(GUIDData) != 16) {
2268 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2269 allOK = 0;
2270 } // if
2271 if (sizeof(PartType) != 16) {
2272 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2273 allOK = 0;
2274 } // if
srs5694fed16d02010-01-27 23:03:40 -05002275 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002276 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002277 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2278 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002279 } // if
2280 return (allOK);
2281} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002282