blob: 9b1faf6e3dbbcd096c7a8ce8c601c3e503a36acd [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();
srs5694fed16d02010-01-27 23:03:40 -0500611 device = deviceFilename;
srs5694546a9c72010-01-26 16:00:26 -0500612 PartitionScan(); // Check for partition types, load GPT, & print summary
srs5694e4ac11e2009-08-31 10:13:04 -0400613
srs5694ba00fed2010-01-12 18:18:36 -0500614 whichWasUsed = UseWhichPartitions();
615 switch (whichWasUsed) {
srs5694e4ac11e2009-08-31 10:13:04 -0400616 case use_mbr:
617 XFormPartitions();
618 break;
619 case use_bsd:
srs5694546a9c72010-01-26 16:00:26 -0500620 bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
srs5694e4ac11e2009-08-31 10:13:04 -0400621// bsdDisklabel.DisplayBSDData();
622 ClearGPTData();
623 protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
srs569408bb0da2010-02-19 17:19:55 -0500624 XFormDisklabel(&bsdDisklabel);
srs5694e4ac11e2009-08-31 10:13:04 -0400625 break;
626 case use_gpt:
srs5694fed16d02010-01-27 23:03:40 -0500627 mbrState = protectiveMBR.GetValidity();
628 if ((mbrState == invalid) || (mbrState == mbr))
629 protectiveMBR.MakeProtectiveMBR();
srs5694e4ac11e2009-08-31 10:13:04 -0400630 break;
631 case use_new:
632 ClearGPTData();
633 protectiveMBR.MakeProtectiveMBR();
634 break;
srs56943c0af382010-01-15 19:19:18 -0500635 case use_abort:
636 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500637 cerr << "Aborting because of invalid partition data!\n";
srs56943c0af382010-01-15 19:19:18 -0500638 break;
srs5694e4ac11e2009-08-31 10:13:04 -0400639 } // switch
640
srs569455d92612010-03-07 22:16:07 -0500641 if (allOK)
srs56943c0af382010-01-15 19:19:18 -0500642 CheckGPTSize();
srs569455d92612010-03-07 22:16:07 -0500643 myDisk.Close();
srs5694a8582cf2010-03-19 14:21:59 -0400644 ComputeAlignment();
srs5694e4ac11e2009-08-31 10:13:04 -0400645 } else {
646 allOK = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400647 } // if/else
648 return (allOK);
649} // GPTData::LoadPartitions()
650
651// Loads the GPT, as much as possible. Returns 1 if this seems to have
652// succeeded, 0 if there are obvious problems....
srs5694546a9c72010-01-26 16:00:26 -0500653int GPTData::ForceLoadGPTData(void) {
srs5694cb76c672010-02-11 22:22:22 -0500654 int allOK, validHeaders, loadedTable = 1;
srs5694e4ac11e2009-08-31 10:13:04 -0400655
srs5694cb76c672010-02-11 22:22:22 -0500656 allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
srs5694e4ac11e2009-08-31 10:13:04 -0400657
srs5694cb76c672010-02-11 22:22:22 -0500658 if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
659 allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
660 } else {
srs569408bb0da2010-02-19 17:19:55 -0500661 allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
662 if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
srs5694fed16d02010-01-27 23:03:40 -0500663 cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
664 << "secondary header from the last sector of the disk! You should use 'v' to\n"
665 << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
666 << "the disk.\n";
srs5694cb76c672010-02-11 22:22:22 -0500667 } // if/else
668 if (!allOK)
srs5694e4ac11e2009-08-31 10:13:04 -0400669 state = gpt_invalid;
srs5694e4ac11e2009-08-31 10:13:04 -0400670
671 // Return valid headers code: 0 = both headers bad; 1 = main header
672 // good, backup bad; 2 = backup header good, main header bad;
673 // 3 = both headers good. Note these codes refer to valid GPT
674 // signatures and version numbers; more subtle problems will elude
675 // this check!
676 validHeaders = CheckHeaderValidity();
677
678 // Read partitions (from primary array)
679 if (validHeaders > 0) { // if at least one header is OK....
680 // GPT appears to be valid....
681 state = gpt_valid;
682
683 // We're calling the GPT valid, but there's a possibility that one
684 // of the two headers is corrupt. If so, use the one that seems to
685 // be in better shape to regenerate the bad one
srs5694546a9c72010-01-26 16:00:26 -0500686 if (validHeaders == 1) { // valid main header, invalid backup header
srs5694fed16d02010-01-27 23:03:40 -0500687 cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
688 << "backup header from main header.\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400689 RebuildSecondHeader();
srs5694546a9c72010-01-26 16:00:26 -0500690 state = gpt_corrupt;
srs5694e4ac11e2009-08-31 10:13:04 -0400691 secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
srs5694546a9c72010-01-26 16:00:26 -0500692 } else if (validHeaders == 2) { // valid backup header, invalid main header
srs5694fed16d02010-01-27 23:03:40 -0500693 cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
694 << "from backup!\n\n";
srs5694546a9c72010-01-26 16:00:26 -0500695 RebuildMainHeader();
696 state = gpt_corrupt;
697 mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
srs5694e4ac11e2009-08-31 10:13:04 -0400698 } // if/else/if
699
srs5694546a9c72010-01-26 16:00:26 -0500700 // Figure out which partition table to load....
701 // Load the main partition table, since either its header's CRC is OK or the
702 // backup header's CRC is not OK....
703 if (mainCrcOk || !secondCrcOk) {
704 if (LoadMainTable() == 0)
705 allOK = 0;
706 } else { // bad main header CRC and backup header CRC is OK
707 state = gpt_corrupt;
708 if (LoadSecondTableAsMain()) {
srs5694cb76c672010-02-11 22:22:22 -0500709 loadedTable = 2;
srs5694fed16d02010-01-27 23:03:40 -0500710 cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
srs5694546a9c72010-01-26 16:00:26 -0500711 } else { // backup table bad, bad main header CRC, but try main table in desperation....
712 if (LoadMainTable() == 0) {
713 allOK = 0;
srs5694cb76c672010-02-11 22:22:22 -0500714 loadedTable = 0;
srs5694fed16d02010-01-27 23:03:40 -0500715 cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500716 } // if
717 } // if/else (LoadSecondTableAsMain())
718 } // if/else (load partition table)
srs5694e4ac11e2009-08-31 10:13:04 -0400719
srs5694cb76c672010-02-11 22:22:22 -0500720 if (loadedTable == 1)
721 secondPartsCrcOk = CheckTable(&secondHeader);
722 else if (loadedTable == 2)
723 mainPartsCrcOk = CheckTable(&mainHeader);
724 else
725 mainPartsCrcOk = secondPartsCrcOk = 0;
srs5694e4ac11e2009-08-31 10:13:04 -0400726
srs5694546a9c72010-01-26 16:00:26 -0500727 // Problem with main partition table; if backup is OK, use it instead....
728 if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
729 state = gpt_corrupt;
730 allOK = allOK && LoadSecondTableAsMain();
srs5694cb76c672010-02-11 22:22:22 -0500731 mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
srs5694fed16d02010-01-27 23:03:40 -0500732 cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
733 << "partition table\ninstead of main partition table!\n\n";
srs5694cb76c672010-02-11 22:22:22 -0500734 } // if */
srs5694546a9c72010-01-26 16:00:26 -0500735
srs5694e4ac11e2009-08-31 10:13:04 -0400736 // Check for valid CRCs and warn if there are problems
737 if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
738 (secondPartsCrcOk == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500739 cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400740 state = gpt_corrupt;
srs5694ba00fed2010-01-12 18:18:36 -0500741 } // if
srs5694e4ac11e2009-08-31 10:13:04 -0400742 } else {
743 state = gpt_invalid;
744 } // if/else
745 return allOK;
746} // GPTData::ForceLoadGPTData()
747
srs5694247657a2009-11-26 18:36:12 -0500748// Loads the partition table pointed to by the main GPT header. The
srs5694e4ac11e2009-08-31 10:13:04 -0400749// main GPT header in memory MUST be valid for this call to do anything
750// sensible!
srs5694546a9c72010-01-26 16:00:26 -0500751// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
srs5694e4ac11e2009-08-31 10:13:04 -0400752int GPTData::LoadMainTable(void) {
srs5694cb76c672010-02-11 22:22:22 -0500753 return LoadPartitionTable(mainHeader, myDisk);
srs5694e4ac11e2009-08-31 10:13:04 -0400754} // GPTData::LoadMainTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400755
756// Load the second (backup) partition table as the primary partition
srs5694546a9c72010-01-26 16:00:26 -0500757// table. Used in repair functions, and when starting up if the main
758// partition table is damaged.
759// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
760int GPTData::LoadSecondTableAsMain(void) {
srs5694cb76c672010-02-11 22:22:22 -0500761 return LoadPartitionTable(secondHeader, myDisk);
762} // GPTData::LoadSecondTableAsMain()
srs5694e7b4ff92009-08-18 13:16:10 -0400763
srs5694cb76c672010-02-11 22:22:22 -0500764// Load a single GPT header (main or backup) from the specified disk device and
765// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
766// value appropriately.
767// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
768// failure.
769int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
770 int allOK = 1;
srs56941c6f8b02010-02-21 11:09:20 -0500771 GPTHeader tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500772
773 disk.Seek(sector);
srs56941c6f8b02010-02-21 11:09:20 -0500774 if (disk.Read(&tempHeader, 512) != 512) {
srs5694cb76c672010-02-11 22:22:22 -0500775 cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
776 allOK = 0;
777 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500778 *crcOk = CheckHeaderCRC(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500779
srs56941c6f8b02010-02-21 11:09:20 -0500780 // Reverse byte order, if necessary
srs5694cb76c672010-02-11 22:22:22 -0500781 if (IsLittleEndian() == 0) {
srs569455d92612010-03-07 22:16:07 -0500782 ReverseHeaderBytes(&tempHeader);
srs5694cb76c672010-02-11 22:22:22 -0500783 } // if
srs56941c6f8b02010-02-21 11:09:20 -0500784
srs569455d92612010-03-07 22:16:07 -0500785 if (allOK && (mainHeader.numParts != tempHeader.numParts) && *crcOk) {
srs56941c6f8b02010-02-21 11:09:20 -0500786 allOK = SetGPTSize(tempHeader.numParts);
srs569455d92612010-03-07 22:16:07 -0500787 }
srs56941c6f8b02010-02-21 11:09:20 -0500788
789 *header = tempHeader;
srs5694cb76c672010-02-11 22:22:22 -0500790 return allOK;
791} // GPTData::LoadHeader
792
793// Load a partition table (either main or secondary) from the specified disk,
794// using header as a reference for what to load. If sector != 0 (the default
795// is 0), loads from the specified sector; otherwise loads from the sector
796// indicated in header.
797// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
798int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
799 uint32_t sizeOfParts, newCRC;
800 int retval;
801
802 if (disk.OpenForRead()) {
803 if (sector == 0) {
804 retval = disk.Seek(header.partitionEntriesLBA);
805 } else {
806 retval = disk.Seek(sector);
807 } // if/else
srs569455d92612010-03-07 22:16:07 -0500808 if (retval == 1)
809 retval = SetGPTSize(header.numParts);
srs5694546a9c72010-01-26 16:00:26 -0500810 if (retval == 1) {
srs5694cb76c672010-02-11 22:22:22 -0500811 sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
812 if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
srs5694fed16d02010-01-27 23:03:40 -0500813 cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
srs5694546a9c72010-01-26 16:00:26 -0500814 retval = 0;
srs56945d58fe02010-01-03 20:57:08 -0500815 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400816 newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
srs5694cb76c672010-02-11 22:22:22 -0500817 mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
srs56942a9f5da2009-08-26 00:48:01 -0400818 if (IsLittleEndian() == 0)
819 ReversePartitionBytes();
srs5694cb76c672010-02-11 22:22:22 -0500820 if (!mainPartsCrcOk) {
821 cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400822 } // if
823 } else {
srs5694cb76c672010-02-11 22:22:22 -0500824 cerr << "Error! Couldn't seek to partition table!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400825 } // if/else
826 } else {
srs5694fed16d02010-01-27 23:03:40 -0500827 cerr << "Error! Couldn't open device " << device
srs5694cb76c672010-02-11 22:22:22 -0500828 << " when reading partition table!\n";
srs5694546a9c72010-01-26 16:00:26 -0500829 retval = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400830 } // if/else
srs5694546a9c72010-01-26 16:00:26 -0500831 return retval;
srs5694cb76c672010-02-11 22:22:22 -0500832} // GPTData::LoadPartitionsTable()
833
834// Check the partition table pointed to by header, but don't keep it
835// around.
836// Returns 1 if the CRC is OK, 0 if not or if there was a read error.
837int GPTData::CheckTable(struct GPTHeader *header) {
838 uint32_t sizeOfParts, newCRC;
839 uint8_t *storage;
840 int newCrcOk = 0;
841
842 // Load backup partition table into temporary storage to check
843 // its CRC and store the results, then discard this temporary
844 // storage, since we don't use it in any but recovery operations
845 if (myDisk.Seek(header->partitionEntriesLBA)) {
846 sizeOfParts = secondHeader.numParts * secondHeader.sizeOfPartitionEntries;
847 storage = new uint8_t[sizeOfParts];
848 if (myDisk.Read(storage, sizeOfParts) != (int) sizeOfParts) {
849 cerr << "Warning! Error " << errno << " reading backup partition table!\n";
850 } else {
851 newCRC = chksum_crc32((unsigned char*) storage, sizeOfParts);
852 newCrcOk = (newCRC == header->partitionEntriesCRC);
853 } // if/else
854 delete[] storage;
855 } // if
856 return newCrcOk;
857} // GPTData::CheckTable()
srs5694e7b4ff92009-08-18 13:16:10 -0400858
srs5694e7b4ff92009-08-18 13:16:10 -0400859// Writes GPT (and protective MBR) to disk. Returns 1 on successful
860// write, 0 if there was a problem.
srs5694ba00fed2010-01-12 18:18:36 -0500861int GPTData::SaveGPTData(int quiet) {
srs56946699b012010-02-04 00:55:30 -0500862 int allOK = 1, littleEndian;
srs5694e321d442010-01-29 17:44:04 -0500863 char answer;
srs5694e7b4ff92009-08-18 13:16:10 -0400864
srs56946699b012010-02-04 00:55:30 -0500865 littleEndian = IsLittleEndian();
866
srs5694fed16d02010-01-27 23:03:40 -0500867 if (device == "") {
868 cerr << "Device not defined.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400869 } // if
870
871 // First do some final sanity checks....
srs56945d58fe02010-01-03 20:57:08 -0500872
873 // This test should only fail on read-only disks....
874 if (justLooking) {
srs5694fed16d02010-01-27 23:03:40 -0500875 cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
srs56945d58fe02010-01-03 20:57:08 -0500876 allOK = 0;
877 } // if
878
srs5694e7b4ff92009-08-18 13:16:10 -0400879 // Is there enough space to hold the GPT headers and partition tables,
880 // given the partition sizes?
srs5694221e0872009-08-29 15:00:31 -0400881 if (CheckGPTSize() > 0) {
srs5694e7b4ff92009-08-18 13:16:10 -0400882 allOK = 0;
883 } // if
884
885 // Check that disk is really big enough to handle this...
886 if (mainHeader.backupLBA > diskSize) {
srs5694fed16d02010-01-27 23:03:40 -0500887 cerr << "Error! Disk is too small! The 'e' option on the experts' menu might fix the\n"
888 << "problem (or it might not). Aborting!\n(Disk size is "
889 << diskSize << " sectors, needs to be " << mainHeader.backupLBA << " sectors.)\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400890 allOK = 0;
891 } // if
srs5694247657a2009-11-26 18:36:12 -0500892 // Check that second header is properly placed. Warn and ask if this should
893 // be corrected if the test fails....
srs5694ba00fed2010-01-12 18:18:36 -0500894 if ((mainHeader.backupLBA < (diskSize - UINT64_C(1))) && (quiet == 0)) {
srs5694fed16d02010-01-27 23:03:40 -0500895 cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
896 << "correct this problem? ";
srs5694247657a2009-11-26 18:36:12 -0500897 if (GetYN() == 'Y') {
898 MoveSecondHeaderToEnd();
srs5694fed16d02010-01-27 23:03:40 -0500899 cout << "Have moved second header and partition table to correct location.\n";
srs5694247657a2009-11-26 18:36:12 -0500900 } else {
srs5694fed16d02010-01-27 23:03:40 -0500901 cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
srs5694247657a2009-11-26 18:36:12 -0500902 } // if correction requested
903 } // if
srs5694e7b4ff92009-08-18 13:16:10 -0400904
srs569455d92612010-03-07 22:16:07 -0500905 // Check for overlapping or insane partitions....
906 if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
srs5694e4ac11e2009-08-31 10:13:04 -0400907 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -0500908 cerr << "Aborting write operation!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400909 } // if
910
911 // Check for mismatched MBR and GPT data, but let it pass if found
912 // (function displays warning message)
913 FindHybridMismatches();
srs5694e7b4ff92009-08-18 13:16:10 -0400914
915 RecomputeCRCs();
916
srs5694ba00fed2010-01-12 18:18:36 -0500917 if ((allOK) && (!quiet)) {
srs5694fed16d02010-01-27 23:03:40 -0500918 cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
919 << "PARTITIONS!!\n\nDo you want to proceed, possibly destroying your data? ";
srs56945d58fe02010-01-03 20:57:08 -0500920 answer = GetYN();
921 if (answer == 'Y') {
srs5694fed16d02010-01-27 23:03:40 -0500922 cout << "OK; writing new GUID partition table (GPT).\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400923 } else {
924 allOK = 0;
925 } // if/else
926 } // if
927
928 // Do it!
929 if (allOK) {
srs56948a4ddfc2010-03-21 19:05:49 -0400930 if (myDisk.OpenForWrite(device)) {
931 // As per UEFI specs, write the secondary table and GPT first....
srs5694cb76c672010-02-11 22:22:22 -0500932 allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
933 if (!allOK)
934 cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
935 << "menu will resolve this problem.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400936
937 // Now write the secondary GPT header...
srs56948a4ddfc2010-03-21 19:05:49 -0400938 allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
939
940 // Now write the main partition tables...
941 allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
942
943 // Now write the main GPT header...
944 allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
945
946 // To top it off, write the protective MBR...
947 allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
srs5694e7b4ff92009-08-18 13:16:10 -0400948
949 // re-read the partition table
950 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500951 myDisk.DiskSync();
srs5694e7b4ff92009-08-18 13:16:10 -0400952 } // if
953
954 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -0500955 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400956 } else {
srs5694fed16d02010-01-27 23:03:40 -0500957 cerr << "Warning! An error was reported when writing the partition table! This error\n"
srs56948a4ddfc2010-03-21 19:05:49 -0400958 << "MIGHT be harmless, but you may have trashed the disk!\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400959 } // if/else
srs56948a4ddfc2010-03-21 19:05:49 -0400960
srs5694546a9c72010-01-26 16:00:26 -0500961 myDisk.Close();
srs5694e7b4ff92009-08-18 13:16:10 -0400962 } else {
srs5694fed16d02010-01-27 23:03:40 -0500963 cerr << "Unable to open device " << device << " for writing! Errno is "
964 << errno << "! Aborting write!\n";
srs5694e4ac11e2009-08-31 10:13:04 -0400965 allOK = 0;
srs5694e7b4ff92009-08-18 13:16:10 -0400966 } // if/else
967 } else {
srs5694fed16d02010-01-27 23:03:40 -0500968 cout << "Aborting write of new partition table.\n";
srs5694e7b4ff92009-08-18 13:16:10 -0400969 } // if
970
971 return (allOK);
972} // GPTData::SaveGPTData()
973
974// Save GPT data to a backup file. This function does much less error
975// checking than SaveGPTData(). It can therefore preserve many types of
976// corruption for later analysis; however, it preserves only the MBR,
977// the main GPT header, the backup GPT header, and the main partition
978// table; it discards the backup partition table, since it should be
979// identical to the main partition table on healthy disks.
srs56940a697312010-01-28 21:10:52 -0500980int GPTData::SaveGPTBackup(const string & filename) {
981 int allOK = 1;
srs5694546a9c72010-01-26 16:00:26 -0500982 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -0400983
srs5694546a9c72010-01-26 16:00:26 -0500984 if (backupFile.OpenForWrite(filename)) {
srs56946699b012010-02-04 00:55:30 -0500985 // Recomputing the CRCs is likely to alter them, which could be bad
986 // if the intent is to save a potentially bad GPT for later analysis;
987 // but if we don't do this, we get bogus errors when we load the
988 // backup. I'm favoring misses over false alarms....
989 RecomputeCRCs();
990
srs5694546a9c72010-01-26 16:00:26 -0500991 protectiveMBR.WriteMBRData(&backupFile);
srs5694e7b4ff92009-08-18 13:16:10 -0400992
srs5694cb76c672010-02-11 22:22:22 -0500993 if (allOK) {
srs5694546a9c72010-01-26 16:00:26 -0500994 // MBR write closed disk, so re-open and seek to end....
995 backupFile.OpenForWrite();
srs5694cb76c672010-02-11 22:22:22 -0500996 allOK = SaveHeader(&mainHeader, backupFile, 1);
997 } // if (allOK)
srs5694e7b4ff92009-08-18 13:16:10 -0400998
srs5694e7b4ff92009-08-18 13:16:10 -0400999 if (allOK)
srs5694cb76c672010-02-11 22:22:22 -05001000 allOK = SaveHeader(&secondHeader, backupFile, 2);
srs5694e7b4ff92009-08-18 13:16:10 -04001001
srs5694cb76c672010-02-11 22:22:22 -05001002 if (allOK)
1003 allOK = SavePartitionTable(backupFile, 3);
srs5694e7b4ff92009-08-18 13:16:10 -04001004
1005 if (allOK) { // writes completed OK
srs5694fed16d02010-01-27 23:03:40 -05001006 cout << "The operation has completed successfully.\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001007 } else {
srs5694fed16d02010-01-27 23:03:40 -05001008 cerr << "Warning! An error was reported when writing the backup file.\n"
1009 << "It may not be usable!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001010 } // if/else
srs5694546a9c72010-01-26 16:00:26 -05001011 backupFile.Close();
srs5694e7b4ff92009-08-18 13:16:10 -04001012 } else {
srs5694fed16d02010-01-27 23:03:40 -05001013 cerr << "Unable to open file " << filename << " for writing! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001014 allOK = 0;
1015 } // if/else
1016 return allOK;
1017} // GPTData::SaveGPTBackup()
1018
srs5694cb76c672010-02-11 22:22:22 -05001019// Write a GPT header (main or backup) to the specified sector. Used by both
1020// the SaveGPTData() and SaveGPTBackup() functions.
1021// Should be passed an architecture-appropriate header (DO NOT call
1022// ReverseHeaderBytes() on the header before calling this function)
1023// Returns 1 on success, 0 on failure
1024int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1025 int littleEndian, allOK = 1;
1026
1027 littleEndian = IsLittleEndian();
1028 if (!littleEndian)
1029 ReverseHeaderBytes(header);
1030 if (disk.Seek(sector)) {
1031 if (disk.Write(header, 512) == -1)
1032 allOK = 0;
1033 } else allOK = 0; // if (disk.Seek()...)
1034 if (!littleEndian)
1035 ReverseHeaderBytes(header);
1036 return allOK;
1037} // GPTData::SaveHeader()
1038
1039// Save the partitions to the specified sector. Used by both the SaveGPTData()
1040// and SaveGPTBackup() functions.
1041// Should be passed an architecture-appropriate header (DO NOT call
1042// ReverseHeaderBytes() on the header before calling this function)
1043// Returns 1 on success, 0 on failure
1044int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1045 int littleEndian, allOK = 1;
1046
1047 littleEndian = IsLittleEndian();
1048 if (disk.Seek(sector)) {
1049 if (!littleEndian)
1050 ReversePartitionBytes();
1051 if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * mainHeader.numParts) == -1)
1052 allOK = 0;
1053 if (!littleEndian)
1054 ReversePartitionBytes();
1055 } else allOK = 0; // if (myDisk.Seek()...)
1056 return allOK;
1057} // GPTData::SavePartitionTable()
1058
srs5694e7b4ff92009-08-18 13:16:10 -04001059// Load GPT data from a backup file created by SaveGPTBackup(). This function
1060// does minimal error checking. It returns 1 if it completed successfully,
1061// 0 if there was a problem. In the latter case, it creates a new empty
1062// set of partitions.
srs56940a697312010-01-28 21:10:52 -05001063int GPTData::LoadGPTBackup(const string & filename) {
srs5694cb76c672010-02-11 22:22:22 -05001064 int allOK = 1, val, err;
1065 uint32_t numParts, sizeOfEntries;
1066 int littleEndian = 1, shortBackup = 0;
srs5694546a9c72010-01-26 16:00:26 -05001067 DiskIO backupFile;
srs5694e7b4ff92009-08-18 13:16:10 -04001068
srs5694546a9c72010-01-26 16:00:26 -05001069 if (backupFile.OpenForRead(filename)) {
srs56942a9f5da2009-08-26 00:48:01 -04001070 if (IsLittleEndian() == 0)
1071 littleEndian = 0;
1072
srs5694e7b4ff92009-08-18 13:16:10 -04001073 // Let the MBRData class load the saved MBR...
srs5694546a9c72010-01-26 16:00:26 -05001074 protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
srs5694e7b4ff92009-08-18 13:16:10 -04001075
srs5694cb76c672010-02-11 22:22:22 -05001076 LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
srs5694e7b4ff92009-08-18 13:16:10 -04001077
srs5694cb76c672010-02-11 22:22:22 -05001078 // Check backup file size and rebuild second header if file is right
1079 // size to be direct dd copy of MBR, main header, and main partition
1080 // table; if other size, treat it like a GPT fdisk-generated backup
1081 // file
1082 shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1083 (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1084 if (shortBackup) {
1085 RebuildSecondHeader();
1086 secondCrcOk = mainCrcOk;
1087 } else {
1088 LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1089 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -04001090
srs5694e7b4ff92009-08-18 13:16:10 -04001091 // Return valid headers code: 0 = both headers bad; 1 = main header
1092 // good, backup bad; 2 = backup header good, main header bad;
1093 // 3 = both headers good. Note these codes refer to valid GPT
1094 // signatures and version numbers; more subtle problems will elude
1095 // this check!
1096 if ((val = CheckHeaderValidity()) > 0) {
1097 if (val == 2) { // only backup header seems to be good
1098 numParts = secondHeader.numParts;
srs5694e4ac11e2009-08-31 10:13:04 -04001099 sizeOfEntries = secondHeader.sizeOfPartitionEntries;
srs5694e7b4ff92009-08-18 13:16:10 -04001100 } else { // main header is OK
1101 numParts = mainHeader.numParts;
1102 sizeOfEntries = mainHeader.sizeOfPartitionEntries;
1103 } // if/else
1104
1105 SetGPTSize(numParts);
1106
srs5694e7b4ff92009-08-18 13:16:10 -04001107 if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
srs5694fed16d02010-01-27 23:03:40 -05001108 cout << "Warning! Current disk size doesn't match that of the backup!\n"
1109 << "Adjusting sizes to match, but subsequent problems are possible!\n";
srs5694247657a2009-11-26 18:36:12 -05001110 MoveSecondHeaderToEnd();
srs5694e7b4ff92009-08-18 13:16:10 -04001111 } // if
1112
srs5694cb76c672010-02-11 22:22:22 -05001113 if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1114 cerr << "Warning! Read error " << errno
1115 << " loading partition table; strange behavior now likely!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001116 } else {
1117 allOK = 0;
1118 } // if/else
srs5694a8582cf2010-03-19 14:21:59 -04001119 // Something went badly wrong, so blank out partitions
1120 if (allOK == 0) {
1121 cerr << "Improper backup file! Clearing all partition data!\n";
1122 ClearGPTData();
1123 protectiveMBR.MakeProtectiveMBR();
1124 } // if
srs5694e7b4ff92009-08-18 13:16:10 -04001125 } else {
1126 allOK = 0;
srs5694fed16d02010-01-27 23:03:40 -05001127 cerr << "Unable to open file " << filename << " for reading! Aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04001128 } // if/else
1129
srs5694e7b4ff92009-08-18 13:16:10 -04001130 return allOK;
1131} // GPTData::LoadGPTBackup()
1132
srs569408bb0da2010-02-19 17:19:55 -05001133int GPTData::SaveMBR(void) {
srs569455d92612010-03-07 22:16:07 -05001134 return protectiveMBR.WriteMBRData(&myDisk);
srs569408bb0da2010-02-19 17:19:55 -05001135} // GPTData::SaveMBR()
1136
1137// This function destroys the on-disk GPT structures, but NOT the on-disk
1138// MBR.
1139// Returns 1 if the operation succeeds, 0 if not.
1140int GPTData::DestroyGPT(void) {
1141 int i, sum, tableSize, allOK = 1;
1142 uint8_t blankSector[512];
1143 uint8_t* emptyTable;
1144
1145 for (i = 0; i < 512; i++) {
1146 blankSector[i] = 0;
1147 } // for
1148
1149 if (myDisk.OpenForWrite()) {
1150 if (!myDisk.Seek(mainHeader.currentLBA))
1151 allOK = 0;
1152 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1153 cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1154 allOK = 0;
1155 } // if
1156 if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1157 allOK = 0;
1158 tableSize = mainHeader.numParts * mainHeader.sizeOfPartitionEntries;
1159 emptyTable = new uint8_t[tableSize];
1160 for (i = 0; i < tableSize; i++)
1161 emptyTable[i] = 0;
1162 if (allOK) {
1163 sum = myDisk.Write(emptyTable, tableSize);
1164 if (sum != tableSize) {
1165 cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1166 allOK = 0;
1167 } // if write failed
1168 } // if
1169 if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1170 allOK = 0;
1171 if (allOK) {
1172 sum = myDisk.Write(emptyTable, tableSize);
1173 if (sum != tableSize) {
1174 cerr << "Warning! GPT backup partition table not overwritten! Error is "
1175 << errno << "\n";
1176 allOK = 0;
1177 } // if wrong size written
1178 } // if
1179 if (!myDisk.Seek(secondHeader.currentLBA))
1180 allOK = 0;
1181 if (allOK) {
1182 if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1183 cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1184 allOK = 0;
1185 } // if
1186 } // if
1187 myDisk.DiskSync();
1188 myDisk.Close();
1189 cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1190 << "other utilities.\n";
1191 delete[] emptyTable;
1192 } else {
1193 cerr << "Problem opening " << device << " for writing! Program will now terminate.\n";
1194 } // if/else (fd != -1)
1195 return (allOK);
1196} // GPTDataTextUI::DestroyGPT()
1197
1198// Wipe MBR data from the disk (zero it out completely)
1199// Returns 1 on success, 0 on failure.
1200int GPTData::DestroyMBR(void) {
1201 int allOK = 1, i;
1202 uint8_t blankSector[512];
1203
1204 for (i = 0; i < 512; i++)
1205 blankSector[i] = 0;
1206
1207 if (myDisk.OpenForWrite()) {
1208 if (myDisk.Seek(0)) {
1209 if (myDisk.Write(blankSector, 512) != 512)
1210 allOK = 0;
1211 } else allOK = 0;
1212 } else allOK = 0;
1213 if (!allOK)
1214 cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1215 return allOK;
1216} // GPTData::DestroyMBR(void)
1217
srs5694e4ac11e2009-08-31 10:13:04 -04001218// Tell user whether Apple Partition Map (APM) was discovered....
1219void GPTData::ShowAPMState(void) {
1220 if (apmFound)
srs5694fed16d02010-01-27 23:03:40 -05001221 cout << " APM: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001222 else
srs5694fed16d02010-01-27 23:03:40 -05001223 cout << " APM: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001224} // GPTData::ShowAPMState()
1225
1226// Tell user about the state of the GPT data....
1227void GPTData::ShowGPTState(void) {
1228 switch (state) {
1229 case gpt_invalid:
srs5694fed16d02010-01-27 23:03:40 -05001230 cout << " GPT: not present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001231 break;
1232 case gpt_valid:
srs5694fed16d02010-01-27 23:03:40 -05001233 cout << " GPT: present\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001234 break;
1235 case gpt_corrupt:
srs5694fed16d02010-01-27 23:03:40 -05001236 cout << " GPT: damaged\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001237 break;
1238 default:
srs5694fed16d02010-01-27 23:03:40 -05001239 cout << "\a GPT: unknown -- bug!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001240 break;
1241 } // switch
1242} // GPTData::ShowGPTState()
1243
1244// Display the basic GPT data
1245void GPTData::DisplayGPTData(void) {
srs5694e321d442010-01-29 17:44:04 -05001246 uint32_t i;
srs5694e4ac11e2009-08-31 10:13:04 -04001247 uint64_t temp, totalFree;
1248
srs5694fed16d02010-01-27 23:03:40 -05001249 cout << "Disk " << device << ": " << diskSize << " sectors, "
1250 << BytesToSI(diskSize * blockSize) << "\n";
1251 cout << "Logical sector size: " << blockSize << " bytes\n";
srs56946699b012010-02-04 00:55:30 -05001252 cout << "Disk identifier (GUID): " << mainHeader.diskGUID.AsString() << "\n";
srs5694fed16d02010-01-27 23:03:40 -05001253 cout << "Partition table holds up to " << mainHeader.numParts << " entries\n";
1254 cout << "First usable sector is " << mainHeader.firstUsableLBA
1255 << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001256 totalFree = FindFreeBlocks(&i, &temp);
srs56948a4ddfc2010-03-21 19:05:49 -04001257 cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
srs5694fed16d02010-01-27 23:03:40 -05001258 cout << "Total free space is " << totalFree << " sectors ("
1259 << BytesToSI(totalFree * (uint64_t) blockSize) << ")\n";
1260 cout << "\nNumber Start (sector) End (sector) Size Code Name\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001261 for (i = 0; i < mainHeader.numParts; i++) {
srs5694978041c2009-09-21 20:51:47 -04001262 partitions[i].ShowSummary(i, blockSize);
srs5694e4ac11e2009-08-31 10:13:04 -04001263 } // for
1264} // GPTData::DisplayGPTData()
1265
srs5694e4ac11e2009-08-31 10:13:04 -04001266// Show detailed information on the specified partition
1267void GPTData::ShowPartDetails(uint32_t partNum) {
1268 if (partitions[partNum].GetFirstLBA() != 0) {
1269 partitions[partNum].ShowDetails(blockSize);
1270 } else {
srs5694fed16d02010-01-27 23:03:40 -05001271 cout << "Partition #" << partNum + 1 << " does not exist.";
srs5694e4ac11e2009-08-31 10:13:04 -04001272 } // if
1273} // GPTData::ShowPartDetails()
1274
srs5694e4ac11e2009-08-31 10:13:04 -04001275/**************************************************************************
1276 * *
1277 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1278 * (some of these functions may require user interaction) *
1279 * *
1280 **************************************************************************/
1281
srs569408bb0da2010-02-19 17:19:55 -05001282// Examines the MBR & GPT data to determine which set of data to use: the
1283// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1284// a new set of partitions (use_new). A return value of use_abort indicates
1285// that this function couldn't determine what to do. Overriding functions
1286// in derived classes may ask users questions in such cases.
srs5694e4ac11e2009-08-31 10:13:04 -04001287WhichToUse GPTData::UseWhichPartitions(void) {
1288 WhichToUse which = use_new;
1289 MBRValidity mbrState;
srs5694e4ac11e2009-08-31 10:13:04 -04001290
1291 mbrState = protectiveMBR.GetValidity();
1292
1293 if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
srs5694fed16d02010-01-27 23:03:40 -05001294 cout << "\n***************************************************************\n"
1295 << "Found invalid GPT and valid MBR; converting MBR to GPT format.\n";
srs56945d58fe02010-01-03 20:57:08 -05001296 if (!justLooking) {
srs5694fed16d02010-01-27 23:03:40 -05001297 cout << "\aTHIS OPERATON IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if\n"
1298 << "you don't want to convert your MBR partitions to GPT format!\n";
srs56945d58fe02010-01-03 20:57:08 -05001299 } // if
srs5694fed16d02010-01-27 23:03:40 -05001300 cout << "***************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001301 which = use_mbr;
1302 } // if
1303
1304 if ((state == gpt_invalid) && bsdFound) {
srs5694fed16d02010-01-27 23:03:40 -05001305 cout << "\n**********************************************************************\n"
1306 << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1307 << "to GPT format.";
srs56940a697312010-01-28 21:10:52 -05001308 if ((!justLooking) && (!beQuiet)) {
srs5694fed16d02010-01-27 23:03:40 -05001309 cout << "\a THIS OPERATON IS POTENTIALLY DESTRUCTIVE! Your first\n"
1310 << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1311 << "want to convert your BSD partitions to GPT format!";
srs56945d58fe02010-01-03 20:57:08 -05001312 } // if
srs5694fed16d02010-01-27 23:03:40 -05001313 cout << "\n**********************************************************************\n\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001314 which = use_bsd;
1315 } // if
1316
1317 if ((state == gpt_valid) && (mbrState == gpt)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001318 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001319 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001320 cout << "Found valid GPT with protective MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001321 } // if
1322 if ((state == gpt_valid) && (mbrState == hybrid)) {
srs5694e4ac11e2009-08-31 10:13:04 -04001323 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001324 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001325 cout << "Found valid GPT with hybrid MBR; using GPT.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001326 } // if
1327 if ((state == gpt_valid) && (mbrState == invalid)) {
srs56940a697312010-01-28 21:10:52 -05001328 cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
srs5694fed16d02010-01-27 23:03:40 -05001329 << "protective MBR on save.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001330 which = use_gpt;
srs5694e4ac11e2009-08-31 10:13:04 -04001331 } // if
1332 if ((state == gpt_valid) && (mbrState == mbr)) {
srs569408bb0da2010-02-19 17:19:55 -05001333 which = use_abort;
srs5694e4ac11e2009-08-31 10:13:04 -04001334 } // if
1335
srs5694e4ac11e2009-08-31 10:13:04 -04001336 if (state == gpt_corrupt) {
srs569408bb0da2010-02-19 17:19:55 -05001337 if (mbrState == gpt) {
1338 cout << "\a\a****************************************************************************\n"
1339 << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1340 << "verification and recovery are STRONGLY recommended.\n"
1341 << "****************************************************************************\n";
1342 which = use_gpt;
srs56943c0af382010-01-15 19:19:18 -05001343 } else {
srs569408bb0da2010-02-19 17:19:55 -05001344 which = use_abort;
1345 } // if/else MBR says disk is GPT
1346 } // if GPT corrupt
srs5694e4ac11e2009-08-31 10:13:04 -04001347
1348 if (which == use_new)
srs5694fed16d02010-01-27 23:03:40 -05001349 cout << "Creating new GPT entries.\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001350
1351 return which;
1352} // UseWhichPartitions()
1353
srs569408bb0da2010-02-19 17:19:55 -05001354// Convert MBR partition table into GPT form.
1355void GPTData::XFormPartitions(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04001356 int i, numToConvert;
1357 uint8_t origType;
srs5694e4ac11e2009-08-31 10:13:04 -04001358
1359 // Clear out old data & prepare basics....
1360 ClearGPTData();
srs569408bb0da2010-02-19 17:19:55 -05001361 protectiveMBR.EmptyBootloader();
srs5694e4ac11e2009-08-31 10:13:04 -04001362
1363 // Convert the smaller of the # of GPT or MBR partitions
srs5694978041c2009-09-21 20:51:47 -04001364 if (mainHeader.numParts > (MAX_MBR_PARTS))
1365 numToConvert = MAX_MBR_PARTS;
srs5694e4ac11e2009-08-31 10:13:04 -04001366 else
1367 numToConvert = mainHeader.numParts;
1368
1369 for (i = 0; i < numToConvert; i++) {
1370 origType = protectiveMBR.GetType(i);
1371 // don't waste CPU time trying to convert extended, hybrid protective, or
1372 // null (non-existent) partitions
srs5694e35eb1b2009-09-14 00:29:34 -04001373 if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
srs56946699b012010-02-04 00:55:30 -05001374 (origType != 0x00) && (origType != 0xEE))
srs5694e4ac11e2009-08-31 10:13:04 -04001375 partitions[i] = protectiveMBR.AsGPT(i);
1376 } // for
1377
1378 // Convert MBR into protective MBR
1379 protectiveMBR.MakeProtectiveMBR();
1380
1381 // Record that all original CRCs were OK so as not to raise flags
1382 // when doing a disk verification
1383 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
srs5694e4ac11e2009-08-31 10:13:04 -04001384} // GPTData::XFormPartitions()
1385
1386// Transforms BSD disklabel on the specified partition (numbered from 0).
srs569408bb0da2010-02-19 17:19:55 -05001387// If an invalid partition number is given, the program does nothing.
srs5694e4ac11e2009-08-31 10:13:04 -04001388// Returns the number of new partitions created.
srs569408bb0da2010-02-19 17:19:55 -05001389int GPTData::XFormDisklabel(uint32_t partNum) {
1390 uint32_t low, high;
srs5694e4ac11e2009-08-31 10:13:04 -04001391 int goOn = 1, numDone = 0;
1392 BSDData disklabel;
1393
srs569408bb0da2010-02-19 17:19:55 -05001394 if (GetPartRange(&low, &high) == 0) {
1395 goOn = 0;
1396 cout << "No partitions!\n";
1397 } // if
1398 if (partNum > high) {
1399 goOn = 0;
1400 cout << "Specified partition is invalid!\n";
1401 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001402
srs569408bb0da2010-02-19 17:19:55 -05001403 // If all is OK, read the disklabel and convert it.
1404 if (goOn) {
1405 goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1406 partitions[partNum].GetLastLBA());
1407 if ((goOn) && (disklabel.IsDisklabel())) {
1408 numDone = XFormDisklabel(&disklabel);
1409 if (numDone == 1)
1410 cout << "Converted 1 BSD partition.\n";
1411 else
1412 cout << "Converted " << numDone << " BSD partitions.\n";
1413 } else {
1414 cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1415 } // if/else
1416 } // if
1417 if (numDone > 0) { // converted partitions; delete carrier
1418 partitions[partNum].BlankPartition();
1419 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001420 return numDone;
srs569455d92612010-03-07 22:16:07 -05001421} // GPTData::XFormDisklabel(uint32_t i)
srs5694e4ac11e2009-08-31 10:13:04 -04001422
1423// Transform the partitions on an already-loaded BSD disklabel...
srs569408bb0da2010-02-19 17:19:55 -05001424int GPTData::XFormDisklabel(BSDData* disklabel) {
1425 int i, partNum = 0, numDone = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04001426
srs569408bb0da2010-02-19 17:19:55 -05001427 if (disklabel->IsDisklabel()) {
srs5694e4ac11e2009-08-31 10:13:04 -04001428 for (i = 0; i < disklabel->GetNumParts(); i++) {
srs569408bb0da2010-02-19 17:19:55 -05001429 partNum = FindFirstFreePart();
1430 if (partNum >= 0) {
1431 partitions[partNum] = disklabel->AsGPT(i);
1432 if (partitions[partNum].IsUsed())
1433 numDone++;
1434 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001435 } // for
srs569408bb0da2010-02-19 17:19:55 -05001436 if (partNum == -1)
1437 cerr << "Warning! Too many partitions to convert!\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001438 } // if
1439
1440 // Record that all original CRCs were OK so as not to raise flags
1441 // when doing a disk verification
1442 mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1443
1444 return numDone;
1445} // GPTData::XFormDisklabel(BSDData* disklabel)
1446
srs569408bb0da2010-02-19 17:19:55 -05001447// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1448// partition has the active/bootable flag UNset and uses the GPT fdisk
1449// type code divided by 0x0100 as the MBR type code.
1450// Returns 1 if operation was 100% successful, 0 if there were ANY
1451// problems.
srs5694978041c2009-09-21 20:51:47 -04001452int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
srs569408bb0da2010-02-19 17:19:55 -05001453 int allOK = 1;
srs5694fed16d02010-01-27 23:03:40 -05001454
srs5694978041c2009-09-21 20:51:47 -04001455 if ((mbrPart < 0) || (mbrPart > 3)) {
srs5694fed16d02010-01-27 23:03:40 -05001456 cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001457 allOK = 0;
1458 } // if
1459 if (gptPart >= mainHeader.numParts) {
srs5694fed16d02010-01-27 23:03:40 -05001460 cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001461 allOK = 0;
1462 } // if
1463 if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
srs5694fed16d02010-01-27 23:03:40 -05001464 cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001465 allOK = 0;
1466 } // if
1467 if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1468 (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1469 if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
srs5694fed16d02010-01-27 23:03:40 -05001470 cout << "Caution: Partition end point past 32-bit pointer boundary;"
1471 << " some OSes may\nreact strangely.\n";
srs569408bb0da2010-02-19 17:19:55 -05001472 } // if
srs5694978041c2009-09-21 20:51:47 -04001473 protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
srs569408bb0da2010-02-19 17:19:55 -05001474 (uint32_t) partitions[gptPart].GetLengthLBA(),
1475 partitions[gptPart].GetHexType() / 256, 0);
srs5694978041c2009-09-21 20:51:47 -04001476 } else { // partition out of range
srs569408bb0da2010-02-19 17:19:55 -05001477 if (allOK) // Display only if "else" triggered by out-of-bounds condition
1478 cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1479 << "partitions, or is\n too big; omitting it.\n";
srs5694978041c2009-09-21 20:51:47 -04001480 allOK = 0;
1481 } // if/else
1482 return allOK;
1483} // GPTData::OnePartToMBR()
1484
srs569455d92612010-03-07 22:16:07 -05001485// Convert partitions to MBR form (primary and logical) and return
1486// the number done. Partitions are specified in a PartNotes variable,
1487// which includes pointers to GPT partition numbers. A partition number
1488// of MBR_EFI_GPT means to place an EFI GPT protective partition in that
1489// location in the table, and MBR_EMPTY means not to create a partition
1490// in that table position. If the partition type entry for a partition
1491// is 0, a default entry is used, based on the GPT partition type code.
srs569408bb0da2010-02-19 17:19:55 -05001492// Returns the number of partitions converted, NOT counting EFI GPT
srs569455d92612010-03-07 22:16:07 -05001493// protective partitions or extended partitions.
1494int GPTData::PartsToMBR(PartNotes & notes) {
1495 int mbrNum = 0, numConverted = 0;
1496 struct PartInfo convInfo;
srs5694978041c2009-09-21 20:51:47 -04001497
srs569455d92612010-03-07 22:16:07 -05001498 protectiveMBR.EmptyMBR();
1499 protectiveMBR.SetDiskSize(diskSize);
1500 notes.Rewind();
1501 while (notes.GetNextInfo(&convInfo) >= 0) {
1502 if ((convInfo.gptPartNum >= 0) && (convInfo.type == PRIMARY)) {
1503 numConverted += OnePartToMBR((uint32_t) convInfo.gptPartNum, mbrNum);
1504 if (convInfo.hexCode != 0)
1505 protectiveMBR.SetPartType(mbrNum, convInfo.hexCode);
1506 if (convInfo.active)
1507 protectiveMBR.SetPartBootable(mbrNum);
1508 mbrNum++;
1509 } // if
1510 if (convInfo.gptPartNum == MBR_EFI_GPT) {
1511 if (protectiveMBR.FindFirstAvailable() == UINT32_C(1)) {
1512 protectiveMBR.MakePart(mbrNum, 1, protectiveMBR.FindLastInFree(1), convInfo.hexCode);
1513 protectiveMBR.SetHybrid();
1514 } else {
1515 protectiveMBR.MakeBiggestPart(mbrNum, convInfo.hexCode);
1516 } // if/else
1517 mbrNum++;
1518 } // if EFI GPT partition specified
1519 } // for
1520 // Now do logical partition(s)...
1521 protectiveMBR.SetDisk(&myDisk);
1522 numConverted += protectiveMBR.CreateLogicals(notes);
1523// numConverted += PartsToLogical(notes);
srs569408bb0da2010-02-19 17:19:55 -05001524 return numConverted;
1525} // GPTData::PartsToMBR()
1526
srs5694e4ac11e2009-08-31 10:13:04 -04001527
1528/**********************************************************************
1529 * *
1530 * Functions that adjust GPT data structures WITHOUT user interaction *
1531 * (they may display information for the user's benefit, though) *
1532 * *
1533 **********************************************************************/
1534
1535// Resizes GPT to specified number of entries. Creates a new table if
srs5694ba00fed2010-01-12 18:18:36 -05001536// necessary, copies data if it already exists. Returns 1 if all goes
1537// well, 0 if an error is encountered.
srs5694e4ac11e2009-08-31 10:13:04 -04001538int GPTData::SetGPTSize(uint32_t numEntries) {
srs569408bb0da2010-02-19 17:19:55 -05001539 GPTPart* newParts;
1540 GPTPart* trash;
srs5694e4ac11e2009-08-31 10:13:04 -04001541 uint32_t i, high, copyNum;
1542 int allOK = 1;
1543
1544 // First, adjust numEntries upward, if necessary, to get a number
1545 // that fills the allocated sectors
1546 i = blockSize / GPT_SIZE;
1547 if ((numEntries % i) != 0) {
srs5694fed16d02010-01-27 23:03:40 -05001548 cout << "Adjusting GPT size from " << numEntries << " to ";
srs5694e4ac11e2009-08-31 10:13:04 -04001549 numEntries = ((numEntries / i) + 1) * i;
srs5694fed16d02010-01-27 23:03:40 -05001550 cout << numEntries << " to fill the sector\n";
srs5694e4ac11e2009-08-31 10:13:04 -04001551 } // if
1552
srs5694247657a2009-11-26 18:36:12 -05001553 // Do the work only if the # of partitions is changing. Along with being
srs569455d92612010-03-07 22:16:07 -05001554 // efficient, this prevents mucking with the location of the secondary
srs5694247657a2009-11-26 18:36:12 -05001555 // partition table, which causes problems when loading data from a RAID
1556 // array that's been expanded because this function is called when loading
1557 // data.
srs569455d92612010-03-07 22:16:07 -05001558 if (((numEntries != mainHeader.numParts) || (numEntries != secondHeader.numParts)
1559 || (partitions == NULL)) && (numEntries > 0)) {
srs5694cb76c672010-02-11 22:22:22 -05001560 newParts = new GPTPart [numEntries * sizeof (GPTPart)];
srs5694247657a2009-11-26 18:36:12 -05001561 if (newParts != NULL) {
1562 if (partitions != NULL) { // existing partitions; copy them over
1563 GetPartRange(&i, &high);
1564 if (numEntries < (high + 1)) { // Highest entry too high for new #
srs5694fed16d02010-01-27 23:03:40 -05001565 cout << "The highest-numbered partition is " << high + 1
1566 << ", which is greater than the requested\n"
1567 << "partition table size of " << numEntries
1568 << "; cannot resize. Perhaps sorting will help.\n";
srs5694247657a2009-11-26 18:36:12 -05001569 allOK = 0;
1570 } else { // go ahead with copy
1571 if (numEntries < mainHeader.numParts)
1572 copyNum = numEntries;
1573 else
1574 copyNum = mainHeader.numParts;
1575 for (i = 0; i < copyNum; i++) {
1576 newParts[i] = partitions[i];
1577 } // for
1578 trash = partitions;
1579 partitions = newParts;
srs5694cb76c672010-02-11 22:22:22 -05001580 delete[] trash;
srs5694247657a2009-11-26 18:36:12 -05001581 } // if
1582 } else { // No existing partition table; just create it
srs5694e4ac11e2009-08-31 10:13:04 -04001583 partitions = newParts;
srs5694247657a2009-11-26 18:36:12 -05001584 } // if/else existing partitions
1585 mainHeader.numParts = numEntries;
1586 secondHeader.numParts = numEntries;
1587 mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + 2 ;
1588 secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1589 MoveSecondHeaderToEnd();
1590 if (diskSize > 0)
1591 CheckGPTSize();
1592 } else { // Bad memory allocation
srs5694fed16d02010-01-27 23:03:40 -05001593 cerr << "Error allocating memory for partition table!\n";
srs5694247657a2009-11-26 18:36:12 -05001594 allOK = 0;
1595 } // if/else
srs5694e4ac11e2009-08-31 10:13:04 -04001596 } // if/else
1597 return (allOK);
1598} // GPTData::SetGPTSize()
1599
1600// Blank the partition array
1601void GPTData::BlankPartitions(void) {
1602 uint32_t i;
1603
1604 for (i = 0; i < mainHeader.numParts; i++) {
1605 partitions[i].BlankPartition();
1606 } // for
1607} // GPTData::BlankPartitions()
1608
srs5694ba00fed2010-01-12 18:18:36 -05001609// Delete a partition by number. Returns 1 if successful,
1610// 0 if there was a problem. Returns 1 if partition was in
1611// range, 0 if it was out of range.
1612int GPTData::DeletePartition(uint32_t partNum) {
1613 uint64_t startSector, length;
1614 uint32_t low, high, numParts, retval = 1;;
1615
1616 numParts = GetPartRange(&low, &high);
1617 if ((numParts > 0) && (partNum >= low) && (partNum <= high)) {
1618 // In case there's a protective MBR, look for & delete matching
1619 // MBR partition....
1620 startSector = partitions[partNum].GetFirstLBA();
1621 length = partitions[partNum].GetLengthLBA();
1622 protectiveMBR.DeleteByLocation(startSector, length);
1623
1624 // Now delete the GPT partition
1625 partitions[partNum].BlankPartition();
1626 } else {
srs5694fed16d02010-01-27 23:03:40 -05001627 cerr << "Partition number " << partNum + 1 << " out of range!\n";
srs5694ba00fed2010-01-12 18:18:36 -05001628 retval = 0;
1629 } // if/else
1630 return retval;
1631} // GPTData::DeletePartition(uint32_t partNum)
1632
srs569408bb0da2010-02-19 17:19:55 -05001633// Non-interactively create a partition.
1634// Returns 1 if the operation was successful, 0 if a problem was discovered.
srs5694e321d442010-01-29 17:44:04 -05001635uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
srs5694ba00fed2010-01-12 18:18:36 -05001636 int retval = 1; // assume there'll be no problems
1637
1638 if (IsFreePartNum(partNum)) {
1639 Align(&startSector); // Align sector to correct multiple
1640 if (IsFree(startSector) && (startSector <= endSector)) {
1641 if (FindLastInFree(startSector) >= endSector) {
1642 partitions[partNum].SetFirstLBA(startSector);
1643 partitions[partNum].SetLastLBA(endSector);
1644 partitions[partNum].SetType(0x0700);
srs56946699b012010-02-04 00:55:30 -05001645 partitions[partNum].RandomizeUniqueGUID();
srs5694ba00fed2010-01-12 18:18:36 -05001646 } else retval = 0; // if free space until endSector
1647 } else retval = 0; // if startSector is free
1648 } else retval = 0; // if legal partition number
1649 return retval;
1650} // GPTData::CreatePartition(partNum, startSector, endSector)
1651
srs5694e4ac11e2009-08-31 10:13:04 -04001652// Sort the GPT entries, eliminating gaps and making for a logical
1653// ordering. Relies on QuickSortGPT() for the bulk of the work
1654void GPTData::SortGPT(void) {
srs5694546a9c72010-01-26 16:00:26 -05001655 uint32_t i, numFound, firstPart, lastPart;
srs5694e4ac11e2009-08-31 10:13:04 -04001656
1657 // First, find the last partition with data, so as not to
1658 // spend needless time sorting empty entries....
srs5694546a9c72010-01-26 16:00:26 -05001659 numFound = GetPartRange(&firstPart, &lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001660
1661 // Now swap empties with the last partitions, to simplify the logic
1662 // in the Quicksort function....
1663 i = 0;
1664 while (i < lastPart) {
1665 if (partitions[i].GetFirstLBA() == 0) {
srs569408bb0da2010-02-19 17:19:55 -05001666 SwapPartitions(i, lastPart);
srs5694546a9c72010-01-26 16:00:26 -05001667 do {
1668 lastPart--;
1669 } while ((lastPart > 0) && (partitions[lastPart].GetFirstLBA() == 0));
srs5694e4ac11e2009-08-31 10:13:04 -04001670 } // if
1671 i++;
1672 } // while
1673
srs5694546a9c72010-01-26 16:00:26 -05001674 // If there are more empties than partitions in the range from 0 to lastPart,
1675 // the above leaves lastPart set too high, so we've got to adjust it to
1676 // prevent empties from migrating to the top of the list....
1677 GetPartRange(&firstPart, &lastPart);
1678
srs5694e4ac11e2009-08-31 10:13:04 -04001679 // Now call the recursive quick sort routine to do the real work....
srs569408bb0da2010-02-19 17:19:55 -05001680 QuickSortGPT(0, lastPart);
srs5694e4ac11e2009-08-31 10:13:04 -04001681} // GPTData::SortGPT()
1682
srs569408bb0da2010-02-19 17:19:55 -05001683// Recursive quick sort algorithm for GPT partitions. Note that if there
1684// are any empties in the specified range, they'll be sorted to the
1685// start, resulting in a sorted set of partitions that begins with
1686// partition 2, 3, or higher.
1687void GPTData::QuickSortGPT(int start, int finish) {
1688 uint64_t starterValue; // starting location of median partition
1689 int left, right;
1690
1691 left = start;
1692 right = finish;
1693 starterValue = partitions[(start + finish) / 2].GetFirstLBA();
1694 do {
1695 while (partitions[left].GetFirstLBA() < starterValue)
1696 left++;
1697 while (partitions[right].GetFirstLBA() > starterValue)
1698 right--;
1699 if (left <= right)
1700 SwapPartitions(left++, right--);
1701 } while (left <= right);
1702 if (start < right) QuickSortGPT(start, right);
1703 if (finish > left) QuickSortGPT(left, finish);
1704} // GPTData::QuickSortGPT()
1705
1706// Swap the contents of two partitions.
1707// Returns 1 if successful, 0 if either partition is out of range
1708// (that is, not a legal number; either or both can be empty).
1709// Note that if partNum1 = partNum2 and this number is in range,
1710// it will be considered successful.
1711int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1712 GPTPart temp;
1713 int allOK = 1;
1714
1715 if ((partNum1 < mainHeader.numParts) && (partNum2 < mainHeader.numParts)) {
1716 if (partNum1 != partNum2) {
1717 temp = partitions[partNum1];
1718 partitions[partNum1] = partitions[partNum2];
1719 partitions[partNum2] = temp;
1720 } // if
1721 } else allOK = 0; // partition numbers are valid
1722 return allOK;
1723} // GPTData::SwapPartitions()
1724
srs5694e4ac11e2009-08-31 10:13:04 -04001725// Set up data structures for entirely new set of partitions on the
1726// specified device. Returns 1 if OK, 0 if there were problems.
srs5694e35eb1b2009-09-14 00:29:34 -04001727// Note that this function does NOT clear the protectiveMBR data
1728// structure, since it may hold the original MBR partitions if the
1729// program was launched on an MBR disk, and those may need to be
1730// converted to GPT format.
srs5694e4ac11e2009-08-31 10:13:04 -04001731int GPTData::ClearGPTData(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001732 int goOn = 1, i;
srs5694e4ac11e2009-08-31 10:13:04 -04001733
1734 // Set up the partition table....
srs5694fed16d02010-01-27 23:03:40 -05001735 if (partitions != NULL)
srs5694cb76c672010-02-11 22:22:22 -05001736 delete[] partitions;
srs5694e4ac11e2009-08-31 10:13:04 -04001737 partitions = NULL;
1738 SetGPTSize(NUM_GPT_ENTRIES);
1739
1740 // Now initialize a bunch of stuff that's static....
1741 mainHeader.signature = GPT_SIGNATURE;
1742 mainHeader.revision = 0x00010000;
srs5694978041c2009-09-21 20:51:47 -04001743 mainHeader.headerSize = HEADER_SIZE;
srs5694e4ac11e2009-08-31 10:13:04 -04001744 mainHeader.reserved = 0;
1745 mainHeader.currentLBA = UINT64_C(1);
1746 mainHeader.partitionEntriesLBA = (uint64_t) 2;
1747 mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1748 for (i = 0; i < GPT_RESERVED; i++) {
1749 mainHeader.reserved2[i] = '\0';
1750 } // for
srs56948a4ddfc2010-03-21 19:05:49 -04001751 sectorAlignment = DEFAULT_ALIGNMENT;
srs5694e4ac11e2009-08-31 10:13:04 -04001752
1753 // Now some semi-static items (computed based on end of disk)
1754 mainHeader.backupLBA = diskSize - UINT64_C(1);
1755 mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1756
1757 // Set a unique GUID for the disk, based on random numbers
srs56946699b012010-02-04 00:55:30 -05001758 mainHeader.diskGUID.Randomize();
srs5694e4ac11e2009-08-31 10:13:04 -04001759
1760 // Copy main header to backup header
1761 RebuildSecondHeader();
1762
1763 // Blank out the partitions array....
1764 BlankPartitions();
1765
1766 // Flag all CRCs as being OK....
1767 mainCrcOk = 1;
1768 secondCrcOk = 1;
1769 mainPartsCrcOk = 1;
1770 secondPartsCrcOk = 1;
1771
1772 return (goOn);
1773} // GPTData::ClearGPTData()
1774
srs5694247657a2009-11-26 18:36:12 -05001775// Set the location of the second GPT header data to the end of the disk.
1776// Used internally and called by the 'e' option on the recovery &
1777// transformation menu, to help users of RAID arrays who add disk space
1778// to their arrays.
1779void GPTData::MoveSecondHeaderToEnd() {
srs56948bb78762009-11-24 15:43:49 -05001780 mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1781 mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1782 secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1783} // GPTData::FixSecondHeaderLocation()
1784
srs56940a697312010-01-28 21:10:52 -05001785int GPTData::SetName(uint32_t partNum, const string & theName) {
srs5694ba00fed2010-01-12 18:18:36 -05001786 int retval = 1;
srs5694fed16d02010-01-27 23:03:40 -05001787
1788 if (!IsFreePartNum(partNum)) {
1789 partitions[partNum].SetName(theName);
1790 } else retval = 0;
srs5694ba00fed2010-01-12 18:18:36 -05001791
1792 return retval;
srs5694e4ac11e2009-08-31 10:13:04 -04001793} // GPTData::SetName
1794
1795// Set the disk GUID to the specified value. Note that the header CRCs must
1796// be recomputed after calling this function.
1797void GPTData::SetDiskGUID(GUIDData newGUID) {
1798 mainHeader.diskGUID = newGUID;
1799 secondHeader.diskGUID = newGUID;
1800} // SetDiskGUID()
1801
1802// Set the unique GUID of the specified partition. Returns 1 on
1803// successful completion, 0 if there were problems (invalid
1804// partition number).
1805int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1806 int retval = 0;
1807
1808 if (pn < mainHeader.numParts) {
1809 if (partitions[pn].GetFirstLBA() != UINT64_C(0)) {
1810 partitions[pn].SetUniqueGUID(theGUID);
1811 retval = 1;
1812 } // if
1813 } // if
1814 return retval;
1815} // GPTData::SetPartitionGUID()
1816
srs5694ba00fed2010-01-12 18:18:36 -05001817// Change partition type code non-interactively. Returns 1 if
1818// successful, 0 if not....
1819int GPTData::ChangePartType(uint32_t partNum, uint16_t hexCode) {
1820 int retval = 1;
1821
1822 if (!IsFreePartNum(partNum)) {
1823 partitions[partNum].SetType(hexCode);
1824 } else retval = 0;
1825 return retval;
1826} // GPTData::ChangePartType()
1827
srs56941d1448a2009-12-31 21:20:19 -05001828// Adjust sector number so that it falls on a sector boundary that's a
1829// multiple of sectorAlignment. This is done to improve the performance
1830// of Western Digital Advanced Format disks and disks with similar
1831// technology from other companies, which use 4096-byte sectors
1832// internally although they translate to 512-byte sectors for the
1833// benefit of the OS. If partitions aren't properly aligned on these
1834// disks, some filesystem data structures can span multiple physical
1835// sectors, degrading performance. This function should be called
1836// only on the FIRST sector of the partition, not the last!
1837// This function returns 1 if the alignment was altered, 0 if it
1838// was unchanged.
1839int GPTData::Align(uint64_t* sector) {
1840 int retval = 0, sectorOK = 0;
1841 uint64_t earlier, later, testSector, original;
1842
1843 if ((*sector % sectorAlignment) != 0) {
1844 original = *sector;
1845 retval = 1;
1846 earlier = (*sector / sectorAlignment) * sectorAlignment;
1847 later = earlier + (uint64_t) sectorAlignment;
1848
1849 // Check to see that every sector between the earlier one and the
1850 // requested one is clear, and that it's not too early....
1851 if (earlier >= mainHeader.firstUsableLBA) {
srs56941d1448a2009-12-31 21:20:19 -05001852 sectorOK = 1;
1853 testSector = earlier;
1854 do {
1855 sectorOK = IsFree(testSector++);
1856 } while ((sectorOK == 1) && (testSector < *sector));
1857 if (sectorOK == 1) {
1858 *sector = earlier;
srs56941d1448a2009-12-31 21:20:19 -05001859 } // if
1860 } // if firstUsableLBA check
1861
1862 // If couldn't move the sector earlier, try to move it later instead....
1863 if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
1864 sectorOK = 1;
1865 testSector = later;
1866 do {
1867 sectorOK = IsFree(testSector--);
1868 } while ((sectorOK == 1) && (testSector > *sector));
1869 if (sectorOK == 1) {
1870 *sector = later;
srs56941d1448a2009-12-31 21:20:19 -05001871 } // if
1872 } // if
1873
1874 // If sector was changed successfully, inform the user of this fact.
1875 // Otherwise, notify the user that it couldn't be done....
1876 if (sectorOK == 1) {
srs5694fed16d02010-01-27 23:03:40 -05001877 cout << "Information: Moved requested sector from " << original << " to "
srs56948a4ddfc2010-03-21 19:05:49 -04001878 << *sector << " in\norder to align on " << sectorAlignment
1879 << "-sector boundaries.\n";
srs5694ba00fed2010-01-12 18:18:36 -05001880 if (!beQuiet)
srs5694fed16d02010-01-27 23:03:40 -05001881 cout << "Use 'l' on the experts' menu to adjust alignment\n";
srs56941d1448a2009-12-31 21:20:19 -05001882 } else {
srs5694fed16d02010-01-27 23:03:40 -05001883 cout << "Information: Sector not aligned on " << sectorAlignment
1884 << "-sector boundary and could not be moved.\n"
1885 << "If you're using a Western Digital Advanced Format or similar disk with\n"
srs56948a4ddfc2010-03-21 19:05:49 -04001886 << "underlying 4096-byte sectors or certain types of RAID array, performance\n"
1887 << "may suffer.\n";
srs56941d1448a2009-12-31 21:20:19 -05001888 retval = 0;
1889 } // if/else
1890 } // if
1891 return retval;
1892} // GPTData::Align()
1893
srs5694e4ac11e2009-08-31 10:13:04 -04001894/********************************************************
1895 * *
1896 * Functions that return data about GPT data structures *
1897 * (most of these are inline in gpt.h) *
1898 * *
1899 ********************************************************/
1900
1901// Find the low and high used partition numbers (numbered from 0).
1902// Return value is the number of partitions found. Note that the
1903// *low and *high values are both set to 0 when no partitions
1904// are found, as well as when a single partition in the first
1905// position exists. Thus, the return value is the only way to
1906// tell when no partitions exist.
1907int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
1908 uint32_t i;
1909 int numFound = 0;
1910
1911 *low = mainHeader.numParts + 1; // code for "not found"
1912 *high = 0;
1913 if (mainHeader.numParts > 0) { // only try if partition table exists...
1914 for (i = 0; i < mainHeader.numParts; i++) {
1915 if (partitions[i].GetFirstLBA() != UINT64_C(0)) { // it exists
1916 *high = i; // since we're counting up, set the high value
srs569408bb0da2010-02-19 17:19:55 -05001917 // Set the low value only if it's not yet found...
srs5694e4ac11e2009-08-31 10:13:04 -04001918 if (*low == (mainHeader.numParts + 1)) *low = i;
srs569408bb0da2010-02-19 17:19:55 -05001919 numFound++;
srs5694e4ac11e2009-08-31 10:13:04 -04001920 } // if
1921 } // for
1922 } // if
1923
1924 // Above will leave *low pointing to its "not found" value if no partitions
1925 // are defined, so reset to 0 if this is the case....
1926 if (*low == (mainHeader.numParts + 1))
1927 *low = 0;
1928 return numFound;
1929} // GPTData::GetPartRange()
1930
srs569408bb0da2010-02-19 17:19:55 -05001931// Returns the value of the first free partition, or -1 if none is
1932// unused.
1933int GPTData::FindFirstFreePart(void) {
1934 int i = 0;
1935
1936 if (partitions != NULL) {
1937 while ((partitions[i].IsUsed()) && (i < (int) mainHeader.numParts))
1938 i++;
1939 if (i >= (int) mainHeader.numParts)
1940 i = -1;
1941 } else i = -1;
1942 return i;
1943} // GPTData::FindFirstFreePart()
1944
srs5694978041c2009-09-21 20:51:47 -04001945// Returns the number of defined partitions.
1946uint32_t GPTData::CountParts(void) {
srs5694e321d442010-01-29 17:44:04 -05001947 uint32_t i, counted = 0;
srs5694978041c2009-09-21 20:51:47 -04001948
1949 for (i = 0; i < mainHeader.numParts; i++) {
srs569408bb0da2010-02-19 17:19:55 -05001950 if (partitions[i].IsUsed())
srs5694978041c2009-09-21 20:51:47 -04001951 counted++;
1952 } // for
1953 return counted;
1954} // GPTData::CountParts()
1955
srs5694e4ac11e2009-08-31 10:13:04 -04001956/****************************************************
1957 * *
1958 * Functions that return data about disk free space *
1959 * *
1960 ****************************************************/
1961
1962// Find the first available block after the starting point; returns 0 if
1963// there are no available blocks left
1964uint64_t GPTData::FindFirstAvailable(uint64_t start) {
1965 uint64_t first;
1966 uint32_t i;
1967 int firstMoved = 0;
1968
1969 // Begin from the specified starting point or from the first usable
1970 // LBA, whichever is greater...
1971 if (start < mainHeader.firstUsableLBA)
1972 first = mainHeader.firstUsableLBA;
1973 else
1974 first = start;
1975
1976 // ...now search through all partitions; if first is within an
1977 // existing partition, move it to the next sector after that
1978 // partition and repeat. If first was moved, set firstMoved
1979 // flag; repeat until firstMoved is not set, so as to catch
1980 // cases where partitions are out of sequential order....
1981 do {
1982 firstMoved = 0;
1983 for (i = 0; i < mainHeader.numParts; i++) {
1984 if ((first >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05001985 (first <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04001986 first = partitions[i].GetLastLBA() + 1;
1987 firstMoved = 1;
srs569455d92612010-03-07 22:16:07 -05001988 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04001989 } // for
1990 } while (firstMoved == 1);
1991 if (first > mainHeader.lastUsableLBA)
1992 first = 0;
1993 return (first);
1994} // GPTData::FindFirstAvailable()
1995
1996// Finds the first available sector in the largest block of unallocated
1997// space on the disk. Returns 0 if there are no available blocks left
1998uint64_t GPTData::FindFirstInLargest(void) {
srs5694e35eb1b2009-09-14 00:29:34 -04001999 uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002000
2001 start = 0;
2002 do {
2003 firstBlock = FindFirstAvailable(start);
2004 if (firstBlock != UINT32_C(0)) { // something's free...
2005 lastBlock = FindLastInFree(firstBlock);
2006 segmentSize = lastBlock - firstBlock + UINT32_C(1);
2007 if (segmentSize > selectedSize) {
2008 selectedSize = segmentSize;
2009 selectedSegment = firstBlock;
2010 } // if
2011 start = lastBlock + 1;
2012 } // if
2013 } while (firstBlock != 0);
2014 return selectedSegment;
2015} // GPTData::FindFirstInLargest()
2016
srs5694cb76c672010-02-11 22:22:22 -05002017// Find the last available block on the disk.
2018// Returns 0 if there are no available partitions
2019uint64_t GPTData::FindLastAvailable(void) {
srs5694e4ac11e2009-08-31 10:13:04 -04002020 uint64_t last;
2021 uint32_t i;
2022 int lastMoved = 0;
2023
2024 // Start by assuming the last usable LBA is available....
2025 last = mainHeader.lastUsableLBA;
2026
2027 // ...now, similar to algorithm in FindFirstAvailable(), search
2028 // through all partitions, moving last when it's in an existing
2029 // partition. Set the lastMoved flag so we repeat to catch cases
2030 // where partitions are out of logical order.
2031 do {
2032 lastMoved = 0;
2033 for (i = 0; i < mainHeader.numParts; i++) {
2034 if ((last >= partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002035 (last <= partitions[i].GetLastLBA())) { // in existing part.
srs5694e4ac11e2009-08-31 10:13:04 -04002036 last = partitions[i].GetFirstLBA() - 1;
2037 lastMoved = 1;
srs569455d92612010-03-07 22:16:07 -05002038 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002039 } // for
2040 } while (lastMoved == 1);
2041 if (last < mainHeader.firstUsableLBA)
2042 last = 0;
2043 return (last);
2044} // GPTData::FindLastAvailable()
2045
2046// Find the last available block in the free space pointed to by start.
2047uint64_t GPTData::FindLastInFree(uint64_t start) {
2048 uint64_t nearestStart;
2049 uint32_t i;
2050
2051 nearestStart = mainHeader.lastUsableLBA;
2052 for (i = 0; i < mainHeader.numParts; i++) {
2053 if ((nearestStart > partitions[i].GetFirstLBA()) &&
srs569455d92612010-03-07 22:16:07 -05002054 (partitions[i].GetFirstLBA() > start)) {
srs5694e4ac11e2009-08-31 10:13:04 -04002055 nearestStart = partitions[i].GetFirstLBA() - 1;
srs569455d92612010-03-07 22:16:07 -05002056 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002057 } // for
2058 return (nearestStart);
2059} // GPTData::FindLastInFree()
2060
2061// Finds the total number of free blocks, the number of segments in which
2062// they reside, and the size of the largest of those segments
srs5694e321d442010-01-29 17:44:04 -05002063uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
srs5694e4ac11e2009-08-31 10:13:04 -04002064 uint64_t start = UINT64_C(0); // starting point for each search
2065 uint64_t totalFound = UINT64_C(0); // running total
2066 uint64_t firstBlock; // first block in a segment
2067 uint64_t lastBlock; // last block in a segment
2068 uint64_t segmentSize; // size of segment in blocks
srs5694e321d442010-01-29 17:44:04 -05002069 uint32_t num = 0;
srs5694e4ac11e2009-08-31 10:13:04 -04002070
2071 *largestSegment = UINT64_C(0);
2072 do {
2073 firstBlock = FindFirstAvailable(start);
2074 if (firstBlock != UINT64_C(0)) { // something's free...
2075 lastBlock = FindLastInFree(firstBlock);
2076 segmentSize = lastBlock - firstBlock + UINT64_C(1);
2077 if (segmentSize > *largestSegment) {
2078 *largestSegment = segmentSize;
2079 } // if
2080 totalFound += segmentSize;
2081 num++;
2082 start = lastBlock + 1;
2083 } // if
2084 } while (firstBlock != 0);
2085 *numSegments = num;
2086 return totalFound;
2087} // GPTData::FindFreeBlocks()
2088
srs569455d92612010-03-07 22:16:07 -05002089// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2090// If it's allocated, return the partition number to which it's allocated
2091// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2092// returned in partNum if the sector is in use by basic GPT data structures.)
2093int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
srs5694e4ac11e2009-08-31 10:13:04 -04002094 int isFree = 1;
2095 uint32_t i;
2096
2097 for (i = 0; i < mainHeader.numParts; i++) {
2098 if ((sector >= partitions[i].GetFirstLBA()) &&
2099 (sector <= partitions[i].GetLastLBA())) {
2100 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002101 if (partNum != NULL)
2102 *partNum = i;
srs569408bb0da2010-02-19 17:19:55 -05002103 } // if
srs5694e4ac11e2009-08-31 10:13:04 -04002104 } // for
srs5694e35eb1b2009-09-14 00:29:34 -04002105 if ((sector < mainHeader.firstUsableLBA) ||
srs5694e4ac11e2009-08-31 10:13:04 -04002106 (sector > mainHeader.lastUsableLBA)) {
2107 isFree = 0;
srs569455d92612010-03-07 22:16:07 -05002108 if (partNum != NULL)
2109 *partNum = UINT32_MAX;
srs569408bb0da2010-02-19 17:19:55 -05002110 } // if
2111 return (isFree);
srs5694e4ac11e2009-08-31 10:13:04 -04002112} // GPTData::IsFree()
2113
srs5694ba00fed2010-01-12 18:18:36 -05002114// Returns 1 if partNum is unused.
2115int GPTData::IsFreePartNum(uint32_t partNum) {
2116 int retval = 1;
2117
srs569408bb0da2010-02-19 17:19:55 -05002118 if ((partNum < mainHeader.numParts) && (partitions != NULL)) {
2119 if (partitions[partNum].IsUsed()) {
srs5694ba00fed2010-01-12 18:18:36 -05002120 retval = 0;
2121 } // if partition is in use
2122 } else retval = 0;
2123
2124 return retval;
2125} // GPTData::IsFreePartNum()
2126
srs5694a8582cf2010-03-19 14:21:59 -04002127
2128/***********************************************************
2129 * *
2130 * Change how functions work or return information on them *
2131 * *
2132 ***********************************************************/
2133
2134// Set partition alignment value; partitions will begin on multiples of
2135// the specified value
2136void GPTData::SetAlignment(uint32_t n) {
2137 uint32_t l2;
2138
2139 sectorAlignment = n;
2140 l2 = (uint32_t) log2(n);
srs5694a8582cf2010-03-19 14:21:59 -04002141} // GPTData::SetAlignment()
2142
2143// Compute sector alignment based on the current partitions (if any). Each
2144// partition's starting LBA is examined, and if it's divisible by a power-of-2
srs56948a4ddfc2010-03-21 19:05:49 -04002145// value less than or equal to the DEFAULT_ALIGNMENT value, but not by the
2146// previously-located alignment value, then the alignment value is adjusted
2147// down. If the computed alignment is less than 8 and the disk is bigger than
2148// SMALLEST_ADVANCED_FORMAT, resets it to 8. This is a safety measure for WD
2149// Advanced Format and similar drives. If no partitions are defined, the
2150// alignment value is set to DEFAULT_ALIGNMENT (2048). The result is that new
2151// drives are aligned to 2048-sector multiples but the program won't complain
2152// about other alignments on existing disks unless a smaller-than-8 alignment
2153// is used on small disks (as safety for WD Advanced Format drives).
srs5694a8582cf2010-03-19 14:21:59 -04002154// Returns the computed alignment value.
2155uint32_t GPTData::ComputeAlignment(void) {
2156 uint32_t i = 0, found, exponent = 31;
2157 uint64_t align = DEFAULT_ALIGNMENT;
2158
srs56948a4ddfc2010-03-21 19:05:49 -04002159 exponent = (uint32_t) log2(DEFAULT_ALIGNMENT);
srs5694a8582cf2010-03-19 14:21:59 -04002160 for (i = 0; i < mainHeader.numParts; i++) {
2161 if (partitions[i].IsUsed()) {
2162 found = 0;
2163 while (!found) {
2164 align = PowerOf2(exponent);
2165 if ((partitions[i].GetFirstLBA() % align) == 0) {
2166 found = 1;
2167 } else {
2168 exponent--;
2169 } // if/else
2170 } // while
2171 } // if
2172 } // for
2173 if ((align < 8) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2174 align = 8;
srs5694a8582cf2010-03-19 14:21:59 -04002175 SetAlignment(align);
2176 return align;
2177} // GPTData::ComputeAlignment()
2178
srs5694e4ac11e2009-08-31 10:13:04 -04002179/********************************
2180 * *
2181 * Endianness support functions *
2182 * *
2183 ********************************/
2184
srs56942a9f5da2009-08-26 00:48:01 -04002185void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
srs5694221e0872009-08-29 15:00:31 -04002186 ReverseBytes(&header->signature, 8);
2187 ReverseBytes(&header->revision, 4);
2188 ReverseBytes(&header->headerSize, 4);
2189 ReverseBytes(&header->headerCRC, 4);
2190 ReverseBytes(&header->reserved, 4);
2191 ReverseBytes(&header->currentLBA, 8);
2192 ReverseBytes(&header->backupLBA, 8);
2193 ReverseBytes(&header->firstUsableLBA, 8);
2194 ReverseBytes(&header->lastUsableLBA, 8);
2195 ReverseBytes(&header->partitionEntriesLBA, 8);
2196 ReverseBytes(&header->numParts, 4);
2197 ReverseBytes(&header->sizeOfPartitionEntries, 4);
2198 ReverseBytes(&header->partitionEntriesCRC, 4);
srs569408bb0da2010-02-19 17:19:55 -05002199 ReverseBytes(header->reserved2, GPT_RESERVED);
srs56942a9f5da2009-08-26 00:48:01 -04002200} // GPTData::ReverseHeaderBytes()
2201
2202// IMPORTANT NOTE: This function requires non-reversed mainHeader
2203// structure!
2204void GPTData::ReversePartitionBytes() {
2205 uint32_t i;
2206
2207 // Check GPT signature on big-endian systems; this will mismatch
2208 // if the function is called out of order. Unfortunately, it'll also
2209 // mismatch if there's data corruption.
2210 if ((mainHeader.signature != GPT_SIGNATURE) && (IsLittleEndian() == 0)) {
srs5694fed16d02010-01-27 23:03:40 -05002211 cerr << "GPT signature mismatch in GPTData::ReversePartitionBytes(). This indicates\n"
2212 << "data corruption or a misplaced call to this function.\n";
srs56942a9f5da2009-08-26 00:48:01 -04002213 } // if signature mismatch....
2214 for (i = 0; i < mainHeader.numParts; i++) {
srs5694221e0872009-08-29 15:00:31 -04002215 partitions[i].ReversePartBytes();
srs56942a9f5da2009-08-26 00:48:01 -04002216 } // for
2217} // GPTData::ReversePartitionBytes()
2218
2219/******************************************
2220 * *
2221 * Additional non-class support functions *
2222 * *
2223 ******************************************/
2224
srs5694e7b4ff92009-08-18 13:16:10 -04002225// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2226// never fail these tests, but the struct types may fail depending on compile options.
2227// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2228// sizes.
2229int SizesOK(void) {
2230 int allOK = 1;
srs5694e7b4ff92009-08-18 13:16:10 -04002231
2232 if (sizeof(uint8_t) != 1) {
srs5694fed16d02010-01-27 23:03:40 -05002233 cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002234 allOK = 0;
2235 } // if
2236 if (sizeof(uint16_t) != 2) {
srs5694fed16d02010-01-27 23:03:40 -05002237 cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002238 allOK = 0;
2239 } // if
2240 if (sizeof(uint32_t) != 4) {
srs5694fed16d02010-01-27 23:03:40 -05002241 cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002242 allOK = 0;
2243 } // if
2244 if (sizeof(uint64_t) != 8) {
srs5694fed16d02010-01-27 23:03:40 -05002245 cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002246 allOK = 0;
2247 } // if
2248 if (sizeof(struct MBRRecord) != 16) {
srs5694fed16d02010-01-27 23:03:40 -05002249 cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002250 allOK = 0;
2251 } // if
srs5694978041c2009-09-21 20:51:47 -04002252 if (sizeof(struct TempMBR) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002253 cerr << "TempMBR is " << sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002254 allOK = 0;
2255 } // if
2256 if (sizeof(struct GPTHeader) != 512) {
srs5694fed16d02010-01-27 23:03:40 -05002257 cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002258 allOK = 0;
2259 } // if
srs5694221e0872009-08-29 15:00:31 -04002260 if (sizeof(GPTPart) != 128) {
srs5694fed16d02010-01-27 23:03:40 -05002261 cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
srs5694221e0872009-08-29 15:00:31 -04002262 allOK = 0;
2263 } // if
srs56946699b012010-02-04 00:55:30 -05002264 if (sizeof(GUIDData) != 16) {
2265 cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2266 allOK = 0;
2267 } // if
2268 if (sizeof(PartType) != 16) {
2269 cerr << "PartType is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2270 allOK = 0;
2271 } // if
srs5694fed16d02010-01-27 23:03:40 -05002272 // Determine endianness; warn user if running on big-endian (PowerPC, etc.) hardware
srs56942a9f5da2009-08-26 00:48:01 -04002273 if (IsLittleEndian() == 0) {
srs5694fed16d02010-01-27 23:03:40 -05002274 cerr << "\aRunning on big-endian hardware. Big-endian support is new and poorly"
2275 " tested!\n";
srs5694e7b4ff92009-08-18 13:16:10 -04002276 } // if
2277 return (allOK);
2278} // SizesOK()
srs5694e4ac11e2009-08-31 10:13:04 -04002279