xref: /aosp_15_r20/external/gptfdisk/gpt.cc (revision 57696d54d05c64fd1b1787f8371dbcf104911cfb)
1*57696d54SAkhilesh Sanikop /* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
2*57696d54SAkhilesh Sanikop    data. */
3*57696d54SAkhilesh Sanikop 
4*57696d54SAkhilesh Sanikop /* By Rod Smith, initial coding January to February, 2009 */
5*57696d54SAkhilesh Sanikop 
6*57696d54SAkhilesh Sanikop /* This program is copyright (c) 2009-2022 by Roderick W. Smith. It is distributed
7*57696d54SAkhilesh Sanikop   under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8*57696d54SAkhilesh Sanikop 
9*57696d54SAkhilesh Sanikop #define __STDC_LIMIT_MACROS
10*57696d54SAkhilesh Sanikop #define __STDC_CONSTANT_MACROS
11*57696d54SAkhilesh Sanikop 
12*57696d54SAkhilesh Sanikop #include <stdio.h>
13*57696d54SAkhilesh Sanikop #include <stdlib.h>
14*57696d54SAkhilesh Sanikop #include <stdint.h>
15*57696d54SAkhilesh Sanikop #include <fcntl.h>
16*57696d54SAkhilesh Sanikop #include <string.h>
17*57696d54SAkhilesh Sanikop #include <math.h>
18*57696d54SAkhilesh Sanikop #include <time.h>
19*57696d54SAkhilesh Sanikop #include <sys/stat.h>
20*57696d54SAkhilesh Sanikop #include <errno.h>
21*57696d54SAkhilesh Sanikop #include <iostream>
22*57696d54SAkhilesh Sanikop #include <algorithm>
23*57696d54SAkhilesh Sanikop #include "crc32.h"
24*57696d54SAkhilesh Sanikop #include "gpt.h"
25*57696d54SAkhilesh Sanikop #include "bsd.h"
26*57696d54SAkhilesh Sanikop #include "support.h"
27*57696d54SAkhilesh Sanikop #include "parttypes.h"
28*57696d54SAkhilesh Sanikop #include "attributes.h"
29*57696d54SAkhilesh Sanikop #include "diskio.h"
30*57696d54SAkhilesh Sanikop 
31*57696d54SAkhilesh Sanikop using namespace std;
32*57696d54SAkhilesh Sanikop 
33*57696d54SAkhilesh Sanikop #ifdef __FreeBSD__
34*57696d54SAkhilesh Sanikop #define log2(x) (log(x) / M_LN2)
35*57696d54SAkhilesh Sanikop #endif // __FreeBSD__
36*57696d54SAkhilesh Sanikop 
37*57696d54SAkhilesh Sanikop #ifdef _MSC_VER
38*57696d54SAkhilesh Sanikop #define log2(x) (log((double) x) / log(2.0))
39*57696d54SAkhilesh Sanikop #endif // Microsoft Visual C++
40*57696d54SAkhilesh Sanikop 
41*57696d54SAkhilesh Sanikop #ifdef EFI
42*57696d54SAkhilesh Sanikop // in UEFI mode MMX registers are not yet available so using the
43*57696d54SAkhilesh Sanikop // x86_64 ABI to move "double" values around is not an option.
44*57696d54SAkhilesh Sanikop #ifdef log2
45*57696d54SAkhilesh Sanikop #undef log2
46*57696d54SAkhilesh Sanikop #endif
47*57696d54SAkhilesh Sanikop #define log2(x) log2_32( x )
log2_32(uint32_t v)48*57696d54SAkhilesh Sanikop static inline uint32_t log2_32(uint32_t v) {
49*57696d54SAkhilesh Sanikop    int r = -1;
50*57696d54SAkhilesh Sanikop    while (v >= 1) {
51*57696d54SAkhilesh Sanikop       r++;
52*57696d54SAkhilesh Sanikop       v >>= 1;
53*57696d54SAkhilesh Sanikop    }
54*57696d54SAkhilesh Sanikop    return r;
55*57696d54SAkhilesh Sanikop }
56*57696d54SAkhilesh Sanikop #endif
57*57696d54SAkhilesh Sanikop 
58*57696d54SAkhilesh Sanikop /****************************************
59*57696d54SAkhilesh Sanikop  *                                      *
60*57696d54SAkhilesh Sanikop  * GPTData class and related structures *
61*57696d54SAkhilesh Sanikop  *                                      *
62*57696d54SAkhilesh Sanikop  ****************************************/
63*57696d54SAkhilesh Sanikop 
64*57696d54SAkhilesh Sanikop // Default constructor
GPTData(void)65*57696d54SAkhilesh Sanikop GPTData::GPTData(void) {
66*57696d54SAkhilesh Sanikop    blockSize = SECTOR_SIZE; // set a default
67*57696d54SAkhilesh Sanikop    physBlockSize = 0; // 0 = can't be determined
68*57696d54SAkhilesh Sanikop    diskSize = 0;
69*57696d54SAkhilesh Sanikop    partitions = NULL;
70*57696d54SAkhilesh Sanikop    state = gpt_valid;
71*57696d54SAkhilesh Sanikop    device = "";
72*57696d54SAkhilesh Sanikop    justLooking = 0;
73*57696d54SAkhilesh Sanikop    mainCrcOk = 0;
74*57696d54SAkhilesh Sanikop    secondCrcOk = 0;
75*57696d54SAkhilesh Sanikop    mainPartsCrcOk = 0;
76*57696d54SAkhilesh Sanikop    secondPartsCrcOk = 0;
77*57696d54SAkhilesh Sanikop    apmFound = 0;
78*57696d54SAkhilesh Sanikop    bsdFound = 0;
79*57696d54SAkhilesh Sanikop    sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
80*57696d54SAkhilesh Sanikop    beQuiet = 0;
81*57696d54SAkhilesh Sanikop    whichWasUsed = use_new;
82*57696d54SAkhilesh Sanikop    mainHeader.numParts = 0;
83*57696d54SAkhilesh Sanikop    mainHeader.firstUsableLBA = 0;
84*57696d54SAkhilesh Sanikop    mainHeader.lastUsableLBA = 0;
85*57696d54SAkhilesh Sanikop    numParts = 0;
86*57696d54SAkhilesh Sanikop    SetGPTSize(NUM_GPT_ENTRIES);
87*57696d54SAkhilesh Sanikop    // Initialize CRC functions...
88*57696d54SAkhilesh Sanikop    chksum_crc32gentab();
89*57696d54SAkhilesh Sanikop } // GPTData default constructor
90*57696d54SAkhilesh Sanikop 
GPTData(const GPTData & orig)91*57696d54SAkhilesh Sanikop GPTData::GPTData(const GPTData & orig) {
92*57696d54SAkhilesh Sanikop    uint32_t i;
93*57696d54SAkhilesh Sanikop 
94*57696d54SAkhilesh Sanikop    if (&orig != this) {
95*57696d54SAkhilesh Sanikop       mainHeader = orig.mainHeader;
96*57696d54SAkhilesh Sanikop       numParts = orig.numParts;
97*57696d54SAkhilesh Sanikop       secondHeader = orig.secondHeader;
98*57696d54SAkhilesh Sanikop       protectiveMBR = orig.protectiveMBR;
99*57696d54SAkhilesh Sanikop       device = orig.device;
100*57696d54SAkhilesh Sanikop       blockSize = orig.blockSize;
101*57696d54SAkhilesh Sanikop       physBlockSize = orig.physBlockSize;
102*57696d54SAkhilesh Sanikop       diskSize = orig.diskSize;
103*57696d54SAkhilesh Sanikop       state = orig.state;
104*57696d54SAkhilesh Sanikop       justLooking = orig.justLooking;
105*57696d54SAkhilesh Sanikop       mainCrcOk = orig.mainCrcOk;
106*57696d54SAkhilesh Sanikop       secondCrcOk = orig.secondCrcOk;
107*57696d54SAkhilesh Sanikop       mainPartsCrcOk = orig.mainPartsCrcOk;
108*57696d54SAkhilesh Sanikop       secondPartsCrcOk = orig.secondPartsCrcOk;
109*57696d54SAkhilesh Sanikop       apmFound = orig.apmFound;
110*57696d54SAkhilesh Sanikop       bsdFound = orig.bsdFound;
111*57696d54SAkhilesh Sanikop       sectorAlignment = orig.sectorAlignment;
112*57696d54SAkhilesh Sanikop       beQuiet = orig.beQuiet;
113*57696d54SAkhilesh Sanikop       whichWasUsed = orig.whichWasUsed;
114*57696d54SAkhilesh Sanikop 
115*57696d54SAkhilesh Sanikop       myDisk.OpenForRead(orig.myDisk.GetName());
116*57696d54SAkhilesh Sanikop 
117*57696d54SAkhilesh Sanikop       delete[] partitions;
118*57696d54SAkhilesh Sanikop       partitions = new GPTPart [numParts];
119*57696d54SAkhilesh Sanikop       if (partitions == NULL) {
120*57696d54SAkhilesh Sanikop          cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
121*57696d54SAkhilesh Sanikop               << "Terminating!\n";
122*57696d54SAkhilesh Sanikop          exit(1);
123*57696d54SAkhilesh Sanikop       } // if
124*57696d54SAkhilesh Sanikop       for (i = 0; i < numParts; i++) {
125*57696d54SAkhilesh Sanikop          partitions[i] = orig.partitions[i];
126*57696d54SAkhilesh Sanikop       } // for
127*57696d54SAkhilesh Sanikop    } // if
128*57696d54SAkhilesh Sanikop } // GPTData copy constructor
129*57696d54SAkhilesh Sanikop 
130*57696d54SAkhilesh Sanikop // The following constructor loads GPT data from a device file
GPTData(string filename)131*57696d54SAkhilesh Sanikop GPTData::GPTData(string filename) {
132*57696d54SAkhilesh Sanikop    blockSize = SECTOR_SIZE; // set a default
133*57696d54SAkhilesh Sanikop    diskSize = 0;
134*57696d54SAkhilesh Sanikop    partitions = NULL;
135*57696d54SAkhilesh Sanikop    state = gpt_invalid;
136*57696d54SAkhilesh Sanikop    device = "";
137*57696d54SAkhilesh Sanikop    justLooking = 0;
138*57696d54SAkhilesh Sanikop    mainCrcOk = 0;
139*57696d54SAkhilesh Sanikop    secondCrcOk = 0;
140*57696d54SAkhilesh Sanikop    mainPartsCrcOk = 0;
141*57696d54SAkhilesh Sanikop    secondPartsCrcOk = 0;
142*57696d54SAkhilesh Sanikop    apmFound = 0;
143*57696d54SAkhilesh Sanikop    bsdFound = 0;
144*57696d54SAkhilesh Sanikop    sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
145*57696d54SAkhilesh Sanikop    beQuiet = 0;
146*57696d54SAkhilesh Sanikop    whichWasUsed = use_new;
147*57696d54SAkhilesh Sanikop    mainHeader.numParts = 0;
148*57696d54SAkhilesh Sanikop    mainHeader.lastUsableLBA = 0;
149*57696d54SAkhilesh Sanikop    numParts = 0;
150*57696d54SAkhilesh Sanikop    // Initialize CRC functions...
151*57696d54SAkhilesh Sanikop    chksum_crc32gentab();
152*57696d54SAkhilesh Sanikop    if (!LoadPartitions(filename))
153*57696d54SAkhilesh Sanikop       exit(2);
154*57696d54SAkhilesh Sanikop } // GPTData(string filename) constructor
155*57696d54SAkhilesh Sanikop 
156*57696d54SAkhilesh Sanikop // Destructor
~GPTData(void)157*57696d54SAkhilesh Sanikop GPTData::~GPTData(void) {
158*57696d54SAkhilesh Sanikop    delete[] partitions;
159*57696d54SAkhilesh Sanikop } // GPTData destructor
160*57696d54SAkhilesh Sanikop 
161*57696d54SAkhilesh Sanikop // Assignment operator
operator =(const GPTData & orig)162*57696d54SAkhilesh Sanikop GPTData & GPTData::operator=(const GPTData & orig) {
163*57696d54SAkhilesh Sanikop    uint32_t i;
164*57696d54SAkhilesh Sanikop 
165*57696d54SAkhilesh Sanikop    if (&orig != this) {
166*57696d54SAkhilesh Sanikop       mainHeader = orig.mainHeader;
167*57696d54SAkhilesh Sanikop       numParts = orig.numParts;
168*57696d54SAkhilesh Sanikop       secondHeader = orig.secondHeader;
169*57696d54SAkhilesh Sanikop       protectiveMBR = orig.protectiveMBR;
170*57696d54SAkhilesh Sanikop       device = orig.device;
171*57696d54SAkhilesh Sanikop       blockSize = orig.blockSize;
172*57696d54SAkhilesh Sanikop       physBlockSize = orig.physBlockSize;
173*57696d54SAkhilesh Sanikop       diskSize = orig.diskSize;
174*57696d54SAkhilesh Sanikop       state = orig.state;
175*57696d54SAkhilesh Sanikop       justLooking = orig.justLooking;
176*57696d54SAkhilesh Sanikop       mainCrcOk = orig.mainCrcOk;
177*57696d54SAkhilesh Sanikop       secondCrcOk = orig.secondCrcOk;
178*57696d54SAkhilesh Sanikop       mainPartsCrcOk = orig.mainPartsCrcOk;
179*57696d54SAkhilesh Sanikop       secondPartsCrcOk = orig.secondPartsCrcOk;
180*57696d54SAkhilesh Sanikop       apmFound = orig.apmFound;
181*57696d54SAkhilesh Sanikop       bsdFound = orig.bsdFound;
182*57696d54SAkhilesh Sanikop       sectorAlignment = orig.sectorAlignment;
183*57696d54SAkhilesh Sanikop       beQuiet = orig.beQuiet;
184*57696d54SAkhilesh Sanikop       whichWasUsed = orig.whichWasUsed;
185*57696d54SAkhilesh Sanikop 
186*57696d54SAkhilesh Sanikop       myDisk.OpenForRead(orig.myDisk.GetName());
187*57696d54SAkhilesh Sanikop 
188*57696d54SAkhilesh Sanikop       delete[] partitions;
189*57696d54SAkhilesh Sanikop       partitions = new GPTPart [numParts];
190*57696d54SAkhilesh Sanikop       if (partitions == NULL) {
191*57696d54SAkhilesh Sanikop          cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
192*57696d54SAkhilesh Sanikop               << "Terminating!\n";
193*57696d54SAkhilesh Sanikop          exit(1);
194*57696d54SAkhilesh Sanikop       } // if
195*57696d54SAkhilesh Sanikop       for (i = 0; i < numParts; i++) {
196*57696d54SAkhilesh Sanikop          partitions[i] = orig.partitions[i];
197*57696d54SAkhilesh Sanikop       } // for
198*57696d54SAkhilesh Sanikop    } // if
199*57696d54SAkhilesh Sanikop 
200*57696d54SAkhilesh Sanikop    return *this;
201*57696d54SAkhilesh Sanikop } // GPTData::operator=()
202*57696d54SAkhilesh Sanikop 
203*57696d54SAkhilesh Sanikop /*********************************************************************
204*57696d54SAkhilesh Sanikop  *                                                                   *
205*57696d54SAkhilesh Sanikop  * Begin functions that verify data, or that adjust the verification *
206*57696d54SAkhilesh Sanikop  * information (compute CRCs, rebuild headers)                       *
207*57696d54SAkhilesh Sanikop  *                                                                   *
208*57696d54SAkhilesh Sanikop  *********************************************************************/
209*57696d54SAkhilesh Sanikop 
210*57696d54SAkhilesh Sanikop // Perform detailed verification, reporting on any problems found, but
211*57696d54SAkhilesh Sanikop // do *NOT* recover from these problems. Returns the total number of
212*57696d54SAkhilesh Sanikop // problems identified.
Verify(void)213*57696d54SAkhilesh Sanikop int GPTData::Verify(void) {
214*57696d54SAkhilesh Sanikop    int problems = 0, alignProbs = 0;
215*57696d54SAkhilesh Sanikop    uint32_t i, numSegments, testAlignment = sectorAlignment;
216*57696d54SAkhilesh Sanikop    uint64_t totalFree, largestSegment;
217*57696d54SAkhilesh Sanikop 
218*57696d54SAkhilesh Sanikop    // First, check for CRC errors in the GPT data....
219*57696d54SAkhilesh Sanikop    if (!mainCrcOk) {
220*57696d54SAkhilesh Sanikop       problems++;
221*57696d54SAkhilesh Sanikop       cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
222*57696d54SAkhilesh Sanikop            << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
223*57696d54SAkhilesh Sanikop            << "header ('b' on the recovery & transformation menu). This report may be a false\n"
224*57696d54SAkhilesh Sanikop            << "alarm if you've already corrected other problems.\n";
225*57696d54SAkhilesh Sanikop    } // if
226*57696d54SAkhilesh Sanikop    if (!mainPartsCrcOk) {
227*57696d54SAkhilesh Sanikop       problems++;
228*57696d54SAkhilesh Sanikop       cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
229*57696d54SAkhilesh Sanikop            << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
230*57696d54SAkhilesh Sanikop            << "transformation menu). This report may be a false alarm if you've already\n"
231*57696d54SAkhilesh Sanikop            << "corrected other problems.\n";
232*57696d54SAkhilesh Sanikop    } // if
233*57696d54SAkhilesh Sanikop    if (!secondCrcOk) {
234*57696d54SAkhilesh Sanikop       problems++;
235*57696d54SAkhilesh Sanikop       cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
236*57696d54SAkhilesh Sanikop            << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
237*57696d54SAkhilesh Sanikop            << "header ('d' on the recovery & transformation menu). This report may be a false\n"
238*57696d54SAkhilesh Sanikop            << "alarm if you've already corrected other problems.\n";
239*57696d54SAkhilesh Sanikop    } // if
240*57696d54SAkhilesh Sanikop    if (!secondPartsCrcOk) {
241*57696d54SAkhilesh Sanikop       problems++;
242*57696d54SAkhilesh Sanikop       cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
243*57696d54SAkhilesh Sanikop            << "be corrupt. This program will automatically create a new backup partition\n"
244*57696d54SAkhilesh Sanikop            << "table when you save your partitions.\n";
245*57696d54SAkhilesh Sanikop    } // if
246*57696d54SAkhilesh Sanikop 
247*57696d54SAkhilesh Sanikop    // Now check that the main and backup headers both point to themselves....
248*57696d54SAkhilesh Sanikop    if (mainHeader.currentLBA != 1) {
249*57696d54SAkhilesh Sanikop       problems++;
250*57696d54SAkhilesh Sanikop       cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
251*57696d54SAkhilesh Sanikop            << "is being automatically corrected, but it may be a symptom of more serious\n"
252*57696d54SAkhilesh Sanikop            << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
253*57696d54SAkhilesh Sanikop       mainHeader.currentLBA = 1;
254*57696d54SAkhilesh Sanikop    } // if
255*57696d54SAkhilesh Sanikop    if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
256*57696d54SAkhilesh Sanikop       problems++;
257*57696d54SAkhilesh Sanikop       cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
258*57696d54SAkhilesh Sanikop            << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
259*57696d54SAkhilesh Sanikop            << "option on the experts' menu to adjust the secondary header's and partition\n"
260*57696d54SAkhilesh Sanikop            << "table's locations.\n";
261*57696d54SAkhilesh Sanikop    } // if
262*57696d54SAkhilesh Sanikop 
263*57696d54SAkhilesh Sanikop    // Now check that critical main and backup GPT entries match each other
264*57696d54SAkhilesh Sanikop    if (mainHeader.currentLBA != secondHeader.backupLBA) {
265*57696d54SAkhilesh Sanikop       problems++;
266*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
267*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
268*57696d54SAkhilesh Sanikop            << secondHeader.backupLBA << ").\n";
269*57696d54SAkhilesh Sanikop    } // if
270*57696d54SAkhilesh Sanikop    if (mainHeader.backupLBA != secondHeader.currentLBA) {
271*57696d54SAkhilesh Sanikop       problems++;
272*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
273*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
274*57696d54SAkhilesh Sanikop            << secondHeader.currentLBA << ").\n"
275*57696d54SAkhilesh Sanikop            << "The 'e' option on the experts' menu may fix this problem.\n";
276*57696d54SAkhilesh Sanikop    } // if
277*57696d54SAkhilesh Sanikop    if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
278*57696d54SAkhilesh Sanikop       problems++;
279*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
280*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
281*57696d54SAkhilesh Sanikop            << secondHeader.firstUsableLBA << ")\n";
282*57696d54SAkhilesh Sanikop    } // if
283*57696d54SAkhilesh Sanikop    if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
284*57696d54SAkhilesh Sanikop       problems++;
285*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
286*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
287*57696d54SAkhilesh Sanikop            << secondHeader.lastUsableLBA << ")\n"
288*57696d54SAkhilesh Sanikop            << "The 'e' option on the experts' menu can probably fix this problem.\n";
289*57696d54SAkhilesh Sanikop    } // if
290*57696d54SAkhilesh Sanikop    if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
291*57696d54SAkhilesh Sanikop       problems++;
292*57696d54SAkhilesh Sanikop       cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
293*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's disk GUID ("
294*57696d54SAkhilesh Sanikop            << secondHeader.diskGUID << ")\n"
295*57696d54SAkhilesh Sanikop            << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
296*57696d54SAkhilesh Sanikop            << "select one or the other header.\n";
297*57696d54SAkhilesh Sanikop    } // if
298*57696d54SAkhilesh Sanikop    if (mainHeader.numParts != secondHeader.numParts) {
299*57696d54SAkhilesh Sanikop       problems++;
300*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
301*57696d54SAkhilesh Sanikop            << ") doesn't\nmatch the backup GPT header's number of partitions ("
302*57696d54SAkhilesh Sanikop            << secondHeader.numParts << ")\n"
303*57696d54SAkhilesh Sanikop            << "Resizing the partition table ('s' on the experts' menu) may help.\n";
304*57696d54SAkhilesh Sanikop    } // if
305*57696d54SAkhilesh Sanikop    if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
306*57696d54SAkhilesh Sanikop       problems++;
307*57696d54SAkhilesh Sanikop       cout << "\nProblem: main GPT header's size of partition entries ("
308*57696d54SAkhilesh Sanikop            << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
309*57696d54SAkhilesh Sanikop            << "match the backup GPT header's size of partition entries ("
310*57696d54SAkhilesh Sanikop            << secondHeader.sizeOfPartitionEntries << ")\n"
311*57696d54SAkhilesh Sanikop            << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
312*57696d54SAkhilesh Sanikop            << "select one or the other header.\n";
313*57696d54SAkhilesh Sanikop    } // if
314*57696d54SAkhilesh Sanikop 
315*57696d54SAkhilesh Sanikop    // Now check for a few other miscellaneous problems...
316*57696d54SAkhilesh Sanikop    // Check that the disk size will hold the data...
317*57696d54SAkhilesh Sanikop    if (mainHeader.backupLBA >= diskSize) {
318*57696d54SAkhilesh Sanikop       problems++;
319*57696d54SAkhilesh Sanikop       cout << "\nProblem: Disk is too small to hold all the data!\n"
320*57696d54SAkhilesh Sanikop            << "(Disk size is " << diskSize << " sectors, needs to be "
321*57696d54SAkhilesh Sanikop            << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
322*57696d54SAkhilesh Sanikop            << "The 'e' option on the experts' menu may fix this problem.\n";
323*57696d54SAkhilesh Sanikop    } // if
324*57696d54SAkhilesh Sanikop 
325*57696d54SAkhilesh Sanikop    // Check the main and backup partition tables for overlap with things and unusual gaps
326*57696d54SAkhilesh Sanikop    if (mainHeader.partitionEntriesLBA + GetTableSizeInSectors() > mainHeader.firstUsableLBA) {
327*57696d54SAkhilesh Sanikop        problems++;
328*57696d54SAkhilesh Sanikop        cout << "\nProblem: Main partition table extends past the first usable LBA.\n"
329*57696d54SAkhilesh Sanikop             << "Using 'j' on the experts' menu may enable fixing this problem.\n";
330*57696d54SAkhilesh Sanikop    } // if
331*57696d54SAkhilesh Sanikop    if (mainHeader.partitionEntriesLBA < 2) {
332*57696d54SAkhilesh Sanikop        problems++;
333*57696d54SAkhilesh Sanikop        cout << "\nProblem: Main partition table appears impossibly early on the disk.\n"
334*57696d54SAkhilesh Sanikop             << "Using 'j' on the experts' menu may enable fixing this problem.\n";
335*57696d54SAkhilesh Sanikop    } // if
336*57696d54SAkhilesh Sanikop    if (secondHeader.partitionEntriesLBA + GetTableSizeInSectors() > secondHeader.currentLBA) {
337*57696d54SAkhilesh Sanikop        problems++;
338*57696d54SAkhilesh Sanikop        cout << "\nProblem: The backup partition table overlaps the backup header.\n"
339*57696d54SAkhilesh Sanikop             << "Using 'e' on the experts' menu may fix this problem.\n";
340*57696d54SAkhilesh Sanikop    } // if
341*57696d54SAkhilesh Sanikop    if (mainHeader.partitionEntriesLBA != 2) {
342*57696d54SAkhilesh Sanikop        cout << "\nWarning: There is a gap between the main metadata (sector 1) and the main\n"
343*57696d54SAkhilesh Sanikop             << "partition table (sector " << mainHeader.partitionEntriesLBA
344*57696d54SAkhilesh Sanikop             << "). This is helpful in some exotic configurations,\n"
345*57696d54SAkhilesh Sanikop             << "but is generally ill-advised. Using 'j' on the experts' menu can adjust this\n"
346*57696d54SAkhilesh Sanikop             << "gap.\n";
347*57696d54SAkhilesh Sanikop    } // if
348*57696d54SAkhilesh Sanikop    if (mainHeader.partitionEntriesLBA + GetTableSizeInSectors() != mainHeader.firstUsableLBA) {
349*57696d54SAkhilesh Sanikop        cout << "\nWarning: There is a gap between the main partition table (ending sector "
350*57696d54SAkhilesh Sanikop             << mainHeader.partitionEntriesLBA + GetTableSizeInSectors() - 1 << ")\n"
351*57696d54SAkhilesh Sanikop             << "and the first usable sector (" << mainHeader.firstUsableLBA << "). This is helpful in some exotic configurations,\n"
352*57696d54SAkhilesh Sanikop             << "but is unusual. The util-linux fdisk program often creates disks like this.\n"
353*57696d54SAkhilesh Sanikop             << "Using 'j' on the experts' menu can adjust this gap.\n";
354*57696d54SAkhilesh Sanikop    } // if
355*57696d54SAkhilesh Sanikop 
356*57696d54SAkhilesh Sanikop    if (mainHeader.sizeOfPartitionEntries * mainHeader.numParts < 16384) {
357*57696d54SAkhilesh Sanikop       cout << "\nWarning: The size of the partition table (" << mainHeader.sizeOfPartitionEntries * mainHeader.numParts
358*57696d54SAkhilesh Sanikop            << " bytes) is less than the minimum\n"
359*57696d54SAkhilesh Sanikop            << "required by the GPT specification. Most OSes and tools seem to work fine on\n"
360*57696d54SAkhilesh Sanikop            << "such disks, but this is a violation of the GPT specification and so may cause\n"
361*57696d54SAkhilesh Sanikop            << "problems.\n";
362*57696d54SAkhilesh Sanikop    } // if
363*57696d54SAkhilesh Sanikop 
364*57696d54SAkhilesh Sanikop    if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
365*57696d54SAkhilesh Sanikop       problems++;
366*57696d54SAkhilesh Sanikop       cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
367*57696d54SAkhilesh Sanikop            << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
368*57696d54SAkhilesh Sanikop            << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
369*57696d54SAkhilesh Sanikop            << "The 'e' option on the experts' menu will probably fix this problem\n";
370*57696d54SAkhilesh Sanikop    }
371*57696d54SAkhilesh Sanikop 
372*57696d54SAkhilesh Sanikop    // Check for overlapping partitions....
373*57696d54SAkhilesh Sanikop    problems += FindOverlaps();
374*57696d54SAkhilesh Sanikop 
375*57696d54SAkhilesh Sanikop    // Check for insane partitions (start after end, hugely big, etc.)
376*57696d54SAkhilesh Sanikop    problems += FindInsanePartitions();
377*57696d54SAkhilesh Sanikop 
378*57696d54SAkhilesh Sanikop    // Check for mismatched MBR and GPT partitions...
379*57696d54SAkhilesh Sanikop    problems += FindHybridMismatches();
380*57696d54SAkhilesh Sanikop 
381*57696d54SAkhilesh Sanikop    // Check for MBR-specific problems....
382*57696d54SAkhilesh Sanikop    problems += VerifyMBR();
383*57696d54SAkhilesh Sanikop 
384*57696d54SAkhilesh Sanikop    // Check for a 0xEE protective partition that's marked as active....
385*57696d54SAkhilesh Sanikop    if (protectiveMBR.IsEEActive()) {
386*57696d54SAkhilesh Sanikop       cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
387*57696d54SAkhilesh Sanikop            << "technically a violation of the GPT specification, and can cause some EFIs to\n"
388*57696d54SAkhilesh Sanikop            << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
389*57696d54SAkhilesh Sanikop            << "computers. You can clear this flag by creating a fresh protective MBR using\n"
390*57696d54SAkhilesh Sanikop            << "the 'n' option on the experts' menu.\n";
391*57696d54SAkhilesh Sanikop    }
392*57696d54SAkhilesh Sanikop 
393*57696d54SAkhilesh Sanikop    // Verify that partitions don't run into GPT data areas....
394*57696d54SAkhilesh Sanikop    problems += CheckGPTSize();
395*57696d54SAkhilesh Sanikop 
396*57696d54SAkhilesh Sanikop    if (!protectiveMBR.DoTheyFit()) {
397*57696d54SAkhilesh Sanikop       cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
398*57696d54SAkhilesh Sanikop            << "fresh protective or hybrid MBR is recommended.\n";
399*57696d54SAkhilesh Sanikop       problems++;
400*57696d54SAkhilesh Sanikop    }
401*57696d54SAkhilesh Sanikop 
402*57696d54SAkhilesh Sanikop    // Check that partitions are aligned on proper boundaries (for WD Advanced
403*57696d54SAkhilesh Sanikop    // Format and similar disks)....
404*57696d54SAkhilesh Sanikop    if ((physBlockSize != 0) && (blockSize != 0))
405*57696d54SAkhilesh Sanikop       testAlignment = physBlockSize / blockSize;
406*57696d54SAkhilesh Sanikop    testAlignment = max(testAlignment, sectorAlignment);
407*57696d54SAkhilesh Sanikop    if (testAlignment == 0) // Should not happen; just being paranoid.
408*57696d54SAkhilesh Sanikop       testAlignment = sectorAlignment;
409*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
410*57696d54SAkhilesh Sanikop       if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % testAlignment) != 0) {
411*57696d54SAkhilesh Sanikop          cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
412*57696d54SAkhilesh Sanikop               << testAlignment << "-sector boundary. This may\nresult "
413*57696d54SAkhilesh Sanikop               << "in degraded performance on some modern (2009 and later) hard disks.\n";
414*57696d54SAkhilesh Sanikop          alignProbs++;
415*57696d54SAkhilesh Sanikop       } // if
416*57696d54SAkhilesh Sanikop       if ((partitions[i].IsUsed()) && ((partitions[i].GetLastLBA() + 1) % testAlignment) != 0) {
417*57696d54SAkhilesh Sanikop          cout << "\nCaution: Partition " << i + 1 << " doesn't end on a "
418*57696d54SAkhilesh Sanikop               << testAlignment << "-sector boundary. This may\nresult "
419*57696d54SAkhilesh Sanikop               << "in problems with some disk encryption tools.\n";
420*57696d54SAkhilesh Sanikop       } // if
421*57696d54SAkhilesh Sanikop    } // for
422*57696d54SAkhilesh Sanikop    if (alignProbs > 0)
423*57696d54SAkhilesh Sanikop       cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
424*57696d54SAkhilesh Sanikop       << "for information on disk alignment.\n";
425*57696d54SAkhilesh Sanikop 
426*57696d54SAkhilesh Sanikop    // Now compute available space, but only if no problems found, since
427*57696d54SAkhilesh Sanikop    // problems could affect the results
428*57696d54SAkhilesh Sanikop    if (problems == 0) {
429*57696d54SAkhilesh Sanikop       totalFree = FindFreeBlocks(&numSegments, &largestSegment);
430*57696d54SAkhilesh Sanikop       cout << "\nNo problems found. " << totalFree << " free sectors ("
431*57696d54SAkhilesh Sanikop            << BytesToIeee(totalFree, blockSize) << ") available in "
432*57696d54SAkhilesh Sanikop            << numSegments << "\nsegments, the largest of which is "
433*57696d54SAkhilesh Sanikop            << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
434*57696d54SAkhilesh Sanikop            << ") in size.\n";
435*57696d54SAkhilesh Sanikop    } else {
436*57696d54SAkhilesh Sanikop       cout << "\nIdentified " << problems << " problems!\n";
437*57696d54SAkhilesh Sanikop    } // if/else
438*57696d54SAkhilesh Sanikop 
439*57696d54SAkhilesh Sanikop    return (problems);
440*57696d54SAkhilesh Sanikop } // GPTData::Verify()
441*57696d54SAkhilesh Sanikop 
442*57696d54SAkhilesh Sanikop // Checks to see if the GPT tables overrun existing partitions; if they
443*57696d54SAkhilesh Sanikop // do, issues a warning but takes no action. Returns number of problems
444*57696d54SAkhilesh Sanikop // detected (0 if OK, 1 to 2 if problems).
CheckGPTSize(void)445*57696d54SAkhilesh Sanikop int GPTData::CheckGPTSize(void) {
446*57696d54SAkhilesh Sanikop    uint64_t overlap, firstUsedBlock, lastUsedBlock;
447*57696d54SAkhilesh Sanikop    uint32_t i;
448*57696d54SAkhilesh Sanikop    int numProbs = 0;
449*57696d54SAkhilesh Sanikop 
450*57696d54SAkhilesh Sanikop    // first, locate the first & last used blocks
451*57696d54SAkhilesh Sanikop    firstUsedBlock = UINT64_MAX;
452*57696d54SAkhilesh Sanikop    lastUsedBlock = 0;
453*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
454*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed()) {
455*57696d54SAkhilesh Sanikop          if (partitions[i].GetFirstLBA() < firstUsedBlock)
456*57696d54SAkhilesh Sanikop             firstUsedBlock = partitions[i].GetFirstLBA();
457*57696d54SAkhilesh Sanikop          if (partitions[i].GetLastLBA() > lastUsedBlock) {
458*57696d54SAkhilesh Sanikop             lastUsedBlock = partitions[i].GetLastLBA();
459*57696d54SAkhilesh Sanikop          } // if
460*57696d54SAkhilesh Sanikop       } // if
461*57696d54SAkhilesh Sanikop    } // for
462*57696d54SAkhilesh Sanikop 
463*57696d54SAkhilesh Sanikop    // If the disk size is 0 (the default), then it means that various
464*57696d54SAkhilesh Sanikop    // variables aren't yet set, so the below tests will be useless;
465*57696d54SAkhilesh Sanikop    // therefore we should skip everything
466*57696d54SAkhilesh Sanikop    if (diskSize != 0) {
467*57696d54SAkhilesh Sanikop       if (mainHeader.firstUsableLBA > firstUsedBlock) {
468*57696d54SAkhilesh Sanikop          overlap = mainHeader.firstUsableLBA - firstUsedBlock;
469*57696d54SAkhilesh Sanikop          cout << "Warning! Main partition table overlaps the first partition by "
470*57696d54SAkhilesh Sanikop               << overlap << " blocks!\n";
471*57696d54SAkhilesh Sanikop          if (firstUsedBlock > 2) {
472*57696d54SAkhilesh Sanikop             cout << "Try reducing the partition table size by " << overlap * 4
473*57696d54SAkhilesh Sanikop                  << " entries.\n(Use the 's' item on the experts' menu.)\n";
474*57696d54SAkhilesh Sanikop          } else {
475*57696d54SAkhilesh Sanikop             cout << "You will need to delete this partition or resize it in another utility.\n";
476*57696d54SAkhilesh Sanikop          } // if/else
477*57696d54SAkhilesh Sanikop          numProbs++;
478*57696d54SAkhilesh Sanikop       } // Problem at start of disk
479*57696d54SAkhilesh Sanikop       if (mainHeader.lastUsableLBA < lastUsedBlock) {
480*57696d54SAkhilesh Sanikop          overlap = lastUsedBlock - mainHeader.lastUsableLBA;
481*57696d54SAkhilesh Sanikop          cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
482*57696d54SAkhilesh Sanikop               << overlap << " blocks!\n";
483*57696d54SAkhilesh Sanikop          if (lastUsedBlock > (diskSize - 2)) {
484*57696d54SAkhilesh Sanikop             cout << "You will need to delete this partition or resize it in another utility.\n";
485*57696d54SAkhilesh Sanikop          } else {
486*57696d54SAkhilesh Sanikop             cout << "Try reducing the partition table size by " << overlap * 4
487*57696d54SAkhilesh Sanikop                  << " entries.\n(Use the 's' item on the experts' menu.)\n";
488*57696d54SAkhilesh Sanikop          } // if/else
489*57696d54SAkhilesh Sanikop          numProbs++;
490*57696d54SAkhilesh Sanikop       } // Problem at end of disk
491*57696d54SAkhilesh Sanikop    } // if (diskSize != 0)
492*57696d54SAkhilesh Sanikop    return numProbs;
493*57696d54SAkhilesh Sanikop } // GPTData::CheckGPTSize()
494*57696d54SAkhilesh Sanikop 
495*57696d54SAkhilesh Sanikop // Check the validity of the GPT header. Returns 1 if the main header
496*57696d54SAkhilesh Sanikop // is valid, 2 if the backup header is valid, 3 if both are valid, and
497*57696d54SAkhilesh Sanikop // 0 if neither is valid. Note that this function checks the GPT signature,
498*57696d54SAkhilesh Sanikop // revision value, and CRCs in both headers.
CheckHeaderValidity(void)499*57696d54SAkhilesh Sanikop int GPTData::CheckHeaderValidity(void) {
500*57696d54SAkhilesh Sanikop    int valid = 3;
501*57696d54SAkhilesh Sanikop 
502*57696d54SAkhilesh Sanikop    cout.setf(ios::uppercase);
503*57696d54SAkhilesh Sanikop    cout.fill('0');
504*57696d54SAkhilesh Sanikop 
505*57696d54SAkhilesh Sanikop    // Note: failed GPT signature checks produce no error message because
506*57696d54SAkhilesh Sanikop    // a message is displayed in the ReversePartitionBytes() function
507*57696d54SAkhilesh Sanikop    if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
508*57696d54SAkhilesh Sanikop       valid -= 1;
509*57696d54SAkhilesh Sanikop    } else if ((mainHeader.revision != 0x00010000) && valid) {
510*57696d54SAkhilesh Sanikop       valid -= 1;
511*57696d54SAkhilesh Sanikop       cout << "Unsupported GPT version in main header; read 0x";
512*57696d54SAkhilesh Sanikop       cout.width(8);
513*57696d54SAkhilesh Sanikop       cout << hex << mainHeader.revision << ", should be\n0x";
514*57696d54SAkhilesh Sanikop       cout.width(8);
515*57696d54SAkhilesh Sanikop       cout << UINT32_C(0x00010000) << dec << "\n";
516*57696d54SAkhilesh Sanikop    } // if/else/if
517*57696d54SAkhilesh Sanikop 
518*57696d54SAkhilesh Sanikop    if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
519*57696d54SAkhilesh Sanikop       valid -= 2;
520*57696d54SAkhilesh Sanikop    } else if ((secondHeader.revision != 0x00010000) && valid) {
521*57696d54SAkhilesh Sanikop       valid -= 2;
522*57696d54SAkhilesh Sanikop       cout << "Unsupported GPT version in backup header; read 0x";
523*57696d54SAkhilesh Sanikop       cout.width(8);
524*57696d54SAkhilesh Sanikop       cout << hex << secondHeader.revision << ", should be\n0x";
525*57696d54SAkhilesh Sanikop       cout.width(8);
526*57696d54SAkhilesh Sanikop       cout << UINT32_C(0x00010000) << dec << "\n";
527*57696d54SAkhilesh Sanikop    } // if/else/if
528*57696d54SAkhilesh Sanikop 
529*57696d54SAkhilesh Sanikop    // Check for an Apple disk signature
530*57696d54SAkhilesh Sanikop    if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
531*57696d54SAkhilesh Sanikop         (mainHeader.signature << 32) == APM_SIGNATURE2) {
532*57696d54SAkhilesh Sanikop       apmFound = 1; // Will display warning message later
533*57696d54SAkhilesh Sanikop    } // if
534*57696d54SAkhilesh Sanikop    cout.fill(' ');
535*57696d54SAkhilesh Sanikop 
536*57696d54SAkhilesh Sanikop    return valid;
537*57696d54SAkhilesh Sanikop } // GPTData::CheckHeaderValidity()
538*57696d54SAkhilesh Sanikop 
539*57696d54SAkhilesh Sanikop // Check the header CRC to see if it's OK...
540*57696d54SAkhilesh Sanikop // Note: Must be called with header in platform-ordered byte order.
541*57696d54SAkhilesh Sanikop // Returns 1 if header's computed CRC matches the stored value, 0 if the
542*57696d54SAkhilesh Sanikop // computed and stored values don't match
CheckHeaderCRC(struct GPTHeader * header,int warn)543*57696d54SAkhilesh Sanikop int GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
544*57696d54SAkhilesh Sanikop    uint32_t oldCRC, newCRC, hSize;
545*57696d54SAkhilesh Sanikop    uint8_t *temp;
546*57696d54SAkhilesh Sanikop 
547*57696d54SAkhilesh Sanikop    // Back up old header CRC and then blank it, since it must be 0 for
548*57696d54SAkhilesh Sanikop    // computation to be valid
549*57696d54SAkhilesh Sanikop    oldCRC = header->headerCRC;
550*57696d54SAkhilesh Sanikop    header->headerCRC = UINT32_C(0);
551*57696d54SAkhilesh Sanikop 
552*57696d54SAkhilesh Sanikop    hSize = header->headerSize;
553*57696d54SAkhilesh Sanikop 
554*57696d54SAkhilesh Sanikop    if (IsLittleEndian() == 0)
555*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(header);
556*57696d54SAkhilesh Sanikop 
557*57696d54SAkhilesh Sanikop    if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
558*57696d54SAkhilesh Sanikop       if (warn) {
559*57696d54SAkhilesh Sanikop          cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
560*57696d54SAkhilesh Sanikop          cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
561*57696d54SAkhilesh Sanikop       } // if
562*57696d54SAkhilesh Sanikop       hSize = HEADER_SIZE;
563*57696d54SAkhilesh Sanikop    } else if ((hSize > sizeof(GPTHeader)) && warn) {
564*57696d54SAkhilesh Sanikop       cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
565*57696d54SAkhilesh Sanikop       cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
566*57696d54SAkhilesh Sanikop            << "which may result in a CRC false alarm.\n";
567*57696d54SAkhilesh Sanikop    } // if/elseif
568*57696d54SAkhilesh Sanikop    temp = new uint8_t[hSize];
569*57696d54SAkhilesh Sanikop    if (temp != NULL) {
570*57696d54SAkhilesh Sanikop       memset(temp, 0, hSize);
571*57696d54SAkhilesh Sanikop       if (hSize < sizeof(GPTHeader))
572*57696d54SAkhilesh Sanikop          memcpy(temp, header, hSize);
573*57696d54SAkhilesh Sanikop       else
574*57696d54SAkhilesh Sanikop          memcpy(temp, header, sizeof(GPTHeader));
575*57696d54SAkhilesh Sanikop 
576*57696d54SAkhilesh Sanikop       newCRC = chksum_crc32((unsigned char*) temp, hSize);
577*57696d54SAkhilesh Sanikop       delete[] temp;
578*57696d54SAkhilesh Sanikop    } else {
579*57696d54SAkhilesh Sanikop       cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
580*57696d54SAkhilesh Sanikop       exit(1);
581*57696d54SAkhilesh Sanikop    }
582*57696d54SAkhilesh Sanikop    if (IsLittleEndian() == 0)
583*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(header);
584*57696d54SAkhilesh Sanikop    header->headerCRC = oldCRC;
585*57696d54SAkhilesh Sanikop    return (oldCRC == newCRC);
586*57696d54SAkhilesh Sanikop } // GPTData::CheckHeaderCRC()
587*57696d54SAkhilesh Sanikop 
588*57696d54SAkhilesh Sanikop // Recompute all the CRCs. Must be called before saving if any changes have
589*57696d54SAkhilesh Sanikop // been made. Must be called on platform-ordered data (this function reverses
590*57696d54SAkhilesh Sanikop // byte order and then undoes that reversal.)
RecomputeCRCs(void)591*57696d54SAkhilesh Sanikop void GPTData::RecomputeCRCs(void) {
592*57696d54SAkhilesh Sanikop    uint32_t crc, hSize;
593*57696d54SAkhilesh Sanikop    int littleEndian;
594*57696d54SAkhilesh Sanikop 
595*57696d54SAkhilesh Sanikop    // If the header size is bigger than the GPT header data structure, reset it;
596*57696d54SAkhilesh Sanikop    // otherwise, set both header sizes to whatever the main one is....
597*57696d54SAkhilesh Sanikop    if (mainHeader.headerSize > sizeof(GPTHeader))
598*57696d54SAkhilesh Sanikop       hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
599*57696d54SAkhilesh Sanikop    else
600*57696d54SAkhilesh Sanikop       hSize = secondHeader.headerSize = mainHeader.headerSize;
601*57696d54SAkhilesh Sanikop 
602*57696d54SAkhilesh Sanikop    if ((littleEndian = IsLittleEndian()) == 0) {
603*57696d54SAkhilesh Sanikop       ReversePartitionBytes();
604*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(&mainHeader);
605*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(&secondHeader);
606*57696d54SAkhilesh Sanikop    } // if
607*57696d54SAkhilesh Sanikop 
608*57696d54SAkhilesh Sanikop    // Compute CRC of partition tables & store in main and secondary headers
609*57696d54SAkhilesh Sanikop    crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
610*57696d54SAkhilesh Sanikop    mainHeader.partitionEntriesCRC = crc;
611*57696d54SAkhilesh Sanikop    secondHeader.partitionEntriesCRC = crc;
612*57696d54SAkhilesh Sanikop    if (littleEndian == 0) {
613*57696d54SAkhilesh Sanikop       ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
614*57696d54SAkhilesh Sanikop       ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
615*57696d54SAkhilesh Sanikop    } // if
616*57696d54SAkhilesh Sanikop 
617*57696d54SAkhilesh Sanikop    // Zero out GPT headers' own CRCs (required for correct computation)
618*57696d54SAkhilesh Sanikop    mainHeader.headerCRC = 0;
619*57696d54SAkhilesh Sanikop    secondHeader.headerCRC = 0;
620*57696d54SAkhilesh Sanikop 
621*57696d54SAkhilesh Sanikop    crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
622*57696d54SAkhilesh Sanikop    if (littleEndian == 0)
623*57696d54SAkhilesh Sanikop       ReverseBytes(&crc, 4);
624*57696d54SAkhilesh Sanikop    mainHeader.headerCRC = crc;
625*57696d54SAkhilesh Sanikop    crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
626*57696d54SAkhilesh Sanikop    if (littleEndian == 0)
627*57696d54SAkhilesh Sanikop       ReverseBytes(&crc, 4);
628*57696d54SAkhilesh Sanikop    secondHeader.headerCRC = crc;
629*57696d54SAkhilesh Sanikop 
630*57696d54SAkhilesh Sanikop    if (littleEndian == 0) {
631*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(&mainHeader);
632*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(&secondHeader);
633*57696d54SAkhilesh Sanikop       ReversePartitionBytes();
634*57696d54SAkhilesh Sanikop    } // if
635*57696d54SAkhilesh Sanikop } // GPTData::RecomputeCRCs()
636*57696d54SAkhilesh Sanikop 
637*57696d54SAkhilesh Sanikop // Rebuild the main GPT header, using the secondary header as a model.
638*57696d54SAkhilesh Sanikop // Typically called when the main header has been found to be corrupt.
RebuildMainHeader(void)639*57696d54SAkhilesh Sanikop void GPTData::RebuildMainHeader(void) {
640*57696d54SAkhilesh Sanikop    mainHeader.signature = GPT_SIGNATURE;
641*57696d54SAkhilesh Sanikop    mainHeader.revision = secondHeader.revision;
642*57696d54SAkhilesh Sanikop    mainHeader.headerSize = secondHeader.headerSize;
643*57696d54SAkhilesh Sanikop    mainHeader.headerCRC = UINT32_C(0);
644*57696d54SAkhilesh Sanikop    mainHeader.reserved = secondHeader.reserved;
645*57696d54SAkhilesh Sanikop    mainHeader.currentLBA = secondHeader.backupLBA;
646*57696d54SAkhilesh Sanikop    mainHeader.backupLBA = secondHeader.currentLBA;
647*57696d54SAkhilesh Sanikop    mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
648*57696d54SAkhilesh Sanikop    mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
649*57696d54SAkhilesh Sanikop    mainHeader.diskGUID = secondHeader.diskGUID;
650*57696d54SAkhilesh Sanikop    mainHeader.numParts = secondHeader.numParts;
651*57696d54SAkhilesh Sanikop    mainHeader.partitionEntriesLBA = secondHeader.firstUsableLBA - GetTableSizeInSectors();
652*57696d54SAkhilesh Sanikop    mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
653*57696d54SAkhilesh Sanikop    mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
654*57696d54SAkhilesh Sanikop    memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
655*57696d54SAkhilesh Sanikop    mainCrcOk = secondCrcOk;
656*57696d54SAkhilesh Sanikop    SetGPTSize(mainHeader.numParts, 0);
657*57696d54SAkhilesh Sanikop } // GPTData::RebuildMainHeader()
658*57696d54SAkhilesh Sanikop 
659*57696d54SAkhilesh Sanikop // Rebuild the secondary GPT header, using the main header as a model.
RebuildSecondHeader(void)660*57696d54SAkhilesh Sanikop void GPTData::RebuildSecondHeader(void) {
661*57696d54SAkhilesh Sanikop    secondHeader.signature = GPT_SIGNATURE;
662*57696d54SAkhilesh Sanikop    secondHeader.revision = mainHeader.revision;
663*57696d54SAkhilesh Sanikop    secondHeader.headerSize = mainHeader.headerSize;
664*57696d54SAkhilesh Sanikop    secondHeader.headerCRC = UINT32_C(0);
665*57696d54SAkhilesh Sanikop    secondHeader.reserved = mainHeader.reserved;
666*57696d54SAkhilesh Sanikop    secondHeader.currentLBA = mainHeader.backupLBA;
667*57696d54SAkhilesh Sanikop    secondHeader.backupLBA = mainHeader.currentLBA;
668*57696d54SAkhilesh Sanikop    secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
669*57696d54SAkhilesh Sanikop    secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
670*57696d54SAkhilesh Sanikop    secondHeader.diskGUID = mainHeader.diskGUID;
671*57696d54SAkhilesh Sanikop    secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
672*57696d54SAkhilesh Sanikop    secondHeader.numParts = mainHeader.numParts;
673*57696d54SAkhilesh Sanikop    secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
674*57696d54SAkhilesh Sanikop    secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
675*57696d54SAkhilesh Sanikop    memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
676*57696d54SAkhilesh Sanikop    secondCrcOk = mainCrcOk;
677*57696d54SAkhilesh Sanikop    SetGPTSize(secondHeader.numParts, 0);
678*57696d54SAkhilesh Sanikop } // GPTData::RebuildSecondHeader()
679*57696d54SAkhilesh Sanikop 
680*57696d54SAkhilesh Sanikop // Search for hybrid MBR entries that have no corresponding GPT partition.
681*57696d54SAkhilesh Sanikop // Returns number of such mismatches found
FindHybridMismatches(void)682*57696d54SAkhilesh Sanikop int GPTData::FindHybridMismatches(void) {
683*57696d54SAkhilesh Sanikop    int i, found, numFound = 0;
684*57696d54SAkhilesh Sanikop    uint32_t j;
685*57696d54SAkhilesh Sanikop    uint64_t mbrFirst, mbrLast;
686*57696d54SAkhilesh Sanikop 
687*57696d54SAkhilesh Sanikop    for (i = 0; i < 4; i++) {
688*57696d54SAkhilesh Sanikop       if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
689*57696d54SAkhilesh Sanikop          j = 0;
690*57696d54SAkhilesh Sanikop          found = 0;
691*57696d54SAkhilesh Sanikop          mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
692*57696d54SAkhilesh Sanikop          mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
693*57696d54SAkhilesh Sanikop          do {
694*57696d54SAkhilesh Sanikop             if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
695*57696d54SAkhilesh Sanikop                 (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
696*57696d54SAkhilesh Sanikop                found = 1;
697*57696d54SAkhilesh Sanikop             j++;
698*57696d54SAkhilesh Sanikop          } while ((!found) && (j < numParts));
699*57696d54SAkhilesh Sanikop          if (!found) {
700*57696d54SAkhilesh Sanikop             numFound++;
701*57696d54SAkhilesh Sanikop             cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
702*57696d54SAkhilesh Sanikop                  << i + 1 << ", of type 0x";
703*57696d54SAkhilesh Sanikop             cout.fill('0');
704*57696d54SAkhilesh Sanikop             cout.setf(ios::uppercase);
705*57696d54SAkhilesh Sanikop             cout.width(2);
706*57696d54SAkhilesh Sanikop             cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
707*57696d54SAkhilesh Sanikop                  << "has no corresponding GPT partition! You may continue, but this condition\n"
708*57696d54SAkhilesh Sanikop                  << "might cause data loss in the future!\a\n" << dec;
709*57696d54SAkhilesh Sanikop             cout.fill(' ');
710*57696d54SAkhilesh Sanikop          } // if
711*57696d54SAkhilesh Sanikop       } // if
712*57696d54SAkhilesh Sanikop    } // for
713*57696d54SAkhilesh Sanikop    return numFound;
714*57696d54SAkhilesh Sanikop } // GPTData::FindHybridMismatches
715*57696d54SAkhilesh Sanikop 
716*57696d54SAkhilesh Sanikop // Find overlapping partitions and warn user about them. Returns number of
717*57696d54SAkhilesh Sanikop // overlapping partitions.
718*57696d54SAkhilesh Sanikop // Returns number of overlapping segments found.
FindOverlaps(void)719*57696d54SAkhilesh Sanikop int GPTData::FindOverlaps(void) {
720*57696d54SAkhilesh Sanikop    int problems = 0;
721*57696d54SAkhilesh Sanikop    uint32_t i, j;
722*57696d54SAkhilesh Sanikop 
723*57696d54SAkhilesh Sanikop    for (i = 1; i < numParts; i++) {
724*57696d54SAkhilesh Sanikop       for (j = 0; j < i; j++) {
725*57696d54SAkhilesh Sanikop          if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
726*57696d54SAkhilesh Sanikop              (partitions[i].DoTheyOverlap(partitions[j]))) {
727*57696d54SAkhilesh Sanikop             problems++;
728*57696d54SAkhilesh Sanikop             cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
729*57696d54SAkhilesh Sanikop             cout << "  Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
730*57696d54SAkhilesh Sanikop                  << " to " << partitions[i].GetLastLBA() << "\n";
731*57696d54SAkhilesh Sanikop             cout << "  Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
732*57696d54SAkhilesh Sanikop                  << " to " << partitions[j].GetLastLBA() << "\n";
733*57696d54SAkhilesh Sanikop          } // if
734*57696d54SAkhilesh Sanikop       } // for j...
735*57696d54SAkhilesh Sanikop    } // for i...
736*57696d54SAkhilesh Sanikop    return problems;
737*57696d54SAkhilesh Sanikop } // GPTData::FindOverlaps()
738*57696d54SAkhilesh Sanikop 
739*57696d54SAkhilesh Sanikop // Find partitions that are insane -- they start after they end or are too
740*57696d54SAkhilesh Sanikop // big for the disk. (The latter should duplicate detection of overlaps
741*57696d54SAkhilesh Sanikop // with GPT backup data structures, but better to err on the side of
742*57696d54SAkhilesh Sanikop // redundant tests than to miss something....)
743*57696d54SAkhilesh Sanikop // Returns number of problems found.
FindInsanePartitions(void)744*57696d54SAkhilesh Sanikop int GPTData::FindInsanePartitions(void) {
745*57696d54SAkhilesh Sanikop    uint32_t i;
746*57696d54SAkhilesh Sanikop    int problems = 0;
747*57696d54SAkhilesh Sanikop 
748*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
749*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed()) {
750*57696d54SAkhilesh Sanikop          if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
751*57696d54SAkhilesh Sanikop             problems++;
752*57696d54SAkhilesh Sanikop             cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
753*57696d54SAkhilesh Sanikop          } // if
754*57696d54SAkhilesh Sanikop          if (partitions[i].GetLastLBA() >= diskSize) {
755*57696d54SAkhilesh Sanikop             problems++;
756*57696d54SAkhilesh Sanikop             cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
757*57696d54SAkhilesh Sanikop          } // if
758*57696d54SAkhilesh Sanikop       } // if
759*57696d54SAkhilesh Sanikop    } // for
760*57696d54SAkhilesh Sanikop    return problems;
761*57696d54SAkhilesh Sanikop } // GPTData::FindInsanePartitions(void)
762*57696d54SAkhilesh Sanikop 
763*57696d54SAkhilesh Sanikop 
764*57696d54SAkhilesh Sanikop /******************************************************************
765*57696d54SAkhilesh Sanikop  *                                                                *
766*57696d54SAkhilesh Sanikop  * Begin functions that load data from disk or save data to disk. *
767*57696d54SAkhilesh Sanikop  *                                                                *
768*57696d54SAkhilesh Sanikop  ******************************************************************/
769*57696d54SAkhilesh Sanikop 
770*57696d54SAkhilesh Sanikop // Change the filename associated with the GPT. Used for duplicating
771*57696d54SAkhilesh Sanikop // the partition table to a new disk and saving backups.
772*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure.
SetDisk(const string & deviceFilename)773*57696d54SAkhilesh Sanikop int GPTData::SetDisk(const string & deviceFilename) {
774*57696d54SAkhilesh Sanikop    int err, allOK = 1;
775*57696d54SAkhilesh Sanikop 
776*57696d54SAkhilesh Sanikop    device = deviceFilename;
777*57696d54SAkhilesh Sanikop    if (allOK && myDisk.OpenForRead(deviceFilename)) {
778*57696d54SAkhilesh Sanikop       // store disk information....
779*57696d54SAkhilesh Sanikop       diskSize = myDisk.DiskSize(&err);
780*57696d54SAkhilesh Sanikop       blockSize = (uint32_t) myDisk.GetBlockSize();
781*57696d54SAkhilesh Sanikop       physBlockSize = (uint32_t) myDisk.GetPhysBlockSize();
782*57696d54SAkhilesh Sanikop    } // if
783*57696d54SAkhilesh Sanikop    protectiveMBR.SetDisk(&myDisk);
784*57696d54SAkhilesh Sanikop    protectiveMBR.SetDiskSize(diskSize);
785*57696d54SAkhilesh Sanikop    protectiveMBR.SetBlockSize(blockSize);
786*57696d54SAkhilesh Sanikop    return allOK;
787*57696d54SAkhilesh Sanikop } // GPTData::SetDisk()
788*57696d54SAkhilesh Sanikop 
SetDisk(const DiskIO & disk)789*57696d54SAkhilesh Sanikop int GPTData::SetDisk(const DiskIO & disk) {
790*57696d54SAkhilesh Sanikop    myDisk = disk;
791*57696d54SAkhilesh Sanikop    return 1;
792*57696d54SAkhilesh Sanikop } // GPTData::SetDisk()
793*57696d54SAkhilesh Sanikop 
794*57696d54SAkhilesh Sanikop // Scan for partition data. This function loads the MBR data (regular MBR or
795*57696d54SAkhilesh Sanikop // protective MBR) and loads BSD disklabel data (which is probably invalid).
796*57696d54SAkhilesh Sanikop // It also looks for APM data, forces a load of GPT data, and summarizes
797*57696d54SAkhilesh Sanikop // the results.
PartitionScan(void)798*57696d54SAkhilesh Sanikop void GPTData::PartitionScan(void) {
799*57696d54SAkhilesh Sanikop    BSDData bsdDisklabel;
800*57696d54SAkhilesh Sanikop 
801*57696d54SAkhilesh Sanikop    // Read the MBR & check for BSD disklabel
802*57696d54SAkhilesh Sanikop    protectiveMBR.ReadMBRData(&myDisk);
803*57696d54SAkhilesh Sanikop    bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
804*57696d54SAkhilesh Sanikop 
805*57696d54SAkhilesh Sanikop    // Load the GPT data, whether or not it's valid
806*57696d54SAkhilesh Sanikop    ForceLoadGPTData();
807*57696d54SAkhilesh Sanikop 
808*57696d54SAkhilesh Sanikop    // Some tools create a 0xEE partition that's too big. If this is detected,
809*57696d54SAkhilesh Sanikop    // normalize it....
810*57696d54SAkhilesh Sanikop    if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
811*57696d54SAkhilesh Sanikop       if (!beQuiet) {
812*57696d54SAkhilesh Sanikop          cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
813*57696d54SAkhilesh Sanikop       } // if
814*57696d54SAkhilesh Sanikop       protectiveMBR.MakeProtectiveMBR();
815*57696d54SAkhilesh Sanikop    } // if
816*57696d54SAkhilesh Sanikop 
817*57696d54SAkhilesh Sanikop    if (!beQuiet) {
818*57696d54SAkhilesh Sanikop       cout << "Partition table scan:\n";
819*57696d54SAkhilesh Sanikop       protectiveMBR.ShowState();
820*57696d54SAkhilesh Sanikop       bsdDisklabel.ShowState();
821*57696d54SAkhilesh Sanikop       ShowAPMState(); // Show whether there's an Apple Partition Map present
822*57696d54SAkhilesh Sanikop       ShowGPTState(); // Show GPT status
823*57696d54SAkhilesh Sanikop       cout << "\n";
824*57696d54SAkhilesh Sanikop    } // if
825*57696d54SAkhilesh Sanikop 
826*57696d54SAkhilesh Sanikop    if (apmFound) {
827*57696d54SAkhilesh Sanikop       cout << "\n*******************************************************************\n"
828*57696d54SAkhilesh Sanikop            << "This disk appears to contain an Apple-format (APM) partition table!\n";
829*57696d54SAkhilesh Sanikop       if (!justLooking) {
830*57696d54SAkhilesh Sanikop          cout << "It will be destroyed if you continue!\n";
831*57696d54SAkhilesh Sanikop       } // if
832*57696d54SAkhilesh Sanikop       cout << "*******************************************************************\n\n\a";
833*57696d54SAkhilesh Sanikop    } // if
834*57696d54SAkhilesh Sanikop } // GPTData::PartitionScan()
835*57696d54SAkhilesh Sanikop 
836*57696d54SAkhilesh Sanikop // Read GPT data from a disk.
LoadPartitions(const string & deviceFilename)837*57696d54SAkhilesh Sanikop int GPTData::LoadPartitions(const string & deviceFilename) {
838*57696d54SAkhilesh Sanikop    BSDData bsdDisklabel;
839*57696d54SAkhilesh Sanikop    int err, allOK = 1;
840*57696d54SAkhilesh Sanikop    MBRValidity mbrState;
841*57696d54SAkhilesh Sanikop 
842*57696d54SAkhilesh Sanikop    if (myDisk.OpenForRead(deviceFilename)) {
843*57696d54SAkhilesh Sanikop       err = myDisk.OpenForWrite(deviceFilename);
844*57696d54SAkhilesh Sanikop       if ((err == 0) && (!justLooking)) {
845*57696d54SAkhilesh Sanikop          cout << "\aNOTE: Write test failed with error number " << errno
846*57696d54SAkhilesh Sanikop               << ". It will be impossible to save\nchanges to this disk's partition table!\n";
847*57696d54SAkhilesh Sanikop #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
848*57696d54SAkhilesh Sanikop          cout << "You may be able to enable writes by exiting this program, typing\n"
849*57696d54SAkhilesh Sanikop               << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
850*57696d54SAkhilesh Sanikop               << "program.\n";
851*57696d54SAkhilesh Sanikop #endif
852*57696d54SAkhilesh Sanikop #if defined (__APPLE__)
853*57696d54SAkhilesh Sanikop          cout << "You may need to deactivate System Integrity Protection to use this program. See\n"
854*57696d54SAkhilesh Sanikop               << "https://www.quora.com/How-do-I-turn-off-the-rootless-in-OS-X-El-Capitan-10-11\n"
855*57696d54SAkhilesh Sanikop               << "for more information.\n";
856*57696d54SAkhilesh Sanikop #endif
857*57696d54SAkhilesh Sanikop               cout << "\n";
858*57696d54SAkhilesh Sanikop       } // if
859*57696d54SAkhilesh Sanikop       myDisk.Close(); // Close and re-open read-only in case of bugs
860*57696d54SAkhilesh Sanikop    } else allOK = 0; // if
861*57696d54SAkhilesh Sanikop 
862*57696d54SAkhilesh Sanikop    if (allOK && myDisk.OpenForRead(deviceFilename)) {
863*57696d54SAkhilesh Sanikop       // store disk information....
864*57696d54SAkhilesh Sanikop       diskSize = myDisk.DiskSize(&err);
865*57696d54SAkhilesh Sanikop       blockSize = (uint32_t) myDisk.GetBlockSize();
866*57696d54SAkhilesh Sanikop       physBlockSize = (uint32_t) myDisk.GetPhysBlockSize();
867*57696d54SAkhilesh Sanikop       device = deviceFilename;
868*57696d54SAkhilesh Sanikop       PartitionScan(); // Check for partition types, load GPT, & print summary
869*57696d54SAkhilesh Sanikop 
870*57696d54SAkhilesh Sanikop       whichWasUsed = UseWhichPartitions();
871*57696d54SAkhilesh Sanikop       switch (whichWasUsed) {
872*57696d54SAkhilesh Sanikop          case use_mbr:
873*57696d54SAkhilesh Sanikop             XFormPartitions();
874*57696d54SAkhilesh Sanikop             break;
875*57696d54SAkhilesh Sanikop          case use_bsd:
876*57696d54SAkhilesh Sanikop             bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
877*57696d54SAkhilesh Sanikop //            bsdDisklabel.DisplayBSDData();
878*57696d54SAkhilesh Sanikop             ClearGPTData();
879*57696d54SAkhilesh Sanikop             protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
880*57696d54SAkhilesh Sanikop             XFormDisklabel(&bsdDisklabel);
881*57696d54SAkhilesh Sanikop             break;
882*57696d54SAkhilesh Sanikop          case use_gpt:
883*57696d54SAkhilesh Sanikop             mbrState = protectiveMBR.GetValidity();
884*57696d54SAkhilesh Sanikop             if ((mbrState == invalid) || (mbrState == mbr))
885*57696d54SAkhilesh Sanikop                protectiveMBR.MakeProtectiveMBR();
886*57696d54SAkhilesh Sanikop             break;
887*57696d54SAkhilesh Sanikop          case use_new:
888*57696d54SAkhilesh Sanikop             ClearGPTData();
889*57696d54SAkhilesh Sanikop             protectiveMBR.MakeProtectiveMBR();
890*57696d54SAkhilesh Sanikop             break;
891*57696d54SAkhilesh Sanikop          case use_abort:
892*57696d54SAkhilesh Sanikop             allOK = 0;
893*57696d54SAkhilesh Sanikop             cerr << "Invalid partition data!\n";
894*57696d54SAkhilesh Sanikop             break;
895*57696d54SAkhilesh Sanikop       } // switch
896*57696d54SAkhilesh Sanikop 
897*57696d54SAkhilesh Sanikop       if (allOK) {
898*57696d54SAkhilesh Sanikop          CheckGPTSize();
899*57696d54SAkhilesh Sanikop          // Below is unlikely to happen on real disks, but could happen if
900*57696d54SAkhilesh Sanikop          // the user is manipulating a truncated image file....
901*57696d54SAkhilesh Sanikop          if (diskSize <= GetTableSizeInSectors() * 2 + 3) {
902*57696d54SAkhilesh Sanikop              allOK = 0;
903*57696d54SAkhilesh Sanikop              cout << "Disk is too small to hold GPT data (" << diskSize
904*57696d54SAkhilesh Sanikop                   << " sectors)! Aborting!\n";
905*57696d54SAkhilesh Sanikop          }
906*57696d54SAkhilesh Sanikop       }
907*57696d54SAkhilesh Sanikop       myDisk.Close();
908*57696d54SAkhilesh Sanikop       ComputeAlignment();
909*57696d54SAkhilesh Sanikop    } else {
910*57696d54SAkhilesh Sanikop       allOK = 0;
911*57696d54SAkhilesh Sanikop    } // if/else
912*57696d54SAkhilesh Sanikop    return (allOK);
913*57696d54SAkhilesh Sanikop } // GPTData::LoadPartitions()
914*57696d54SAkhilesh Sanikop 
915*57696d54SAkhilesh Sanikop // Loads the GPT, as much as possible. Returns 1 if this seems to have
916*57696d54SAkhilesh Sanikop // succeeded, 0 if there are obvious problems....
ForceLoadGPTData(void)917*57696d54SAkhilesh Sanikop int GPTData::ForceLoadGPTData(void) {
918*57696d54SAkhilesh Sanikop    int allOK, validHeaders, loadedTable = 1;
919*57696d54SAkhilesh Sanikop 
920*57696d54SAkhilesh Sanikop    allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
921*57696d54SAkhilesh Sanikop 
922*57696d54SAkhilesh Sanikop    if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
923*57696d54SAkhilesh Sanikop       allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
924*57696d54SAkhilesh Sanikop    } else {
925*57696d54SAkhilesh Sanikop       allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
926*57696d54SAkhilesh Sanikop       if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
927*57696d54SAkhilesh Sanikop          cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
928*57696d54SAkhilesh Sanikop               << "secondary header from the last sector of the disk! You should use 'v' to\n"
929*57696d54SAkhilesh Sanikop               << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
930*57696d54SAkhilesh Sanikop               << "the disk.\n";
931*57696d54SAkhilesh Sanikop    } // if/else
932*57696d54SAkhilesh Sanikop    if (!allOK)
933*57696d54SAkhilesh Sanikop       state = gpt_invalid;
934*57696d54SAkhilesh Sanikop 
935*57696d54SAkhilesh Sanikop    // Return valid headers code: 0 = both headers bad; 1 = main header
936*57696d54SAkhilesh Sanikop    // good, backup bad; 2 = backup header good, main header bad;
937*57696d54SAkhilesh Sanikop    // 3 = both headers good. Note these codes refer to valid GPT
938*57696d54SAkhilesh Sanikop    // signatures, version numbers, and CRCs.
939*57696d54SAkhilesh Sanikop    validHeaders = CheckHeaderValidity();
940*57696d54SAkhilesh Sanikop 
941*57696d54SAkhilesh Sanikop    // Read partitions (from primary array)
942*57696d54SAkhilesh Sanikop    if (validHeaders > 0) { // if at least one header is OK....
943*57696d54SAkhilesh Sanikop       // GPT appears to be valid....
944*57696d54SAkhilesh Sanikop       state = gpt_valid;
945*57696d54SAkhilesh Sanikop 
946*57696d54SAkhilesh Sanikop       // We're calling the GPT valid, but there's a possibility that one
947*57696d54SAkhilesh Sanikop       // of the two headers is corrupt. If so, use the one that seems to
948*57696d54SAkhilesh Sanikop       // be in better shape to regenerate the bad one
949*57696d54SAkhilesh Sanikop       if (validHeaders == 1) { // valid main header, invalid backup header
950*57696d54SAkhilesh Sanikop          cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
951*57696d54SAkhilesh Sanikop               << "backup header from main header.\n\n";
952*57696d54SAkhilesh Sanikop          RebuildSecondHeader();
953*57696d54SAkhilesh Sanikop          state = gpt_corrupt;
954*57696d54SAkhilesh Sanikop          secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
955*57696d54SAkhilesh Sanikop       } else if (validHeaders == 2) { // valid backup header, invalid main header
956*57696d54SAkhilesh Sanikop          cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
957*57696d54SAkhilesh Sanikop               << "from backup!\n\n";
958*57696d54SAkhilesh Sanikop          RebuildMainHeader();
959*57696d54SAkhilesh Sanikop          state = gpt_corrupt;
960*57696d54SAkhilesh Sanikop          mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
961*57696d54SAkhilesh Sanikop       } // if/else/if
962*57696d54SAkhilesh Sanikop 
963*57696d54SAkhilesh Sanikop       // Figure out which partition table to load....
964*57696d54SAkhilesh Sanikop       // Load the main partition table, if its header's CRC is OK
965*57696d54SAkhilesh Sanikop       if (validHeaders != 2) {
966*57696d54SAkhilesh Sanikop          if (LoadMainTable() == 0)
967*57696d54SAkhilesh Sanikop             allOK = 0;
968*57696d54SAkhilesh Sanikop       } else { // bad main header CRC and backup header CRC is OK
969*57696d54SAkhilesh Sanikop          state = gpt_corrupt;
970*57696d54SAkhilesh Sanikop          if (LoadSecondTableAsMain()) {
971*57696d54SAkhilesh Sanikop             loadedTable = 2;
972*57696d54SAkhilesh Sanikop             cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
973*57696d54SAkhilesh Sanikop          } else { // backup table bad, bad main header CRC, but try main table in desperation....
974*57696d54SAkhilesh Sanikop             if (LoadMainTable() == 0) {
975*57696d54SAkhilesh Sanikop                allOK = 0;
976*57696d54SAkhilesh Sanikop                loadedTable = 0;
977*57696d54SAkhilesh Sanikop                cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
978*57696d54SAkhilesh Sanikop             } // if
979*57696d54SAkhilesh Sanikop          } // if/else (LoadSecondTableAsMain())
980*57696d54SAkhilesh Sanikop       } // if/else (load partition table)
981*57696d54SAkhilesh Sanikop 
982*57696d54SAkhilesh Sanikop       if (loadedTable == 1)
983*57696d54SAkhilesh Sanikop          secondPartsCrcOk = CheckTable(&secondHeader);
984*57696d54SAkhilesh Sanikop       else if (loadedTable == 2)
985*57696d54SAkhilesh Sanikop          mainPartsCrcOk = CheckTable(&mainHeader);
986*57696d54SAkhilesh Sanikop       else
987*57696d54SAkhilesh Sanikop          mainPartsCrcOk = secondPartsCrcOk = 0;
988*57696d54SAkhilesh Sanikop 
989*57696d54SAkhilesh Sanikop       // Problem with main partition table; if backup is OK, use it instead....
990*57696d54SAkhilesh Sanikop       if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
991*57696d54SAkhilesh Sanikop          state = gpt_corrupt;
992*57696d54SAkhilesh Sanikop          allOK = allOK && LoadSecondTableAsMain();
993*57696d54SAkhilesh Sanikop          mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
994*57696d54SAkhilesh Sanikop          cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
995*57696d54SAkhilesh Sanikop               << "partition table\ninstead of main partition table!\n\n";
996*57696d54SAkhilesh Sanikop       } // if */
997*57696d54SAkhilesh Sanikop 
998*57696d54SAkhilesh Sanikop       // Check for valid CRCs and warn if there are problems
999*57696d54SAkhilesh Sanikop       if ((validHeaders != 3) || (mainPartsCrcOk == 0) ||
1000*57696d54SAkhilesh Sanikop            (secondPartsCrcOk == 0)) {
1001*57696d54SAkhilesh Sanikop          cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n";
1002*57696d54SAkhilesh Sanikop          // Show detail status of header and table
1003*57696d54SAkhilesh Sanikop          if (validHeaders & 0x1)
1004*57696d54SAkhilesh Sanikop             cerr << "Main header: OK\n";
1005*57696d54SAkhilesh Sanikop          else
1006*57696d54SAkhilesh Sanikop             cerr << "Main header: ERROR\n";
1007*57696d54SAkhilesh Sanikop          if (validHeaders & 0x2)
1008*57696d54SAkhilesh Sanikop             cerr << "Backup header: OK\n";
1009*57696d54SAkhilesh Sanikop          else
1010*57696d54SAkhilesh Sanikop             cerr << "Backup header: ERROR\n";
1011*57696d54SAkhilesh Sanikop          if (mainPartsCrcOk)
1012*57696d54SAkhilesh Sanikop             cerr << "Main partition table: OK\n";
1013*57696d54SAkhilesh Sanikop          else
1014*57696d54SAkhilesh Sanikop             cerr << "Main partition table: ERROR\n";
1015*57696d54SAkhilesh Sanikop          if (secondPartsCrcOk)
1016*57696d54SAkhilesh Sanikop             cerr << "Backup partition table: OK\n";
1017*57696d54SAkhilesh Sanikop          else
1018*57696d54SAkhilesh Sanikop             cerr << "Backup partition table: ERROR\n";
1019*57696d54SAkhilesh Sanikop          cerr << "\n";
1020*57696d54SAkhilesh Sanikop          state = gpt_corrupt;
1021*57696d54SAkhilesh Sanikop       } // if
1022*57696d54SAkhilesh Sanikop    } else {
1023*57696d54SAkhilesh Sanikop       state = gpt_invalid;
1024*57696d54SAkhilesh Sanikop    } // if/else
1025*57696d54SAkhilesh Sanikop    return allOK;
1026*57696d54SAkhilesh Sanikop } // GPTData::ForceLoadGPTData()
1027*57696d54SAkhilesh Sanikop 
1028*57696d54SAkhilesh Sanikop // Loads the partition table pointed to by the main GPT header. The
1029*57696d54SAkhilesh Sanikop // main GPT header in memory MUST be valid for this call to do anything
1030*57696d54SAkhilesh Sanikop // sensible!
1031*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadMainTable(void)1032*57696d54SAkhilesh Sanikop int GPTData::LoadMainTable(void) {
1033*57696d54SAkhilesh Sanikop    return LoadPartitionTable(mainHeader, myDisk);
1034*57696d54SAkhilesh Sanikop } // GPTData::LoadMainTable()
1035*57696d54SAkhilesh Sanikop 
1036*57696d54SAkhilesh Sanikop // Load the second (backup) partition table as the primary partition
1037*57696d54SAkhilesh Sanikop // table. Used in repair functions, and when starting up if the main
1038*57696d54SAkhilesh Sanikop // partition table is damaged.
1039*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadSecondTableAsMain(void)1040*57696d54SAkhilesh Sanikop int GPTData::LoadSecondTableAsMain(void) {
1041*57696d54SAkhilesh Sanikop    return LoadPartitionTable(secondHeader, myDisk);
1042*57696d54SAkhilesh Sanikop } // GPTData::LoadSecondTableAsMain()
1043*57696d54SAkhilesh Sanikop 
1044*57696d54SAkhilesh Sanikop // Load a single GPT header (main or backup) from the specified disk device and
1045*57696d54SAkhilesh Sanikop // sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
1046*57696d54SAkhilesh Sanikop // value appropriately.
1047*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
1048*57696d54SAkhilesh Sanikop // failure.
LoadHeader(struct GPTHeader * header,DiskIO & disk,uint64_t sector,int * crcOk)1049*57696d54SAkhilesh Sanikop int GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
1050*57696d54SAkhilesh Sanikop    int allOK = 1;
1051*57696d54SAkhilesh Sanikop    GPTHeader tempHeader;
1052*57696d54SAkhilesh Sanikop 
1053*57696d54SAkhilesh Sanikop    disk.Seek(sector);
1054*57696d54SAkhilesh Sanikop    if (disk.Read(&tempHeader, 512) != 512) {
1055*57696d54SAkhilesh Sanikop       cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
1056*57696d54SAkhilesh Sanikop       allOK = 0;
1057*57696d54SAkhilesh Sanikop    } // if
1058*57696d54SAkhilesh Sanikop 
1059*57696d54SAkhilesh Sanikop    // Reverse byte order, if necessary
1060*57696d54SAkhilesh Sanikop    if (IsLittleEndian() == 0) {
1061*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(&tempHeader);
1062*57696d54SAkhilesh Sanikop    } // if
1063*57696d54SAkhilesh Sanikop    *crcOk = CheckHeaderCRC(&tempHeader);
1064*57696d54SAkhilesh Sanikop 
1065*57696d54SAkhilesh Sanikop    if (tempHeader.sizeOfPartitionEntries != sizeof(GPTPart)) {
1066*57696d54SAkhilesh Sanikop       // Print the below warning only if the CRC is OK -- but correct the
1067*57696d54SAkhilesh Sanikop       // problem either way. The warning is printed only on a valid CRC
1068*57696d54SAkhilesh Sanikop       // because otherwise this warning will display inappropriately when
1069*57696d54SAkhilesh Sanikop       // reading MBR disks. If the CRC is invalid, then a warning about
1070*57696d54SAkhilesh Sanikop       // that will be shown later, so the user will still know that
1071*57696d54SAkhilesh Sanikop       // something is wrong.
1072*57696d54SAkhilesh Sanikop       if (*crcOk) {
1073*57696d54SAkhilesh Sanikop          cerr << "Warning: Partition table header claims that the size of partition table\n";
1074*57696d54SAkhilesh Sanikop          cerr << "entries is " << tempHeader.sizeOfPartitionEntries << " bytes, but this program ";
1075*57696d54SAkhilesh Sanikop          cerr << " supports only " << sizeof(GPTPart) << "-byte entries.\n";
1076*57696d54SAkhilesh Sanikop          cerr << "Adjusting accordingly, but partition table may be garbage.\n";
1077*57696d54SAkhilesh Sanikop       }
1078*57696d54SAkhilesh Sanikop       tempHeader.sizeOfPartitionEntries = sizeof(GPTPart);
1079*57696d54SAkhilesh Sanikop    }
1080*57696d54SAkhilesh Sanikop 
1081*57696d54SAkhilesh Sanikop    if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
1082*57696d54SAkhilesh Sanikop       allOK = SetGPTSize(tempHeader.numParts, 0);
1083*57696d54SAkhilesh Sanikop    }
1084*57696d54SAkhilesh Sanikop 
1085*57696d54SAkhilesh Sanikop    *header = tempHeader;
1086*57696d54SAkhilesh Sanikop    return allOK;
1087*57696d54SAkhilesh Sanikop } // GPTData::LoadHeader
1088*57696d54SAkhilesh Sanikop 
1089*57696d54SAkhilesh Sanikop // Load a partition table (either main or secondary) from the specified disk,
1090*57696d54SAkhilesh Sanikop // using header as a reference for what to load. If sector != 0 (the default
1091*57696d54SAkhilesh Sanikop // is 0), loads from the specified sector; otherwise loads from the sector
1092*57696d54SAkhilesh Sanikop // indicated in header.
1093*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
LoadPartitionTable(const struct GPTHeader & header,DiskIO & disk,uint64_t sector)1094*57696d54SAkhilesh Sanikop int GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
1095*57696d54SAkhilesh Sanikop    uint32_t sizeOfParts, newCRC;
1096*57696d54SAkhilesh Sanikop    int retval;
1097*57696d54SAkhilesh Sanikop 
1098*57696d54SAkhilesh Sanikop    if (header.sizeOfPartitionEntries != sizeof(GPTPart)) {
1099*57696d54SAkhilesh Sanikop       cerr << "Error! GPT header contains invalid partition entry size!\n";
1100*57696d54SAkhilesh Sanikop       retval = 0;
1101*57696d54SAkhilesh Sanikop    } else if (disk.OpenForRead()) {
1102*57696d54SAkhilesh Sanikop       if (sector == 0) {
1103*57696d54SAkhilesh Sanikop          retval = disk.Seek(header.partitionEntriesLBA);
1104*57696d54SAkhilesh Sanikop       } else {
1105*57696d54SAkhilesh Sanikop          retval = disk.Seek(sector);
1106*57696d54SAkhilesh Sanikop       } // if/else
1107*57696d54SAkhilesh Sanikop       if (retval == 1)
1108*57696d54SAkhilesh Sanikop          retval = SetGPTSize(header.numParts, 0);
1109*57696d54SAkhilesh Sanikop       if (retval == 1) {
1110*57696d54SAkhilesh Sanikop          sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
1111*57696d54SAkhilesh Sanikop          if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
1112*57696d54SAkhilesh Sanikop             cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
1113*57696d54SAkhilesh Sanikop             retval = 0;
1114*57696d54SAkhilesh Sanikop          } // if
1115*57696d54SAkhilesh Sanikop          newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
1116*57696d54SAkhilesh Sanikop          mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
1117*57696d54SAkhilesh Sanikop          if (IsLittleEndian() == 0)
1118*57696d54SAkhilesh Sanikop             ReversePartitionBytes();
1119*57696d54SAkhilesh Sanikop          if (!mainPartsCrcOk) {
1120*57696d54SAkhilesh Sanikop             cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
1121*57696d54SAkhilesh Sanikop          } // if
1122*57696d54SAkhilesh Sanikop       } else {
1123*57696d54SAkhilesh Sanikop          cerr << "Error! Couldn't seek to partition table!\n";
1124*57696d54SAkhilesh Sanikop       } // if/else
1125*57696d54SAkhilesh Sanikop    } else {
1126*57696d54SAkhilesh Sanikop       cerr << "Error! Couldn't open device " << device
1127*57696d54SAkhilesh Sanikop            << " when reading partition table!\n";
1128*57696d54SAkhilesh Sanikop       retval = 0;
1129*57696d54SAkhilesh Sanikop    } // if/else
1130*57696d54SAkhilesh Sanikop    return retval;
1131*57696d54SAkhilesh Sanikop } // GPTData::LoadPartitionsTable()
1132*57696d54SAkhilesh Sanikop 
1133*57696d54SAkhilesh Sanikop // Check the partition table pointed to by header, but don't keep it
1134*57696d54SAkhilesh Sanikop // around.
1135*57696d54SAkhilesh Sanikop // Returns 1 if the CRC is OK & this table matches the one already in memory,
1136*57696d54SAkhilesh Sanikop // 0 if not or if there was a read error.
CheckTable(struct GPTHeader * header)1137*57696d54SAkhilesh Sanikop int GPTData::CheckTable(struct GPTHeader *header) {
1138*57696d54SAkhilesh Sanikop    uint32_t sizeOfParts, newCRC;
1139*57696d54SAkhilesh Sanikop    GPTPart *partsToCheck;
1140*57696d54SAkhilesh Sanikop    GPTHeader *otherHeader;
1141*57696d54SAkhilesh Sanikop    int allOK = 0;
1142*57696d54SAkhilesh Sanikop 
1143*57696d54SAkhilesh Sanikop    // Load partition table into temporary storage to check
1144*57696d54SAkhilesh Sanikop    // its CRC and store the results, then discard this temporary
1145*57696d54SAkhilesh Sanikop    // storage, since we don't use it in any but recovery operations
1146*57696d54SAkhilesh Sanikop    if (myDisk.Seek(header->partitionEntriesLBA)) {
1147*57696d54SAkhilesh Sanikop       partsToCheck = new GPTPart[header->numParts];
1148*57696d54SAkhilesh Sanikop       sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
1149*57696d54SAkhilesh Sanikop       if (partsToCheck == NULL) {
1150*57696d54SAkhilesh Sanikop          cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
1151*57696d54SAkhilesh Sanikop          exit(1);
1152*57696d54SAkhilesh Sanikop       } // if
1153*57696d54SAkhilesh Sanikop       if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
1154*57696d54SAkhilesh Sanikop          cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
1155*57696d54SAkhilesh Sanikop       } else {
1156*57696d54SAkhilesh Sanikop          newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
1157*57696d54SAkhilesh Sanikop          allOK = (newCRC == header->partitionEntriesCRC);
1158*57696d54SAkhilesh Sanikop          if (header == &mainHeader)
1159*57696d54SAkhilesh Sanikop             otherHeader = &secondHeader;
1160*57696d54SAkhilesh Sanikop          else
1161*57696d54SAkhilesh Sanikop             otherHeader = &mainHeader;
1162*57696d54SAkhilesh Sanikop          if (newCRC != otherHeader->partitionEntriesCRC) {
1163*57696d54SAkhilesh Sanikop             cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
1164*57696d54SAkhilesh Sanikop                  << "on the recovery & transformation menu to examine the two tables.\n\n";
1165*57696d54SAkhilesh Sanikop             allOK = 0;
1166*57696d54SAkhilesh Sanikop          } // if
1167*57696d54SAkhilesh Sanikop       } // if/else
1168*57696d54SAkhilesh Sanikop       delete[] partsToCheck;
1169*57696d54SAkhilesh Sanikop    } // if
1170*57696d54SAkhilesh Sanikop    return allOK;
1171*57696d54SAkhilesh Sanikop } // GPTData::CheckTable()
1172*57696d54SAkhilesh Sanikop 
1173*57696d54SAkhilesh Sanikop // Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1174*57696d54SAkhilesh Sanikop // header later on the disk without asking for permission, if necessary, and
1175*57696d54SAkhilesh Sanikop // doesn't confirm the operation before writing. If quiet==0, asks permission
1176*57696d54SAkhilesh Sanikop // before moving the second header and asks for final confirmation of any
1177*57696d54SAkhilesh Sanikop // write.
1178*57696d54SAkhilesh Sanikop // Returns 1 on successful write, 0 if there was a problem.
SaveGPTData(int quiet)1179*57696d54SAkhilesh Sanikop int GPTData::SaveGPTData(int quiet) {
1180*57696d54SAkhilesh Sanikop    int allOK = 1, syncIt = 1;
1181*57696d54SAkhilesh Sanikop    char answer;
1182*57696d54SAkhilesh Sanikop 
1183*57696d54SAkhilesh Sanikop    // First do some final sanity checks....
1184*57696d54SAkhilesh Sanikop 
1185*57696d54SAkhilesh Sanikop    // This test should only fail on read-only disks....
1186*57696d54SAkhilesh Sanikop    if (justLooking) {
1187*57696d54SAkhilesh Sanikop       cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
1188*57696d54SAkhilesh Sanikop       allOK = 0;
1189*57696d54SAkhilesh Sanikop    } // if
1190*57696d54SAkhilesh Sanikop 
1191*57696d54SAkhilesh Sanikop    // Check that disk is really big enough to handle the second header...
1192*57696d54SAkhilesh Sanikop    if (mainHeader.backupLBA >= diskSize) {
1193*57696d54SAkhilesh Sanikop       cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1194*57696d54SAkhilesh Sanikop            << "header, but other problems may occur!\n";
1195*57696d54SAkhilesh Sanikop       MoveSecondHeaderToEnd();
1196*57696d54SAkhilesh Sanikop    } // if
1197*57696d54SAkhilesh Sanikop 
1198*57696d54SAkhilesh Sanikop    // Is there enough space to hold the GPT headers and partition tables,
1199*57696d54SAkhilesh Sanikop    // given the partition sizes?
1200*57696d54SAkhilesh Sanikop    if (CheckGPTSize() > 0) {
1201*57696d54SAkhilesh Sanikop       allOK = 0;
1202*57696d54SAkhilesh Sanikop    } // if
1203*57696d54SAkhilesh Sanikop 
1204*57696d54SAkhilesh Sanikop    // Check that second header is properly placed. Warn and ask if this should
1205*57696d54SAkhilesh Sanikop    // be corrected if the test fails....
1206*57696d54SAkhilesh Sanikop    if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
1207*57696d54SAkhilesh Sanikop       if (quiet == 0) {
1208*57696d54SAkhilesh Sanikop          cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
1209*57696d54SAkhilesh Sanikop               << "correct this problem? ";
1210*57696d54SAkhilesh Sanikop          if (GetYN() == 'Y') {
1211*57696d54SAkhilesh Sanikop             MoveSecondHeaderToEnd();
1212*57696d54SAkhilesh Sanikop             cout << "Have moved second header and partition table to correct location.\n";
1213*57696d54SAkhilesh Sanikop          } else {
1214*57696d54SAkhilesh Sanikop             cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1215*57696d54SAkhilesh Sanikop          } // if correction requested
1216*57696d54SAkhilesh Sanikop       } else { // Go ahead and do correction automatically
1217*57696d54SAkhilesh Sanikop          MoveSecondHeaderToEnd();
1218*57696d54SAkhilesh Sanikop       } // if/else quiet
1219*57696d54SAkhilesh Sanikop    } // if
1220*57696d54SAkhilesh Sanikop 
1221*57696d54SAkhilesh Sanikop    if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1222*57696d54SAkhilesh Sanikop       if (quiet == 0) {
1223*57696d54SAkhilesh Sanikop          cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1224*57696d54SAkhilesh Sanikop               << "this problem? ";
1225*57696d54SAkhilesh Sanikop          if (GetYN() == 'Y') {
1226*57696d54SAkhilesh Sanikop             MoveSecondHeaderToEnd();
1227*57696d54SAkhilesh Sanikop             cout << "Have adjusted the second header and last usable sector value.\n";
1228*57696d54SAkhilesh Sanikop          } else {
1229*57696d54SAkhilesh Sanikop             cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1230*57696d54SAkhilesh Sanikop          } // if correction requested
1231*57696d54SAkhilesh Sanikop       } else { // go ahead and do correction automatically
1232*57696d54SAkhilesh Sanikop          MoveSecondHeaderToEnd();
1233*57696d54SAkhilesh Sanikop       } // if/else quiet
1234*57696d54SAkhilesh Sanikop    } // if
1235*57696d54SAkhilesh Sanikop 
1236*57696d54SAkhilesh Sanikop    // Check for overlapping or insane partitions....
1237*57696d54SAkhilesh Sanikop    if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
1238*57696d54SAkhilesh Sanikop       allOK = 0;
1239*57696d54SAkhilesh Sanikop       cerr << "Aborting write operation!\n";
1240*57696d54SAkhilesh Sanikop    } // if
1241*57696d54SAkhilesh Sanikop 
1242*57696d54SAkhilesh Sanikop    // Check that protective MBR fits, and warn if it doesn't....
1243*57696d54SAkhilesh Sanikop    if (!protectiveMBR.DoTheyFit()) {
1244*57696d54SAkhilesh Sanikop       cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1245*57696d54SAkhilesh Sanikop            << "fresh protective or hybrid MBR is recommended.\n";
1246*57696d54SAkhilesh Sanikop    }
1247*57696d54SAkhilesh Sanikop 
1248*57696d54SAkhilesh Sanikop    // Check for mismatched MBR and GPT data, but let it pass if found
1249*57696d54SAkhilesh Sanikop    // (function displays warning message)
1250*57696d54SAkhilesh Sanikop    FindHybridMismatches();
1251*57696d54SAkhilesh Sanikop 
1252*57696d54SAkhilesh Sanikop    RecomputeCRCs();
1253*57696d54SAkhilesh Sanikop 
1254*57696d54SAkhilesh Sanikop    if ((allOK) && (!quiet)) {
1255*57696d54SAkhilesh Sanikop       cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
1256*57696d54SAkhilesh Sanikop            << "PARTITIONS!!\n\nDo you want to proceed? ";
1257*57696d54SAkhilesh Sanikop       answer = GetYN();
1258*57696d54SAkhilesh Sanikop       if (answer == 'Y') {
1259*57696d54SAkhilesh Sanikop          cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
1260*57696d54SAkhilesh Sanikop       } else {
1261*57696d54SAkhilesh Sanikop          allOK = 0;
1262*57696d54SAkhilesh Sanikop       } // if/else
1263*57696d54SAkhilesh Sanikop    } // if
1264*57696d54SAkhilesh Sanikop 
1265*57696d54SAkhilesh Sanikop    // Do it!
1266*57696d54SAkhilesh Sanikop    if (allOK) {
1267*57696d54SAkhilesh Sanikop       if (myDisk.OpenForWrite()) {
1268*57696d54SAkhilesh Sanikop          // As per UEFI specs, write the secondary table and GPT first....
1269*57696d54SAkhilesh Sanikop          allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1270*57696d54SAkhilesh Sanikop          if (!allOK) {
1271*57696d54SAkhilesh Sanikop             cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1272*57696d54SAkhilesh Sanikop                  << "menu will resolve this problem.\n";
1273*57696d54SAkhilesh Sanikop             syncIt = 0;
1274*57696d54SAkhilesh Sanikop          } // if
1275*57696d54SAkhilesh Sanikop 
1276*57696d54SAkhilesh Sanikop          // Now write the secondary GPT header...
1277*57696d54SAkhilesh Sanikop          allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1278*57696d54SAkhilesh Sanikop 
1279*57696d54SAkhilesh Sanikop          // Now write the main partition tables...
1280*57696d54SAkhilesh Sanikop          allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1281*57696d54SAkhilesh Sanikop 
1282*57696d54SAkhilesh Sanikop          // Now write the main GPT header...
1283*57696d54SAkhilesh Sanikop          allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1284*57696d54SAkhilesh Sanikop 
1285*57696d54SAkhilesh Sanikop          // To top it off, write the protective MBR...
1286*57696d54SAkhilesh Sanikop          allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
1287*57696d54SAkhilesh Sanikop 
1288*57696d54SAkhilesh Sanikop          // re-read the partition table
1289*57696d54SAkhilesh Sanikop          // Note: Done even if some write operations failed, but not if all of them failed.
1290*57696d54SAkhilesh Sanikop          // Done this way because I've received one problem report from a user one whose
1291*57696d54SAkhilesh Sanikop          // system the MBR write failed but everything else was OK (on a GPT disk under
1292*57696d54SAkhilesh Sanikop          // Windows), and the failure to sync therefore caused Windows to restore the
1293*57696d54SAkhilesh Sanikop          // original partition table from its cache. OTOH, such restoration might be
1294*57696d54SAkhilesh Sanikop          // desirable if the error occurs later; but that seems unlikely unless the initial
1295*57696d54SAkhilesh Sanikop          // write fails....
1296*57696d54SAkhilesh Sanikop          if (syncIt)
1297*57696d54SAkhilesh Sanikop             myDisk.DiskSync();
1298*57696d54SAkhilesh Sanikop 
1299*57696d54SAkhilesh Sanikop          if (allOK) { // writes completed OK
1300*57696d54SAkhilesh Sanikop             cout << "The operation has completed successfully.\n";
1301*57696d54SAkhilesh Sanikop          } else {
1302*57696d54SAkhilesh Sanikop             cerr << "Warning! An error was reported when writing the partition table! This error\n"
1303*57696d54SAkhilesh Sanikop                  << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
1304*57696d54SAkhilesh Sanikop          } // if/else
1305*57696d54SAkhilesh Sanikop 
1306*57696d54SAkhilesh Sanikop          myDisk.Close();
1307*57696d54SAkhilesh Sanikop       } else {
1308*57696d54SAkhilesh Sanikop          cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
1309*57696d54SAkhilesh Sanikop               << errno << "! Aborting write!\n";
1310*57696d54SAkhilesh Sanikop          allOK = 0;
1311*57696d54SAkhilesh Sanikop       } // if/else
1312*57696d54SAkhilesh Sanikop    } else {
1313*57696d54SAkhilesh Sanikop       cout << "Aborting write of new partition table.\n";
1314*57696d54SAkhilesh Sanikop    } // if
1315*57696d54SAkhilesh Sanikop 
1316*57696d54SAkhilesh Sanikop    return (allOK);
1317*57696d54SAkhilesh Sanikop } // GPTData::SaveGPTData()
1318*57696d54SAkhilesh Sanikop 
1319*57696d54SAkhilesh Sanikop // Save GPT data to a backup file. This function does much less error
1320*57696d54SAkhilesh Sanikop // checking than SaveGPTData(). It can therefore preserve many types of
1321*57696d54SAkhilesh Sanikop // corruption for later analysis; however, it preserves only the MBR,
1322*57696d54SAkhilesh Sanikop // the main GPT header, the backup GPT header, and the main partition
1323*57696d54SAkhilesh Sanikop // table; it discards the backup partition table, since it should be
1324*57696d54SAkhilesh Sanikop // identical to the main partition table on healthy disks.
SaveGPTBackup(const string & filename)1325*57696d54SAkhilesh Sanikop int GPTData::SaveGPTBackup(const string & filename) {
1326*57696d54SAkhilesh Sanikop    int allOK = 1;
1327*57696d54SAkhilesh Sanikop    DiskIO backupFile;
1328*57696d54SAkhilesh Sanikop 
1329*57696d54SAkhilesh Sanikop    if (backupFile.OpenForWrite(filename)) {
1330*57696d54SAkhilesh Sanikop       // Recomputing the CRCs is likely to alter them, which could be bad
1331*57696d54SAkhilesh Sanikop       // if the intent is to save a potentially bad GPT for later analysis;
1332*57696d54SAkhilesh Sanikop       // but if we don't do this, we get bogus errors when we load the
1333*57696d54SAkhilesh Sanikop       // backup. I'm favoring misses over false alarms....
1334*57696d54SAkhilesh Sanikop       RecomputeCRCs();
1335*57696d54SAkhilesh Sanikop 
1336*57696d54SAkhilesh Sanikop       protectiveMBR.WriteMBRData(&backupFile);
1337*57696d54SAkhilesh Sanikop       protectiveMBR.SetDisk(&myDisk);
1338*57696d54SAkhilesh Sanikop 
1339*57696d54SAkhilesh Sanikop       if (allOK) {
1340*57696d54SAkhilesh Sanikop          // MBR write closed disk, so re-open and seek to end....
1341*57696d54SAkhilesh Sanikop          backupFile.OpenForWrite();
1342*57696d54SAkhilesh Sanikop          allOK = SaveHeader(&mainHeader, backupFile, 1);
1343*57696d54SAkhilesh Sanikop       } // if (allOK)
1344*57696d54SAkhilesh Sanikop 
1345*57696d54SAkhilesh Sanikop       if (allOK)
1346*57696d54SAkhilesh Sanikop          allOK = SaveHeader(&secondHeader, backupFile, 2);
1347*57696d54SAkhilesh Sanikop 
1348*57696d54SAkhilesh Sanikop       if (allOK)
1349*57696d54SAkhilesh Sanikop          allOK = SavePartitionTable(backupFile, 3);
1350*57696d54SAkhilesh Sanikop 
1351*57696d54SAkhilesh Sanikop       if (allOK) { // writes completed OK
1352*57696d54SAkhilesh Sanikop          cout << "The operation has completed successfully.\n";
1353*57696d54SAkhilesh Sanikop       } else {
1354*57696d54SAkhilesh Sanikop          cerr << "Warning! An error was reported when writing the backup file.\n"
1355*57696d54SAkhilesh Sanikop               << "It may not be usable!\n";
1356*57696d54SAkhilesh Sanikop       } // if/else
1357*57696d54SAkhilesh Sanikop       backupFile.Close();
1358*57696d54SAkhilesh Sanikop    } else {
1359*57696d54SAkhilesh Sanikop       cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
1360*57696d54SAkhilesh Sanikop       allOK = 0;
1361*57696d54SAkhilesh Sanikop    } // if/else
1362*57696d54SAkhilesh Sanikop    return allOK;
1363*57696d54SAkhilesh Sanikop } // GPTData::SaveGPTBackup()
1364*57696d54SAkhilesh Sanikop 
1365*57696d54SAkhilesh Sanikop // Write a GPT header (main or backup) to the specified sector. Used by both
1366*57696d54SAkhilesh Sanikop // the SaveGPTData() and SaveGPTBackup() functions.
1367*57696d54SAkhilesh Sanikop // Should be passed an architecture-appropriate header (DO NOT call
1368*57696d54SAkhilesh Sanikop // ReverseHeaderBytes() on the header before calling this function)
1369*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure
SaveHeader(struct GPTHeader * header,DiskIO & disk,uint64_t sector)1370*57696d54SAkhilesh Sanikop int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1371*57696d54SAkhilesh Sanikop    int littleEndian, allOK = 1;
1372*57696d54SAkhilesh Sanikop 
1373*57696d54SAkhilesh Sanikop    littleEndian = IsLittleEndian();
1374*57696d54SAkhilesh Sanikop    if (!littleEndian)
1375*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(header);
1376*57696d54SAkhilesh Sanikop    if (disk.Seek(sector)) {
1377*57696d54SAkhilesh Sanikop       if (disk.Write(header, 512) == -1)
1378*57696d54SAkhilesh Sanikop          allOK = 0;
1379*57696d54SAkhilesh Sanikop    } else allOK = 0; // if (disk.Seek()...)
1380*57696d54SAkhilesh Sanikop    if (!littleEndian)
1381*57696d54SAkhilesh Sanikop       ReverseHeaderBytes(header);
1382*57696d54SAkhilesh Sanikop    return allOK;
1383*57696d54SAkhilesh Sanikop } // GPTData::SaveHeader()
1384*57696d54SAkhilesh Sanikop 
1385*57696d54SAkhilesh Sanikop // Save the partitions to the specified sector. Used by both the SaveGPTData()
1386*57696d54SAkhilesh Sanikop // and SaveGPTBackup() functions.
1387*57696d54SAkhilesh Sanikop // Should be passed an architecture-appropriate header (DO NOT call
1388*57696d54SAkhilesh Sanikop // ReverseHeaderBytes() on the header before calling this function)
1389*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure
SavePartitionTable(DiskIO & disk,uint64_t sector)1390*57696d54SAkhilesh Sanikop int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1391*57696d54SAkhilesh Sanikop    int littleEndian, allOK = 1;
1392*57696d54SAkhilesh Sanikop 
1393*57696d54SAkhilesh Sanikop    littleEndian = IsLittleEndian();
1394*57696d54SAkhilesh Sanikop    if (disk.Seek(sector)) {
1395*57696d54SAkhilesh Sanikop       if (!littleEndian)
1396*57696d54SAkhilesh Sanikop          ReversePartitionBytes();
1397*57696d54SAkhilesh Sanikop       if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
1398*57696d54SAkhilesh Sanikop          allOK = 0;
1399*57696d54SAkhilesh Sanikop       if (!littleEndian)
1400*57696d54SAkhilesh Sanikop          ReversePartitionBytes();
1401*57696d54SAkhilesh Sanikop    } else allOK = 0; // if (myDisk.Seek()...)
1402*57696d54SAkhilesh Sanikop    return allOK;
1403*57696d54SAkhilesh Sanikop } // GPTData::SavePartitionTable()
1404*57696d54SAkhilesh Sanikop 
1405*57696d54SAkhilesh Sanikop // Load GPT data from a backup file created by SaveGPTBackup(). This function
1406*57696d54SAkhilesh Sanikop // does minimal error checking. It returns 1 if it completed successfully,
1407*57696d54SAkhilesh Sanikop // 0 if there was a problem. In the latter case, it creates a new empty
1408*57696d54SAkhilesh Sanikop // set of partitions.
LoadGPTBackup(const string & filename)1409*57696d54SAkhilesh Sanikop int GPTData::LoadGPTBackup(const string & filename) {
1410*57696d54SAkhilesh Sanikop    int allOK = 1, val, err;
1411*57696d54SAkhilesh Sanikop    int shortBackup = 0;
1412*57696d54SAkhilesh Sanikop    DiskIO backupFile;
1413*57696d54SAkhilesh Sanikop 
1414*57696d54SAkhilesh Sanikop    if (backupFile.OpenForRead(filename)) {
1415*57696d54SAkhilesh Sanikop       // Let the MBRData class load the saved MBR...
1416*57696d54SAkhilesh Sanikop       protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
1417*57696d54SAkhilesh Sanikop       protectiveMBR.SetDisk(&myDisk);
1418*57696d54SAkhilesh Sanikop 
1419*57696d54SAkhilesh Sanikop       LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
1420*57696d54SAkhilesh Sanikop 
1421*57696d54SAkhilesh Sanikop       // Check backup file size and rebuild second header if file is right
1422*57696d54SAkhilesh Sanikop       // size to be direct dd copy of MBR, main header, and main partition
1423*57696d54SAkhilesh Sanikop       // table; if other size, treat it like a GPT fdisk-generated backup
1424*57696d54SAkhilesh Sanikop       // file
1425*57696d54SAkhilesh Sanikop       shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1426*57696d54SAkhilesh Sanikop                      (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1427*57696d54SAkhilesh Sanikop       if (shortBackup) {
1428*57696d54SAkhilesh Sanikop          RebuildSecondHeader();
1429*57696d54SAkhilesh Sanikop          secondCrcOk = mainCrcOk;
1430*57696d54SAkhilesh Sanikop       } else {
1431*57696d54SAkhilesh Sanikop          LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1432*57696d54SAkhilesh Sanikop       } // if/else
1433*57696d54SAkhilesh Sanikop 
1434*57696d54SAkhilesh Sanikop       // Return valid headers code: 0 = both headers bad; 1 = main header
1435*57696d54SAkhilesh Sanikop       // good, backup bad; 2 = backup header good, main header bad;
1436*57696d54SAkhilesh Sanikop       // 3 = both headers good. Note these codes refer to valid GPT
1437*57696d54SAkhilesh Sanikop       // signatures and version numbers; more subtle problems will elude
1438*57696d54SAkhilesh Sanikop       // this check!
1439*57696d54SAkhilesh Sanikop       if ((val = CheckHeaderValidity()) > 0) {
1440*57696d54SAkhilesh Sanikop          if (val == 2) { // only backup header seems to be good
1441*57696d54SAkhilesh Sanikop             SetGPTSize(secondHeader.numParts, 0);
1442*57696d54SAkhilesh Sanikop          } else { // main header is OK
1443*57696d54SAkhilesh Sanikop             SetGPTSize(mainHeader.numParts, 0);
1444*57696d54SAkhilesh Sanikop          } // if/else
1445*57696d54SAkhilesh Sanikop 
1446*57696d54SAkhilesh Sanikop          if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
1447*57696d54SAkhilesh Sanikop             cout << "Warning! Current disk size doesn't match that of the backup!\n"
1448*57696d54SAkhilesh Sanikop                  << "Adjusting sizes to match, but subsequent problems are possible!\n";
1449*57696d54SAkhilesh Sanikop             MoveSecondHeaderToEnd();
1450*57696d54SAkhilesh Sanikop          } // if
1451*57696d54SAkhilesh Sanikop 
1452*57696d54SAkhilesh Sanikop          if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1453*57696d54SAkhilesh Sanikop             cerr << "Warning! Read error " << errno
1454*57696d54SAkhilesh Sanikop                  << " loading partition table; strange behavior now likely!\n";
1455*57696d54SAkhilesh Sanikop       } else {
1456*57696d54SAkhilesh Sanikop          allOK = 0;
1457*57696d54SAkhilesh Sanikop       } // if/else
1458*57696d54SAkhilesh Sanikop       // Something went badly wrong, so blank out partitions
1459*57696d54SAkhilesh Sanikop       if (allOK == 0) {
1460*57696d54SAkhilesh Sanikop          cerr << "Improper backup file! Clearing all partition data!\n";
1461*57696d54SAkhilesh Sanikop          ClearGPTData();
1462*57696d54SAkhilesh Sanikop          protectiveMBR.MakeProtectiveMBR();
1463*57696d54SAkhilesh Sanikop       } // if
1464*57696d54SAkhilesh Sanikop    } else {
1465*57696d54SAkhilesh Sanikop       allOK = 0;
1466*57696d54SAkhilesh Sanikop       cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
1467*57696d54SAkhilesh Sanikop    } // if/else
1468*57696d54SAkhilesh Sanikop 
1469*57696d54SAkhilesh Sanikop    return allOK;
1470*57696d54SAkhilesh Sanikop } // GPTData::LoadGPTBackup()
1471*57696d54SAkhilesh Sanikop 
SaveMBR(void)1472*57696d54SAkhilesh Sanikop int GPTData::SaveMBR(void) {
1473*57696d54SAkhilesh Sanikop    return protectiveMBR.WriteMBRData(&myDisk);
1474*57696d54SAkhilesh Sanikop } // GPTData::SaveMBR()
1475*57696d54SAkhilesh Sanikop 
1476*57696d54SAkhilesh Sanikop // This function destroys the on-disk GPT structures, but NOT the on-disk
1477*57696d54SAkhilesh Sanikop // MBR.
1478*57696d54SAkhilesh Sanikop // Returns 1 if the operation succeeds, 0 if not.
DestroyGPT(void)1479*57696d54SAkhilesh Sanikop int GPTData::DestroyGPT(void) {
1480*57696d54SAkhilesh Sanikop    int sum, tableSize, allOK = 1;
1481*57696d54SAkhilesh Sanikop    uint8_t blankSector[512];
1482*57696d54SAkhilesh Sanikop    uint8_t* emptyTable;
1483*57696d54SAkhilesh Sanikop 
1484*57696d54SAkhilesh Sanikop    memset(blankSector, 0, sizeof(blankSector));
1485*57696d54SAkhilesh Sanikop    ClearGPTData();
1486*57696d54SAkhilesh Sanikop 
1487*57696d54SAkhilesh Sanikop    if (myDisk.OpenForWrite()) {
1488*57696d54SAkhilesh Sanikop       if (!myDisk.Seek(mainHeader.currentLBA))
1489*57696d54SAkhilesh Sanikop          allOK = 0;
1490*57696d54SAkhilesh Sanikop       if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1491*57696d54SAkhilesh Sanikop          cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1492*57696d54SAkhilesh Sanikop          allOK = 0;
1493*57696d54SAkhilesh Sanikop       } // if
1494*57696d54SAkhilesh Sanikop       if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1495*57696d54SAkhilesh Sanikop          allOK = 0;
1496*57696d54SAkhilesh Sanikop       tableSize = numParts * mainHeader.sizeOfPartitionEntries;
1497*57696d54SAkhilesh Sanikop       emptyTable = new uint8_t[tableSize];
1498*57696d54SAkhilesh Sanikop       if (emptyTable == NULL) {
1499*57696d54SAkhilesh Sanikop          cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
1500*57696d54SAkhilesh Sanikop          exit(1);
1501*57696d54SAkhilesh Sanikop       } // if
1502*57696d54SAkhilesh Sanikop       memset(emptyTable, 0, tableSize);
1503*57696d54SAkhilesh Sanikop       if (allOK) {
1504*57696d54SAkhilesh Sanikop          sum = myDisk.Write(emptyTable, tableSize);
1505*57696d54SAkhilesh Sanikop          if (sum != tableSize) {
1506*57696d54SAkhilesh Sanikop             cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1507*57696d54SAkhilesh Sanikop             allOK = 0;
1508*57696d54SAkhilesh Sanikop          } // if write failed
1509*57696d54SAkhilesh Sanikop       } // if
1510*57696d54SAkhilesh Sanikop       if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1511*57696d54SAkhilesh Sanikop          allOK = 0;
1512*57696d54SAkhilesh Sanikop       if (allOK) {
1513*57696d54SAkhilesh Sanikop          sum = myDisk.Write(emptyTable, tableSize);
1514*57696d54SAkhilesh Sanikop          if (sum != tableSize) {
1515*57696d54SAkhilesh Sanikop             cerr << "Warning! GPT backup partition table not overwritten! Error is "
1516*57696d54SAkhilesh Sanikop                  << errno << "\n";
1517*57696d54SAkhilesh Sanikop             allOK = 0;
1518*57696d54SAkhilesh Sanikop          } // if wrong size written
1519*57696d54SAkhilesh Sanikop       } // if
1520*57696d54SAkhilesh Sanikop       if (!myDisk.Seek(secondHeader.currentLBA))
1521*57696d54SAkhilesh Sanikop          allOK = 0;
1522*57696d54SAkhilesh Sanikop       if (allOK) {
1523*57696d54SAkhilesh Sanikop          if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1524*57696d54SAkhilesh Sanikop             cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1525*57696d54SAkhilesh Sanikop             allOK = 0;
1526*57696d54SAkhilesh Sanikop          } // if
1527*57696d54SAkhilesh Sanikop       } // if
1528*57696d54SAkhilesh Sanikop       myDisk.DiskSync();
1529*57696d54SAkhilesh Sanikop       myDisk.Close();
1530*57696d54SAkhilesh Sanikop       cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1531*57696d54SAkhilesh Sanikop            << "other utilities.\n";
1532*57696d54SAkhilesh Sanikop       delete[] emptyTable;
1533*57696d54SAkhilesh Sanikop    } else {
1534*57696d54SAkhilesh Sanikop       cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
1535*57696d54SAkhilesh Sanikop    } // if/else (fd != -1)
1536*57696d54SAkhilesh Sanikop    return (allOK);
1537*57696d54SAkhilesh Sanikop } // GPTDataTextUI::DestroyGPT()
1538*57696d54SAkhilesh Sanikop 
1539*57696d54SAkhilesh Sanikop // Wipe MBR data from the disk (zero it out completely)
1540*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure.
DestroyMBR(void)1541*57696d54SAkhilesh Sanikop int GPTData::DestroyMBR(void) {
1542*57696d54SAkhilesh Sanikop    int allOK;
1543*57696d54SAkhilesh Sanikop    uint8_t blankSector[512];
1544*57696d54SAkhilesh Sanikop 
1545*57696d54SAkhilesh Sanikop    memset(blankSector, 0, sizeof(blankSector));
1546*57696d54SAkhilesh Sanikop 
1547*57696d54SAkhilesh Sanikop    allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1548*57696d54SAkhilesh Sanikop 
1549*57696d54SAkhilesh Sanikop    if (!allOK)
1550*57696d54SAkhilesh Sanikop       cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1551*57696d54SAkhilesh Sanikop    return allOK;
1552*57696d54SAkhilesh Sanikop } // GPTData::DestroyMBR(void)
1553*57696d54SAkhilesh Sanikop 
1554*57696d54SAkhilesh Sanikop // Tell user whether Apple Partition Map (APM) was discovered....
ShowAPMState(void)1555*57696d54SAkhilesh Sanikop void GPTData::ShowAPMState(void) {
1556*57696d54SAkhilesh Sanikop    if (apmFound)
1557*57696d54SAkhilesh Sanikop       cout << "  APM: present\n";
1558*57696d54SAkhilesh Sanikop    else
1559*57696d54SAkhilesh Sanikop       cout << "  APM: not present\n";
1560*57696d54SAkhilesh Sanikop } // GPTData::ShowAPMState()
1561*57696d54SAkhilesh Sanikop 
1562*57696d54SAkhilesh Sanikop // Tell user about the state of the GPT data....
ShowGPTState(void)1563*57696d54SAkhilesh Sanikop void GPTData::ShowGPTState(void) {
1564*57696d54SAkhilesh Sanikop    switch (state) {
1565*57696d54SAkhilesh Sanikop       case gpt_invalid:
1566*57696d54SAkhilesh Sanikop          cout << "  GPT: not present\n";
1567*57696d54SAkhilesh Sanikop          break;
1568*57696d54SAkhilesh Sanikop       case gpt_valid:
1569*57696d54SAkhilesh Sanikop          cout << "  GPT: present\n";
1570*57696d54SAkhilesh Sanikop          break;
1571*57696d54SAkhilesh Sanikop       case gpt_corrupt:
1572*57696d54SAkhilesh Sanikop          cout << "  GPT: damaged\n";
1573*57696d54SAkhilesh Sanikop          break;
1574*57696d54SAkhilesh Sanikop       default:
1575*57696d54SAkhilesh Sanikop          cout << "\a  GPT: unknown -- bug!\n";
1576*57696d54SAkhilesh Sanikop          break;
1577*57696d54SAkhilesh Sanikop    } // switch
1578*57696d54SAkhilesh Sanikop } // GPTData::ShowGPTState()
1579*57696d54SAkhilesh Sanikop 
1580*57696d54SAkhilesh Sanikop // Display the basic GPT data
DisplayGPTData(void)1581*57696d54SAkhilesh Sanikop void GPTData::DisplayGPTData(void) {
1582*57696d54SAkhilesh Sanikop    uint32_t i;
1583*57696d54SAkhilesh Sanikop    uint64_t temp, totalFree;
1584*57696d54SAkhilesh Sanikop 
1585*57696d54SAkhilesh Sanikop    cout << "Disk " << device << ": " << diskSize << " sectors, "
1586*57696d54SAkhilesh Sanikop         << BytesToIeee(diskSize, blockSize) << "\n";
1587*57696d54SAkhilesh Sanikop    if (myDisk.GetModel() != "")
1588*57696d54SAkhilesh Sanikop       cout << "Model: " << myDisk.GetModel() << "\n";
1589*57696d54SAkhilesh Sanikop    if (physBlockSize > 0)
1590*57696d54SAkhilesh Sanikop       cout << "Sector size (logical/physical): " << blockSize << "/" << physBlockSize << " bytes\n";
1591*57696d54SAkhilesh Sanikop    else
1592*57696d54SAkhilesh Sanikop       cout << "Sector size (logical): " << blockSize << " bytes\n";
1593*57696d54SAkhilesh Sanikop    cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
1594*57696d54SAkhilesh Sanikop    cout << "Partition table holds up to " << numParts << " entries\n";
1595*57696d54SAkhilesh Sanikop    cout << "Main partition table begins at sector " << mainHeader.partitionEntriesLBA
1596*57696d54SAkhilesh Sanikop         << " and ends at sector " << mainHeader.partitionEntriesLBA + GetTableSizeInSectors() - 1 << "\n";
1597*57696d54SAkhilesh Sanikop    cout << "First usable sector is " << mainHeader.firstUsableLBA
1598*57696d54SAkhilesh Sanikop         << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
1599*57696d54SAkhilesh Sanikop    totalFree = FindFreeBlocks(&i, &temp);
1600*57696d54SAkhilesh Sanikop    cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
1601*57696d54SAkhilesh Sanikop    cout << "Total free space is " << totalFree << " sectors ("
1602*57696d54SAkhilesh Sanikop         << BytesToIeee(totalFree, blockSize) << ")\n";
1603*57696d54SAkhilesh Sanikop    cout << "\nNumber  Start (sector)    End (sector)  Size       Code  Name\n";
1604*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
1605*57696d54SAkhilesh Sanikop       partitions[i].ShowSummary(i, blockSize);
1606*57696d54SAkhilesh Sanikop    } // for
1607*57696d54SAkhilesh Sanikop } // GPTData::DisplayGPTData()
1608*57696d54SAkhilesh Sanikop 
1609*57696d54SAkhilesh Sanikop // Show detailed information on the specified partition
ShowPartDetails(uint32_t partNum)1610*57696d54SAkhilesh Sanikop void GPTData::ShowPartDetails(uint32_t partNum) {
1611*57696d54SAkhilesh Sanikop    if ((partNum < numParts) && !IsFreePartNum(partNum)) {
1612*57696d54SAkhilesh Sanikop       partitions[partNum].ShowDetails(blockSize);
1613*57696d54SAkhilesh Sanikop    } else {
1614*57696d54SAkhilesh Sanikop       cout << "Partition #" << partNum + 1 << " does not exist.\n";
1615*57696d54SAkhilesh Sanikop    } // if
1616*57696d54SAkhilesh Sanikop } // GPTData::ShowPartDetails()
1617*57696d54SAkhilesh Sanikop 
1618*57696d54SAkhilesh Sanikop /**************************************************************************
1619*57696d54SAkhilesh Sanikop  *                                                                        *
1620*57696d54SAkhilesh Sanikop  * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1621*57696d54SAkhilesh Sanikop  * (some of these functions may require user interaction)                 *
1622*57696d54SAkhilesh Sanikop  *                                                                        *
1623*57696d54SAkhilesh Sanikop  **************************************************************************/
1624*57696d54SAkhilesh Sanikop 
1625*57696d54SAkhilesh Sanikop // Examines the MBR & GPT data to determine which set of data to use: the
1626*57696d54SAkhilesh Sanikop // MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1627*57696d54SAkhilesh Sanikop // a new set of partitions (use_new). A return value of use_abort indicates
1628*57696d54SAkhilesh Sanikop // that this function couldn't determine what to do. Overriding functions
1629*57696d54SAkhilesh Sanikop // in derived classes may ask users questions in such cases.
UseWhichPartitions(void)1630*57696d54SAkhilesh Sanikop WhichToUse GPTData::UseWhichPartitions(void) {
1631*57696d54SAkhilesh Sanikop    WhichToUse which = use_new;
1632*57696d54SAkhilesh Sanikop    MBRValidity mbrState;
1633*57696d54SAkhilesh Sanikop 
1634*57696d54SAkhilesh Sanikop    mbrState = protectiveMBR.GetValidity();
1635*57696d54SAkhilesh Sanikop 
1636*57696d54SAkhilesh Sanikop    if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
1637*57696d54SAkhilesh Sanikop       cout << "\n***************************************************************\n"
1638*57696d54SAkhilesh Sanikop            << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1639*57696d54SAkhilesh Sanikop            << "in memory. ";
1640*57696d54SAkhilesh Sanikop       if (!justLooking) {
1641*57696d54SAkhilesh Sanikop          cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1642*57696d54SAkhilesh Sanikop               << "typing 'q' if you don't want to convert your MBR partitions\n"
1643*57696d54SAkhilesh Sanikop               << "to GPT format!";
1644*57696d54SAkhilesh Sanikop       } // if
1645*57696d54SAkhilesh Sanikop       cout << "\n***************************************************************\n\n";
1646*57696d54SAkhilesh Sanikop       which = use_mbr;
1647*57696d54SAkhilesh Sanikop    } // if
1648*57696d54SAkhilesh Sanikop 
1649*57696d54SAkhilesh Sanikop    if ((state == gpt_invalid) && bsdFound) {
1650*57696d54SAkhilesh Sanikop       cout << "\n**********************************************************************\n"
1651*57696d54SAkhilesh Sanikop            << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1652*57696d54SAkhilesh Sanikop            << "to GPT format.";
1653*57696d54SAkhilesh Sanikop       if ((!justLooking) && (!beQuiet)) {
1654*57696d54SAkhilesh Sanikop       cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
1655*57696d54SAkhilesh Sanikop            << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1656*57696d54SAkhilesh Sanikop            << "want to convert your BSD partitions to GPT format!";
1657*57696d54SAkhilesh Sanikop       } // if
1658*57696d54SAkhilesh Sanikop       cout << "\n**********************************************************************\n\n";
1659*57696d54SAkhilesh Sanikop       which = use_bsd;
1660*57696d54SAkhilesh Sanikop    } // if
1661*57696d54SAkhilesh Sanikop 
1662*57696d54SAkhilesh Sanikop    if ((state == gpt_valid) && (mbrState == gpt)) {
1663*57696d54SAkhilesh Sanikop       which = use_gpt;
1664*57696d54SAkhilesh Sanikop       if (!beQuiet)
1665*57696d54SAkhilesh Sanikop          cout << "Found valid GPT with protective MBR; using GPT.\n";
1666*57696d54SAkhilesh Sanikop    } // if
1667*57696d54SAkhilesh Sanikop    if ((state == gpt_valid) && (mbrState == hybrid)) {
1668*57696d54SAkhilesh Sanikop       which = use_gpt;
1669*57696d54SAkhilesh Sanikop       if (!beQuiet)
1670*57696d54SAkhilesh Sanikop          cout << "Found valid GPT with hybrid MBR; using GPT.\n";
1671*57696d54SAkhilesh Sanikop    } // if
1672*57696d54SAkhilesh Sanikop    if ((state == gpt_valid) && (mbrState == invalid)) {
1673*57696d54SAkhilesh Sanikop       cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
1674*57696d54SAkhilesh Sanikop            << "protective MBR on save.\n";
1675*57696d54SAkhilesh Sanikop       which = use_gpt;
1676*57696d54SAkhilesh Sanikop    } // if
1677*57696d54SAkhilesh Sanikop    if ((state == gpt_valid) && (mbrState == mbr)) {
1678*57696d54SAkhilesh Sanikop       which = use_abort;
1679*57696d54SAkhilesh Sanikop    } // if
1680*57696d54SAkhilesh Sanikop 
1681*57696d54SAkhilesh Sanikop    if (state == gpt_corrupt) {
1682*57696d54SAkhilesh Sanikop       if (mbrState == gpt) {
1683*57696d54SAkhilesh Sanikop          cout << "\a\a****************************************************************************\n"
1684*57696d54SAkhilesh Sanikop               << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1685*57696d54SAkhilesh Sanikop               << "verification and recovery are STRONGLY recommended.\n"
1686*57696d54SAkhilesh Sanikop               << "****************************************************************************\n";
1687*57696d54SAkhilesh Sanikop          which = use_gpt;
1688*57696d54SAkhilesh Sanikop       } else {
1689*57696d54SAkhilesh Sanikop          which = use_abort;
1690*57696d54SAkhilesh Sanikop       } // if/else MBR says disk is GPT
1691*57696d54SAkhilesh Sanikop    } // if GPT corrupt
1692*57696d54SAkhilesh Sanikop 
1693*57696d54SAkhilesh Sanikop    if (which == use_new)
1694*57696d54SAkhilesh Sanikop       cout << "Creating new GPT entries in memory.\n";
1695*57696d54SAkhilesh Sanikop 
1696*57696d54SAkhilesh Sanikop    return which;
1697*57696d54SAkhilesh Sanikop } // UseWhichPartitions()
1698*57696d54SAkhilesh Sanikop 
1699*57696d54SAkhilesh Sanikop // Convert MBR partition table into GPT form.
XFormPartitions(void)1700*57696d54SAkhilesh Sanikop void GPTData::XFormPartitions(void) {
1701*57696d54SAkhilesh Sanikop    int i, numToConvert;
1702*57696d54SAkhilesh Sanikop    uint8_t origType;
1703*57696d54SAkhilesh Sanikop 
1704*57696d54SAkhilesh Sanikop    // Clear out old data & prepare basics....
1705*57696d54SAkhilesh Sanikop    ClearGPTData();
1706*57696d54SAkhilesh Sanikop 
1707*57696d54SAkhilesh Sanikop    // Convert the smaller of the # of GPT or MBR partitions
1708*57696d54SAkhilesh Sanikop    if (numParts > MAX_MBR_PARTS)
1709*57696d54SAkhilesh Sanikop       numToConvert = MAX_MBR_PARTS;
1710*57696d54SAkhilesh Sanikop    else
1711*57696d54SAkhilesh Sanikop       numToConvert = numParts;
1712*57696d54SAkhilesh Sanikop 
1713*57696d54SAkhilesh Sanikop    for (i = 0; i < numToConvert; i++) {
1714*57696d54SAkhilesh Sanikop       origType = protectiveMBR.GetType(i);
1715*57696d54SAkhilesh Sanikop       // don't waste CPU time trying to convert extended, hybrid protective, or
1716*57696d54SAkhilesh Sanikop       // null (non-existent) partitions
1717*57696d54SAkhilesh Sanikop       if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
1718*57696d54SAkhilesh Sanikop           (origType != 0x00) && (origType != 0xEE))
1719*57696d54SAkhilesh Sanikop          partitions[i] = protectiveMBR.AsGPT(i);
1720*57696d54SAkhilesh Sanikop    } // for
1721*57696d54SAkhilesh Sanikop 
1722*57696d54SAkhilesh Sanikop    // Convert MBR into protective MBR
1723*57696d54SAkhilesh Sanikop    protectiveMBR.MakeProtectiveMBR();
1724*57696d54SAkhilesh Sanikop 
1725*57696d54SAkhilesh Sanikop    // Record that all original CRCs were OK so as not to raise flags
1726*57696d54SAkhilesh Sanikop    // when doing a disk verification
1727*57696d54SAkhilesh Sanikop    mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1728*57696d54SAkhilesh Sanikop } // GPTData::XFormPartitions()
1729*57696d54SAkhilesh Sanikop 
1730*57696d54SAkhilesh Sanikop // Transforms BSD disklabel on the specified partition (numbered from 0).
1731*57696d54SAkhilesh Sanikop // If an invalid partition number is given, the program does nothing.
1732*57696d54SAkhilesh Sanikop // Returns the number of new partitions created.
XFormDisklabel(uint32_t partNum)1733*57696d54SAkhilesh Sanikop int GPTData::XFormDisklabel(uint32_t partNum) {
1734*57696d54SAkhilesh Sanikop    uint32_t low, high;
1735*57696d54SAkhilesh Sanikop    int goOn = 1, numDone = 0;
1736*57696d54SAkhilesh Sanikop    BSDData disklabel;
1737*57696d54SAkhilesh Sanikop 
1738*57696d54SAkhilesh Sanikop    if (GetPartRange(&low, &high) == 0) {
1739*57696d54SAkhilesh Sanikop       goOn = 0;
1740*57696d54SAkhilesh Sanikop       cout << "No partitions!\n";
1741*57696d54SAkhilesh Sanikop    } // if
1742*57696d54SAkhilesh Sanikop    if (partNum > high) {
1743*57696d54SAkhilesh Sanikop       goOn = 0;
1744*57696d54SAkhilesh Sanikop       cout << "Specified partition is invalid!\n";
1745*57696d54SAkhilesh Sanikop    } // if
1746*57696d54SAkhilesh Sanikop 
1747*57696d54SAkhilesh Sanikop    // If all is OK, read the disklabel and convert it.
1748*57696d54SAkhilesh Sanikop    if (goOn) {
1749*57696d54SAkhilesh Sanikop       goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1750*57696d54SAkhilesh Sanikop                                    partitions[partNum].GetLastLBA());
1751*57696d54SAkhilesh Sanikop       if ((goOn) && (disklabel.IsDisklabel())) {
1752*57696d54SAkhilesh Sanikop          numDone = XFormDisklabel(&disklabel);
1753*57696d54SAkhilesh Sanikop          if (numDone == 1)
1754*57696d54SAkhilesh Sanikop             cout << "Converted 1 BSD partition.\n";
1755*57696d54SAkhilesh Sanikop          else
1756*57696d54SAkhilesh Sanikop             cout << "Converted " << numDone << " BSD partitions.\n";
1757*57696d54SAkhilesh Sanikop       } else {
1758*57696d54SAkhilesh Sanikop          cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1759*57696d54SAkhilesh Sanikop       } // if/else
1760*57696d54SAkhilesh Sanikop    } // if
1761*57696d54SAkhilesh Sanikop    if (numDone > 0) { // converted partitions; delete carrier
1762*57696d54SAkhilesh Sanikop       partitions[partNum].BlankPartition();
1763*57696d54SAkhilesh Sanikop    } // if
1764*57696d54SAkhilesh Sanikop    return numDone;
1765*57696d54SAkhilesh Sanikop } // GPTData::XFormDisklabel(uint32_t i)
1766*57696d54SAkhilesh Sanikop 
1767*57696d54SAkhilesh Sanikop // Transform the partitions on an already-loaded BSD disklabel...
XFormDisklabel(BSDData * disklabel)1768*57696d54SAkhilesh Sanikop int GPTData::XFormDisklabel(BSDData* disklabel) {
1769*57696d54SAkhilesh Sanikop    int i, partNum = 0, numDone = 0;
1770*57696d54SAkhilesh Sanikop 
1771*57696d54SAkhilesh Sanikop    if (disklabel->IsDisklabel()) {
1772*57696d54SAkhilesh Sanikop       for (i = 0; i < disklabel->GetNumParts(); i++) {
1773*57696d54SAkhilesh Sanikop          partNum = FindFirstFreePart();
1774*57696d54SAkhilesh Sanikop          if (partNum >= 0) {
1775*57696d54SAkhilesh Sanikop             partitions[partNum] = disklabel->AsGPT(i);
1776*57696d54SAkhilesh Sanikop             if (partitions[partNum].IsUsed())
1777*57696d54SAkhilesh Sanikop                numDone++;
1778*57696d54SAkhilesh Sanikop          } // if
1779*57696d54SAkhilesh Sanikop       } // for
1780*57696d54SAkhilesh Sanikop       if (partNum == -1)
1781*57696d54SAkhilesh Sanikop          cerr << "Warning! Too many partitions to convert!\n";
1782*57696d54SAkhilesh Sanikop    } // if
1783*57696d54SAkhilesh Sanikop 
1784*57696d54SAkhilesh Sanikop    // Record that all original CRCs were OK so as not to raise flags
1785*57696d54SAkhilesh Sanikop    // when doing a disk verification
1786*57696d54SAkhilesh Sanikop    mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1787*57696d54SAkhilesh Sanikop 
1788*57696d54SAkhilesh Sanikop    return numDone;
1789*57696d54SAkhilesh Sanikop } // GPTData::XFormDisklabel(BSDData* disklabel)
1790*57696d54SAkhilesh Sanikop 
1791*57696d54SAkhilesh Sanikop // Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1792*57696d54SAkhilesh Sanikop // partition has the active/bootable flag UNset and uses the GPT fdisk
1793*57696d54SAkhilesh Sanikop // type code divided by 0x0100 as the MBR type code.
1794*57696d54SAkhilesh Sanikop // Returns 1 if operation was 100% successful, 0 if there were ANY
1795*57696d54SAkhilesh Sanikop // problems.
OnePartToMBR(uint32_t gptPart,int mbrPart)1796*57696d54SAkhilesh Sanikop int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1797*57696d54SAkhilesh Sanikop    int allOK = 1;
1798*57696d54SAkhilesh Sanikop 
1799*57696d54SAkhilesh Sanikop    if ((mbrPart < 0) || (mbrPart > 3)) {
1800*57696d54SAkhilesh Sanikop       cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
1801*57696d54SAkhilesh Sanikop       allOK = 0;
1802*57696d54SAkhilesh Sanikop    } // if
1803*57696d54SAkhilesh Sanikop    if (gptPart >= numParts) {
1804*57696d54SAkhilesh Sanikop       cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
1805*57696d54SAkhilesh Sanikop       allOK = 0;
1806*57696d54SAkhilesh Sanikop    } // if
1807*57696d54SAkhilesh Sanikop    if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
1808*57696d54SAkhilesh Sanikop       cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
1809*57696d54SAkhilesh Sanikop       allOK = 0;
1810*57696d54SAkhilesh Sanikop    } // if
1811*57696d54SAkhilesh Sanikop    if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1812*57696d54SAkhilesh Sanikop        (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1813*57696d54SAkhilesh Sanikop       if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
1814*57696d54SAkhilesh Sanikop          cout << "Caution: Partition end point past 32-bit pointer boundary;"
1815*57696d54SAkhilesh Sanikop               << " some OSes may\nreact strangely.\n";
1816*57696d54SAkhilesh Sanikop       } // if
1817*57696d54SAkhilesh Sanikop       protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1818*57696d54SAkhilesh Sanikop                              (uint32_t) partitions[gptPart].GetLengthLBA(),
1819*57696d54SAkhilesh Sanikop                              partitions[gptPart].GetHexType() / 256, 0);
1820*57696d54SAkhilesh Sanikop    } else { // partition out of range
1821*57696d54SAkhilesh Sanikop       if (allOK) // Display only if "else" triggered by out-of-bounds condition
1822*57696d54SAkhilesh Sanikop          cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1823*57696d54SAkhilesh Sanikop               << "partitions, or is\n too big; omitting it.\n";
1824*57696d54SAkhilesh Sanikop       allOK = 0;
1825*57696d54SAkhilesh Sanikop    } // if/else
1826*57696d54SAkhilesh Sanikop    return allOK;
1827*57696d54SAkhilesh Sanikop } // GPTData::OnePartToMBR()
1828*57696d54SAkhilesh Sanikop 
1829*57696d54SAkhilesh Sanikop 
1830*57696d54SAkhilesh Sanikop /**********************************************************************
1831*57696d54SAkhilesh Sanikop  *                                                                    *
1832*57696d54SAkhilesh Sanikop  * Functions that adjust GPT data structures WITHOUT user interaction *
1833*57696d54SAkhilesh Sanikop  * (they may display information for the user's benefit, though)      *
1834*57696d54SAkhilesh Sanikop  *                                                                    *
1835*57696d54SAkhilesh Sanikop  **********************************************************************/
1836*57696d54SAkhilesh Sanikop 
1837*57696d54SAkhilesh Sanikop // Resizes GPT to specified number of entries. Creates a new table if
1838*57696d54SAkhilesh Sanikop // necessary, copies data if it already exists. If fillGPTSectors is 1
1839*57696d54SAkhilesh Sanikop // (the default), rounds numEntries to fill all the sectors necessary to
1840*57696d54SAkhilesh Sanikop // hold the GPT.
1841*57696d54SAkhilesh Sanikop // Returns 1 if all goes well, 0 if an error is encountered.
SetGPTSize(uint32_t numEntries,int fillGPTSectors)1842*57696d54SAkhilesh Sanikop int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
1843*57696d54SAkhilesh Sanikop    GPTPart* newParts;
1844*57696d54SAkhilesh Sanikop    uint32_t i, high, copyNum, entriesPerSector;
1845*57696d54SAkhilesh Sanikop    int allOK = 1;
1846*57696d54SAkhilesh Sanikop 
1847*57696d54SAkhilesh Sanikop    // First, adjust numEntries upward, if necessary, to get a number
1848*57696d54SAkhilesh Sanikop    // that fills the allocated sectors
1849*57696d54SAkhilesh Sanikop    entriesPerSector = blockSize / GPT_SIZE;
1850*57696d54SAkhilesh Sanikop    if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
1851*57696d54SAkhilesh Sanikop       cout << "Adjusting GPT size from " << numEntries << " to ";
1852*57696d54SAkhilesh Sanikop       numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
1853*57696d54SAkhilesh Sanikop       cout << numEntries << " to fill the sector\n";
1854*57696d54SAkhilesh Sanikop    } // if
1855*57696d54SAkhilesh Sanikop 
1856*57696d54SAkhilesh Sanikop    // Do the work only if the # of partitions is changing. Along with being
1857*57696d54SAkhilesh Sanikop    // efficient, this prevents mucking with the location of the secondary
1858*57696d54SAkhilesh Sanikop    // partition table, which causes problems when loading data from a RAID
1859*57696d54SAkhilesh Sanikop    // array that's been expanded because this function is called when loading
1860*57696d54SAkhilesh Sanikop    // data.
1861*57696d54SAkhilesh Sanikop    if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
1862*57696d54SAkhilesh Sanikop       newParts = new GPTPart [numEntries];
1863*57696d54SAkhilesh Sanikop       if (newParts != NULL) {
1864*57696d54SAkhilesh Sanikop          if (partitions != NULL) { // existing partitions; copy them over
1865*57696d54SAkhilesh Sanikop             GetPartRange(&i, &high);
1866*57696d54SAkhilesh Sanikop             if (numEntries < (high + 1)) { // Highest entry too high for new #
1867*57696d54SAkhilesh Sanikop                cout << "The highest-numbered partition is " << high + 1
1868*57696d54SAkhilesh Sanikop                     << ", which is greater than the requested\n"
1869*57696d54SAkhilesh Sanikop                     << "partition table size of " << numEntries
1870*57696d54SAkhilesh Sanikop                     << "; cannot resize. Perhaps sorting will help.\n";
1871*57696d54SAkhilesh Sanikop                allOK = 0;
1872*57696d54SAkhilesh Sanikop                delete[] newParts;
1873*57696d54SAkhilesh Sanikop             } else { // go ahead with copy
1874*57696d54SAkhilesh Sanikop                if (numEntries < numParts)
1875*57696d54SAkhilesh Sanikop                   copyNum = numEntries;
1876*57696d54SAkhilesh Sanikop                else
1877*57696d54SAkhilesh Sanikop                   copyNum = numParts;
1878*57696d54SAkhilesh Sanikop                for (i = 0; i < copyNum; i++) {
1879*57696d54SAkhilesh Sanikop                   newParts[i] = partitions[i];
1880*57696d54SAkhilesh Sanikop                } // for
1881*57696d54SAkhilesh Sanikop                delete[] partitions;
1882*57696d54SAkhilesh Sanikop                partitions = newParts;
1883*57696d54SAkhilesh Sanikop             } // if
1884*57696d54SAkhilesh Sanikop          } else { // No existing partition table; just create it
1885*57696d54SAkhilesh Sanikop             partitions = newParts;
1886*57696d54SAkhilesh Sanikop          } // if/else existing partitions
1887*57696d54SAkhilesh Sanikop          numParts = numEntries;
1888*57696d54SAkhilesh Sanikop          mainHeader.firstUsableLBA = GetTableSizeInSectors() + mainHeader.partitionEntriesLBA;
1889*57696d54SAkhilesh Sanikop          secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1890*57696d54SAkhilesh Sanikop          MoveSecondHeaderToEnd();
1891*57696d54SAkhilesh Sanikop          if (diskSize > 0)
1892*57696d54SAkhilesh Sanikop             CheckGPTSize();
1893*57696d54SAkhilesh Sanikop       } else { // Bad memory allocation
1894*57696d54SAkhilesh Sanikop          cerr << "Error allocating memory for partition table! Size is unchanged!\n";
1895*57696d54SAkhilesh Sanikop          allOK = 0;
1896*57696d54SAkhilesh Sanikop       } // if/else
1897*57696d54SAkhilesh Sanikop    } // if/else
1898*57696d54SAkhilesh Sanikop    mainHeader.numParts = numParts;
1899*57696d54SAkhilesh Sanikop    secondHeader.numParts = numParts;
1900*57696d54SAkhilesh Sanikop    return (allOK);
1901*57696d54SAkhilesh Sanikop } // GPTData::SetGPTSize()
1902*57696d54SAkhilesh Sanikop 
1903*57696d54SAkhilesh Sanikop // Change the start sector for the main partition table.
1904*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure
MoveMainTable(uint64_t pteSector)1905*57696d54SAkhilesh Sanikop int GPTData::MoveMainTable(uint64_t pteSector) {
1906*57696d54SAkhilesh Sanikop     uint64_t pteSize = GetTableSizeInSectors();
1907*57696d54SAkhilesh Sanikop     int retval = 1;
1908*57696d54SAkhilesh Sanikop 
1909*57696d54SAkhilesh Sanikop     if ((pteSector >= 2) && ((pteSector + pteSize) <= FindFirstUsedLBA())) {
1910*57696d54SAkhilesh Sanikop        mainHeader.partitionEntriesLBA = pteSector;
1911*57696d54SAkhilesh Sanikop        mainHeader.firstUsableLBA = pteSector + pteSize;
1912*57696d54SAkhilesh Sanikop        RebuildSecondHeader();
1913*57696d54SAkhilesh Sanikop     } else {
1914*57696d54SAkhilesh Sanikop        cerr << "Unable to set the main partition table's location to " << pteSector << "!\n";
1915*57696d54SAkhilesh Sanikop        retval = 0;
1916*57696d54SAkhilesh Sanikop     } // if/else
1917*57696d54SAkhilesh Sanikop     return retval;
1918*57696d54SAkhilesh Sanikop } // GPTData::MoveMainTable()
1919*57696d54SAkhilesh Sanikop 
1920*57696d54SAkhilesh Sanikop // Blank the partition array
BlankPartitions(void)1921*57696d54SAkhilesh Sanikop void GPTData::BlankPartitions(void) {
1922*57696d54SAkhilesh Sanikop    uint32_t i;
1923*57696d54SAkhilesh Sanikop 
1924*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
1925*57696d54SAkhilesh Sanikop       partitions[i].BlankPartition();
1926*57696d54SAkhilesh Sanikop    } // for
1927*57696d54SAkhilesh Sanikop } // GPTData::BlankPartitions()
1928*57696d54SAkhilesh Sanikop 
1929*57696d54SAkhilesh Sanikop // Delete a partition by number. Returns 1 if successful,
1930*57696d54SAkhilesh Sanikop // 0 if there was a problem. Returns 1 if partition was in
1931*57696d54SAkhilesh Sanikop // range, 0 if it was out of range.
DeletePartition(uint32_t partNum)1932*57696d54SAkhilesh Sanikop int GPTData::DeletePartition(uint32_t partNum) {
1933*57696d54SAkhilesh Sanikop    uint64_t startSector, length;
1934*57696d54SAkhilesh Sanikop    uint32_t low, high, numUsedParts, retval = 1;;
1935*57696d54SAkhilesh Sanikop 
1936*57696d54SAkhilesh Sanikop    numUsedParts = GetPartRange(&low, &high);
1937*57696d54SAkhilesh Sanikop    if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
1938*57696d54SAkhilesh Sanikop       // In case there's a protective MBR, look for & delete matching
1939*57696d54SAkhilesh Sanikop       // MBR partition....
1940*57696d54SAkhilesh Sanikop       startSector = partitions[partNum].GetFirstLBA();
1941*57696d54SAkhilesh Sanikop       length = partitions[partNum].GetLengthLBA();
1942*57696d54SAkhilesh Sanikop       protectiveMBR.DeleteByLocation(startSector, length);
1943*57696d54SAkhilesh Sanikop 
1944*57696d54SAkhilesh Sanikop       // Now delete the GPT partition
1945*57696d54SAkhilesh Sanikop       partitions[partNum].BlankPartition();
1946*57696d54SAkhilesh Sanikop    } else {
1947*57696d54SAkhilesh Sanikop       cerr << "Partition number " << partNum + 1 << " out of range!\n";
1948*57696d54SAkhilesh Sanikop       retval = 0;
1949*57696d54SAkhilesh Sanikop    } // if/else
1950*57696d54SAkhilesh Sanikop    return retval;
1951*57696d54SAkhilesh Sanikop } // GPTData::DeletePartition(uint32_t partNum)
1952*57696d54SAkhilesh Sanikop 
1953*57696d54SAkhilesh Sanikop // Non-interactively create a partition.
1954*57696d54SAkhilesh Sanikop // Returns 1 if the operation was successful, 0 if a problem was discovered.
CreatePartition(uint32_t partNum,uint64_t startSector,uint64_t endSector)1955*57696d54SAkhilesh Sanikop uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
1956*57696d54SAkhilesh Sanikop    int retval = 1; // assume there'll be no problems
1957*57696d54SAkhilesh Sanikop    uint64_t origSector = startSector;
1958*57696d54SAkhilesh Sanikop 
1959*57696d54SAkhilesh Sanikop    if (IsFreePartNum(partNum)) {
1960*57696d54SAkhilesh Sanikop       if (Align(&startSector)) {
1961*57696d54SAkhilesh Sanikop          cout << "Information: Moved requested sector from " << origSector << " to "
1962*57696d54SAkhilesh Sanikop               << startSector << " in\norder to align on " << sectorAlignment
1963*57696d54SAkhilesh Sanikop               << "-sector boundaries.\n";
1964*57696d54SAkhilesh Sanikop       } // if
1965*57696d54SAkhilesh Sanikop       if (IsFree(startSector) && (startSector <= endSector)) {
1966*57696d54SAkhilesh Sanikop          if (FindLastInFree(startSector) >= endSector) {
1967*57696d54SAkhilesh Sanikop             partitions[partNum].SetFirstLBA(startSector);
1968*57696d54SAkhilesh Sanikop             partitions[partNum].SetLastLBA(endSector);
1969*57696d54SAkhilesh Sanikop             partitions[partNum].SetType(DEFAULT_GPT_TYPE);
1970*57696d54SAkhilesh Sanikop             partitions[partNum].RandomizeUniqueGUID();
1971*57696d54SAkhilesh Sanikop          } else retval = 0; // if free space until endSector
1972*57696d54SAkhilesh Sanikop       } else retval = 0; // if startSector is free
1973*57696d54SAkhilesh Sanikop    } else retval = 0; // if legal partition number
1974*57696d54SAkhilesh Sanikop    return retval;
1975*57696d54SAkhilesh Sanikop } // GPTData::CreatePartition(partNum, startSector, endSector)
1976*57696d54SAkhilesh Sanikop 
1977*57696d54SAkhilesh Sanikop // Sort the GPT entries, eliminating gaps and making for a logical
1978*57696d54SAkhilesh Sanikop // ordering.
SortGPT(void)1979*57696d54SAkhilesh Sanikop void GPTData::SortGPT(void) {
1980*57696d54SAkhilesh Sanikop    if (numParts > 0)
1981*57696d54SAkhilesh Sanikop       sort(partitions, partitions + numParts);
1982*57696d54SAkhilesh Sanikop } // GPTData::SortGPT()
1983*57696d54SAkhilesh Sanikop 
1984*57696d54SAkhilesh Sanikop // Swap the contents of two partitions.
1985*57696d54SAkhilesh Sanikop // Returns 1 if successful, 0 if either partition is out of range
1986*57696d54SAkhilesh Sanikop // (that is, not a legal number; either or both can be empty).
1987*57696d54SAkhilesh Sanikop // Note that if partNum1 = partNum2 and this number is in range,
1988*57696d54SAkhilesh Sanikop // it will be considered successful.
SwapPartitions(uint32_t partNum1,uint32_t partNum2)1989*57696d54SAkhilesh Sanikop int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1990*57696d54SAkhilesh Sanikop    GPTPart temp;
1991*57696d54SAkhilesh Sanikop    int allOK = 1;
1992*57696d54SAkhilesh Sanikop 
1993*57696d54SAkhilesh Sanikop    if ((partNum1 < numParts) && (partNum2 < numParts)) {
1994*57696d54SAkhilesh Sanikop       if (partNum1 != partNum2) {
1995*57696d54SAkhilesh Sanikop          temp = partitions[partNum1];
1996*57696d54SAkhilesh Sanikop          partitions[partNum1] = partitions[partNum2];
1997*57696d54SAkhilesh Sanikop          partitions[partNum2] = temp;
1998*57696d54SAkhilesh Sanikop       } // if
1999*57696d54SAkhilesh Sanikop    } else allOK = 0; // partition numbers are valid
2000*57696d54SAkhilesh Sanikop    return allOK;
2001*57696d54SAkhilesh Sanikop } // GPTData::SwapPartitions()
2002*57696d54SAkhilesh Sanikop 
2003*57696d54SAkhilesh Sanikop // Set up data structures for entirely new set of partitions on the
2004*57696d54SAkhilesh Sanikop // specified device. Returns 1 if OK, 0 if there were problems.
2005*57696d54SAkhilesh Sanikop // Note that this function does NOT clear the protectiveMBR data
2006*57696d54SAkhilesh Sanikop // structure, since it may hold the original MBR partitions if the
2007*57696d54SAkhilesh Sanikop // program was launched on an MBR disk, and those may need to be
2008*57696d54SAkhilesh Sanikop // converted to GPT format.
ClearGPTData(void)2009*57696d54SAkhilesh Sanikop int GPTData::ClearGPTData(void) {
2010*57696d54SAkhilesh Sanikop    int goOn = 1, i;
2011*57696d54SAkhilesh Sanikop 
2012*57696d54SAkhilesh Sanikop    // Set up the partition table....
2013*57696d54SAkhilesh Sanikop    delete[] partitions;
2014*57696d54SAkhilesh Sanikop    partitions = NULL;
2015*57696d54SAkhilesh Sanikop    SetGPTSize(NUM_GPT_ENTRIES);
2016*57696d54SAkhilesh Sanikop 
2017*57696d54SAkhilesh Sanikop    // Now initialize a bunch of stuff that's static....
2018*57696d54SAkhilesh Sanikop    mainHeader.signature = GPT_SIGNATURE;
2019*57696d54SAkhilesh Sanikop    mainHeader.revision = 0x00010000;
2020*57696d54SAkhilesh Sanikop    mainHeader.headerSize = HEADER_SIZE;
2021*57696d54SAkhilesh Sanikop    mainHeader.reserved = 0;
2022*57696d54SAkhilesh Sanikop    mainHeader.currentLBA = UINT64_C(1);
2023*57696d54SAkhilesh Sanikop    mainHeader.partitionEntriesLBA = (uint64_t) 2;
2024*57696d54SAkhilesh Sanikop    mainHeader.sizeOfPartitionEntries = GPT_SIZE;
2025*57696d54SAkhilesh Sanikop    mainHeader.firstUsableLBA = GetTableSizeInSectors() + mainHeader.partitionEntriesLBA;
2026*57696d54SAkhilesh Sanikop    for (i = 0; i < GPT_RESERVED; i++) {
2027*57696d54SAkhilesh Sanikop       mainHeader.reserved2[i] = '\0';
2028*57696d54SAkhilesh Sanikop    } // for
2029*57696d54SAkhilesh Sanikop    if (blockSize > 0)
2030*57696d54SAkhilesh Sanikop       sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2031*57696d54SAkhilesh Sanikop    else
2032*57696d54SAkhilesh Sanikop       sectorAlignment = DEFAULT_ALIGNMENT;
2033*57696d54SAkhilesh Sanikop 
2034*57696d54SAkhilesh Sanikop    // Now some semi-static items (computed based on end of disk)
2035*57696d54SAkhilesh Sanikop    mainHeader.backupLBA = diskSize - UINT64_C(1);
2036*57696d54SAkhilesh Sanikop    mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2037*57696d54SAkhilesh Sanikop 
2038*57696d54SAkhilesh Sanikop    // Set a unique GUID for the disk, based on random numbers
2039*57696d54SAkhilesh Sanikop    mainHeader.diskGUID.Randomize();
2040*57696d54SAkhilesh Sanikop 
2041*57696d54SAkhilesh Sanikop    // Copy main header to backup header
2042*57696d54SAkhilesh Sanikop    RebuildSecondHeader();
2043*57696d54SAkhilesh Sanikop 
2044*57696d54SAkhilesh Sanikop    // Blank out the partitions array....
2045*57696d54SAkhilesh Sanikop    BlankPartitions();
2046*57696d54SAkhilesh Sanikop 
2047*57696d54SAkhilesh Sanikop    // Flag all CRCs as being OK....
2048*57696d54SAkhilesh Sanikop    mainCrcOk = 1;
2049*57696d54SAkhilesh Sanikop    secondCrcOk = 1;
2050*57696d54SAkhilesh Sanikop    mainPartsCrcOk = 1;
2051*57696d54SAkhilesh Sanikop    secondPartsCrcOk = 1;
2052*57696d54SAkhilesh Sanikop 
2053*57696d54SAkhilesh Sanikop    return (goOn);
2054*57696d54SAkhilesh Sanikop } // GPTData::ClearGPTData()
2055*57696d54SAkhilesh Sanikop 
2056*57696d54SAkhilesh Sanikop // Set the location of the second GPT header data to the end of the disk.
2057*57696d54SAkhilesh Sanikop // If the disk size has actually changed, this also adjusts the protective
2058*57696d54SAkhilesh Sanikop // entry in the MBR, since it's probably no longer correct.
2059*57696d54SAkhilesh Sanikop // Used internally and called by the 'e' option on the recovery &
2060*57696d54SAkhilesh Sanikop // transformation menu, to help users of RAID arrays who add disk space
2061*57696d54SAkhilesh Sanikop // to their arrays or to adjust data structures in restore operations
2062*57696d54SAkhilesh Sanikop // involving unequal-sized disks.
MoveSecondHeaderToEnd()2063*57696d54SAkhilesh Sanikop void GPTData::MoveSecondHeaderToEnd() {
2064*57696d54SAkhilesh Sanikop    mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
2065*57696d54SAkhilesh Sanikop    if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
2066*57696d54SAkhilesh Sanikop       if (protectiveMBR.GetValidity() == hybrid) {
2067*57696d54SAkhilesh Sanikop          protectiveMBR.OptimizeEESize();
2068*57696d54SAkhilesh Sanikop          RecomputeCHS();
2069*57696d54SAkhilesh Sanikop       } // if
2070*57696d54SAkhilesh Sanikop       if (protectiveMBR.GetValidity() == gpt)
2071*57696d54SAkhilesh Sanikop          MakeProtectiveMBR();
2072*57696d54SAkhilesh Sanikop    } // if
2073*57696d54SAkhilesh Sanikop    mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
2074*57696d54SAkhilesh Sanikop    secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
2075*57696d54SAkhilesh Sanikop } // GPTData::FixSecondHeaderLocation()
2076*57696d54SAkhilesh Sanikop 
2077*57696d54SAkhilesh Sanikop // Sets the partition's name to the specified UnicodeString without
2078*57696d54SAkhilesh Sanikop // user interaction.
2079*57696d54SAkhilesh Sanikop // Returns 1 on success, 0 on failure (invalid partition number).
SetName(uint32_t partNum,const UnicodeString & theName)2080*57696d54SAkhilesh Sanikop int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
2081*57696d54SAkhilesh Sanikop    int retval = 1;
2082*57696d54SAkhilesh Sanikop 
2083*57696d54SAkhilesh Sanikop    if (IsUsedPartNum(partNum))
2084*57696d54SAkhilesh Sanikop       partitions[partNum].SetName(theName);
2085*57696d54SAkhilesh Sanikop    else
2086*57696d54SAkhilesh Sanikop       retval = 0;
2087*57696d54SAkhilesh Sanikop 
2088*57696d54SAkhilesh Sanikop    return retval;
2089*57696d54SAkhilesh Sanikop } // GPTData::SetName
2090*57696d54SAkhilesh Sanikop 
2091*57696d54SAkhilesh Sanikop // Set the disk GUID to the specified value. Note that the header CRCs must
2092*57696d54SAkhilesh Sanikop // be recomputed after calling this function.
SetDiskGUID(GUIDData newGUID)2093*57696d54SAkhilesh Sanikop void GPTData::SetDiskGUID(GUIDData newGUID) {
2094*57696d54SAkhilesh Sanikop    mainHeader.diskGUID = newGUID;
2095*57696d54SAkhilesh Sanikop    secondHeader.diskGUID = newGUID;
2096*57696d54SAkhilesh Sanikop } // SetDiskGUID()
2097*57696d54SAkhilesh Sanikop 
2098*57696d54SAkhilesh Sanikop // Set the unique GUID of the specified partition. Returns 1 on
2099*57696d54SAkhilesh Sanikop // successful completion, 0 if there were problems (invalid
2100*57696d54SAkhilesh Sanikop // partition number).
SetPartitionGUID(uint32_t pn,GUIDData theGUID)2101*57696d54SAkhilesh Sanikop int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
2102*57696d54SAkhilesh Sanikop    int retval = 0;
2103*57696d54SAkhilesh Sanikop 
2104*57696d54SAkhilesh Sanikop    if (pn < numParts) {
2105*57696d54SAkhilesh Sanikop       if (partitions[pn].IsUsed()) {
2106*57696d54SAkhilesh Sanikop          partitions[pn].SetUniqueGUID(theGUID);
2107*57696d54SAkhilesh Sanikop          retval = 1;
2108*57696d54SAkhilesh Sanikop       } // if
2109*57696d54SAkhilesh Sanikop    } // if
2110*57696d54SAkhilesh Sanikop    return retval;
2111*57696d54SAkhilesh Sanikop } // GPTData::SetPartitionGUID()
2112*57696d54SAkhilesh Sanikop 
2113*57696d54SAkhilesh Sanikop // Set new random GUIDs for the disk and all partitions. Intended to be used
2114*57696d54SAkhilesh Sanikop // after disk cloning or similar operations that don't randomize the GUIDs.
RandomizeGUIDs(void)2115*57696d54SAkhilesh Sanikop void GPTData::RandomizeGUIDs(void) {
2116*57696d54SAkhilesh Sanikop    uint32_t i;
2117*57696d54SAkhilesh Sanikop 
2118*57696d54SAkhilesh Sanikop    mainHeader.diskGUID.Randomize();
2119*57696d54SAkhilesh Sanikop    secondHeader.diskGUID = mainHeader.diskGUID;
2120*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++)
2121*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed())
2122*57696d54SAkhilesh Sanikop          partitions[i].RandomizeUniqueGUID();
2123*57696d54SAkhilesh Sanikop } // GPTData::RandomizeGUIDs()
2124*57696d54SAkhilesh Sanikop 
2125*57696d54SAkhilesh Sanikop // Change partition type code non-interactively. Returns 1 if
2126*57696d54SAkhilesh Sanikop // successful, 0 if not....
ChangePartType(uint32_t partNum,PartType theGUID)2127*57696d54SAkhilesh Sanikop int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
2128*57696d54SAkhilesh Sanikop    int retval = 1;
2129*57696d54SAkhilesh Sanikop 
2130*57696d54SAkhilesh Sanikop    if (!IsFreePartNum(partNum)) {
2131*57696d54SAkhilesh Sanikop       partitions[partNum].SetType(theGUID);
2132*57696d54SAkhilesh Sanikop    } else retval = 0;
2133*57696d54SAkhilesh Sanikop    return retval;
2134*57696d54SAkhilesh Sanikop } // GPTData::ChangePartType()
2135*57696d54SAkhilesh Sanikop 
2136*57696d54SAkhilesh Sanikop // Recompute the CHS values of all the MBR partitions. Used to reset
2137*57696d54SAkhilesh Sanikop // CHS values that some BIOSes require, despite the fact that the
2138*57696d54SAkhilesh Sanikop // resulting CHS values violate the GPT standard.
RecomputeCHS(void)2139*57696d54SAkhilesh Sanikop void GPTData::RecomputeCHS(void) {
2140*57696d54SAkhilesh Sanikop    int i;
2141*57696d54SAkhilesh Sanikop 
2142*57696d54SAkhilesh Sanikop    for (i = 0; i < 4; i++)
2143*57696d54SAkhilesh Sanikop       protectiveMBR.RecomputeCHS(i);
2144*57696d54SAkhilesh Sanikop } // GPTData::RecomputeCHS()
2145*57696d54SAkhilesh Sanikop 
2146*57696d54SAkhilesh Sanikop // Adjust sector number so that it falls on a sector boundary that's a
2147*57696d54SAkhilesh Sanikop // multiple of sectorAlignment. This is done to improve the performance
2148*57696d54SAkhilesh Sanikop // of Western Digital Advanced Format disks and disks with similar
2149*57696d54SAkhilesh Sanikop // technology from other companies, which use 4096-byte sectors
2150*57696d54SAkhilesh Sanikop // internally although they translate to 512-byte sectors for the
2151*57696d54SAkhilesh Sanikop // benefit of the OS. If partitions aren't properly aligned on these
2152*57696d54SAkhilesh Sanikop // disks, some filesystem data structures can span multiple physical
2153*57696d54SAkhilesh Sanikop // sectors, degrading performance. This function should be called
2154*57696d54SAkhilesh Sanikop // only on the FIRST sector of the partition, not the last!
2155*57696d54SAkhilesh Sanikop // This function returns 1 if the alignment was altered, 0 if it
2156*57696d54SAkhilesh Sanikop // was unchanged.
Align(uint64_t * sector)2157*57696d54SAkhilesh Sanikop int GPTData::Align(uint64_t* sector) {
2158*57696d54SAkhilesh Sanikop    int retval = 0, sectorOK = 0;
2159*57696d54SAkhilesh Sanikop    uint64_t earlier, later, testSector;
2160*57696d54SAkhilesh Sanikop 
2161*57696d54SAkhilesh Sanikop    if ((*sector % sectorAlignment) != 0) {
2162*57696d54SAkhilesh Sanikop       earlier = (*sector / sectorAlignment) * sectorAlignment;
2163*57696d54SAkhilesh Sanikop       later = earlier + (uint64_t) sectorAlignment;
2164*57696d54SAkhilesh Sanikop 
2165*57696d54SAkhilesh Sanikop       // Check to see that every sector between the earlier one and the
2166*57696d54SAkhilesh Sanikop       // requested one is clear, and that it's not too early....
2167*57696d54SAkhilesh Sanikop       if (earlier >= mainHeader.firstUsableLBA) {
2168*57696d54SAkhilesh Sanikop          testSector = earlier;
2169*57696d54SAkhilesh Sanikop          do {
2170*57696d54SAkhilesh Sanikop             sectorOK = IsFree(testSector++);
2171*57696d54SAkhilesh Sanikop          } while ((sectorOK == 1) && (testSector < *sector));
2172*57696d54SAkhilesh Sanikop          if (sectorOK == 1) {
2173*57696d54SAkhilesh Sanikop             *sector = earlier;
2174*57696d54SAkhilesh Sanikop             retval = 1;
2175*57696d54SAkhilesh Sanikop          } // if
2176*57696d54SAkhilesh Sanikop       } // if firstUsableLBA check
2177*57696d54SAkhilesh Sanikop 
2178*57696d54SAkhilesh Sanikop       // If couldn't move the sector earlier, try to move it later instead....
2179*57696d54SAkhilesh Sanikop       if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2180*57696d54SAkhilesh Sanikop          testSector = later;
2181*57696d54SAkhilesh Sanikop          do {
2182*57696d54SAkhilesh Sanikop             sectorOK = IsFree(testSector--);
2183*57696d54SAkhilesh Sanikop          } while ((sectorOK == 1) && (testSector > *sector));
2184*57696d54SAkhilesh Sanikop          if (sectorOK == 1) {
2185*57696d54SAkhilesh Sanikop             *sector = later;
2186*57696d54SAkhilesh Sanikop             retval = 1;
2187*57696d54SAkhilesh Sanikop          } // if
2188*57696d54SAkhilesh Sanikop       } // if
2189*57696d54SAkhilesh Sanikop    } // if
2190*57696d54SAkhilesh Sanikop    return retval;
2191*57696d54SAkhilesh Sanikop } // GPTData::Align()
2192*57696d54SAkhilesh Sanikop 
2193*57696d54SAkhilesh Sanikop /********************************************************
2194*57696d54SAkhilesh Sanikop  *                                                      *
2195*57696d54SAkhilesh Sanikop  * Functions that return data about GPT data structures *
2196*57696d54SAkhilesh Sanikop  * (most of these are inline in gpt.h)                  *
2197*57696d54SAkhilesh Sanikop  *                                                      *
2198*57696d54SAkhilesh Sanikop  ********************************************************/
2199*57696d54SAkhilesh Sanikop 
2200*57696d54SAkhilesh Sanikop // Find the low and high used partition numbers (numbered from 0).
2201*57696d54SAkhilesh Sanikop // Return value is the number of partitions found. Note that the
2202*57696d54SAkhilesh Sanikop // *low and *high values are both set to 0 when no partitions
2203*57696d54SAkhilesh Sanikop // are found, as well as when a single partition in the first
2204*57696d54SAkhilesh Sanikop // position exists. Thus, the return value is the only way to
2205*57696d54SAkhilesh Sanikop // tell when no partitions exist.
GetPartRange(uint32_t * low,uint32_t * high)2206*57696d54SAkhilesh Sanikop int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2207*57696d54SAkhilesh Sanikop    uint32_t i;
2208*57696d54SAkhilesh Sanikop    int numFound = 0;
2209*57696d54SAkhilesh Sanikop 
2210*57696d54SAkhilesh Sanikop    *low = numParts + 1; // code for "not found"
2211*57696d54SAkhilesh Sanikop    *high = 0;
2212*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2213*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed()) { // it exists
2214*57696d54SAkhilesh Sanikop          *high = i; // since we're counting up, set the high value
2215*57696d54SAkhilesh Sanikop          // Set the low value only if it's not yet found...
2216*57696d54SAkhilesh Sanikop          if (*low == (numParts + 1)) *low = i;
2217*57696d54SAkhilesh Sanikop             numFound++;
2218*57696d54SAkhilesh Sanikop       } // if
2219*57696d54SAkhilesh Sanikop    } // for
2220*57696d54SAkhilesh Sanikop 
2221*57696d54SAkhilesh Sanikop    // Above will leave *low pointing to its "not found" value if no partitions
2222*57696d54SAkhilesh Sanikop    // are defined, so reset to 0 if this is the case....
2223*57696d54SAkhilesh Sanikop    if (*low == (numParts + 1))
2224*57696d54SAkhilesh Sanikop       *low = 0;
2225*57696d54SAkhilesh Sanikop    return numFound;
2226*57696d54SAkhilesh Sanikop } // GPTData::GetPartRange()
2227*57696d54SAkhilesh Sanikop 
2228*57696d54SAkhilesh Sanikop // Returns the value of the first free partition, or -1 if none is
2229*57696d54SAkhilesh Sanikop // unused.
FindFirstFreePart(void)2230*57696d54SAkhilesh Sanikop int GPTData::FindFirstFreePart(void) {
2231*57696d54SAkhilesh Sanikop    int i = 0;
2232*57696d54SAkhilesh Sanikop 
2233*57696d54SAkhilesh Sanikop    if (partitions != NULL) {
2234*57696d54SAkhilesh Sanikop       while ((i < (int) numParts) && (partitions[i].IsUsed()))
2235*57696d54SAkhilesh Sanikop          i++;
2236*57696d54SAkhilesh Sanikop       if (i >= (int) numParts)
2237*57696d54SAkhilesh Sanikop          i = -1;
2238*57696d54SAkhilesh Sanikop    } else i = -1;
2239*57696d54SAkhilesh Sanikop    return i;
2240*57696d54SAkhilesh Sanikop } // GPTData::FindFirstFreePart()
2241*57696d54SAkhilesh Sanikop 
2242*57696d54SAkhilesh Sanikop // Returns the number of defined partitions.
CountParts(void)2243*57696d54SAkhilesh Sanikop uint32_t GPTData::CountParts(void) {
2244*57696d54SAkhilesh Sanikop    uint32_t i, counted = 0;
2245*57696d54SAkhilesh Sanikop 
2246*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2247*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed())
2248*57696d54SAkhilesh Sanikop          counted++;
2249*57696d54SAkhilesh Sanikop    } // for
2250*57696d54SAkhilesh Sanikop    return counted;
2251*57696d54SAkhilesh Sanikop } // GPTData::CountParts()
2252*57696d54SAkhilesh Sanikop 
2253*57696d54SAkhilesh Sanikop /****************************************************
2254*57696d54SAkhilesh Sanikop  *                                                  *
2255*57696d54SAkhilesh Sanikop  * Functions that return data about disk free space *
2256*57696d54SAkhilesh Sanikop  *                                                  *
2257*57696d54SAkhilesh Sanikop  ****************************************************/
2258*57696d54SAkhilesh Sanikop 
2259*57696d54SAkhilesh Sanikop // Find the first available block after the starting point; returns 0 if
2260*57696d54SAkhilesh Sanikop // there are no available blocks left
FindFirstAvailable(uint64_t start)2261*57696d54SAkhilesh Sanikop uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2262*57696d54SAkhilesh Sanikop    uint64_t first;
2263*57696d54SAkhilesh Sanikop    uint32_t i;
2264*57696d54SAkhilesh Sanikop    int firstMoved = 0;
2265*57696d54SAkhilesh Sanikop 
2266*57696d54SAkhilesh Sanikop    // Begin from the specified starting point or from the first usable
2267*57696d54SAkhilesh Sanikop    // LBA, whichever is greater...
2268*57696d54SAkhilesh Sanikop    if (start < mainHeader.firstUsableLBA)
2269*57696d54SAkhilesh Sanikop       first = mainHeader.firstUsableLBA;
2270*57696d54SAkhilesh Sanikop    else
2271*57696d54SAkhilesh Sanikop       first = start;
2272*57696d54SAkhilesh Sanikop 
2273*57696d54SAkhilesh Sanikop    // ...now search through all partitions; if first is within an
2274*57696d54SAkhilesh Sanikop    // existing partition, move it to the next sector after that
2275*57696d54SAkhilesh Sanikop    // partition and repeat. If first was moved, set firstMoved
2276*57696d54SAkhilesh Sanikop    // flag; repeat until firstMoved is not set, so as to catch
2277*57696d54SAkhilesh Sanikop    // cases where partitions are out of sequential order....
2278*57696d54SAkhilesh Sanikop    do {
2279*57696d54SAkhilesh Sanikop       firstMoved = 0;
2280*57696d54SAkhilesh Sanikop       for (i = 0; i < numParts; i++) {
2281*57696d54SAkhilesh Sanikop          if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
2282*57696d54SAkhilesh Sanikop              (first <= partitions[i].GetLastLBA())) { // in existing part.
2283*57696d54SAkhilesh Sanikop             first = partitions[i].GetLastLBA() + 1;
2284*57696d54SAkhilesh Sanikop             firstMoved = 1;
2285*57696d54SAkhilesh Sanikop          } // if
2286*57696d54SAkhilesh Sanikop       } // for
2287*57696d54SAkhilesh Sanikop    } while (firstMoved == 1);
2288*57696d54SAkhilesh Sanikop    if (first > mainHeader.lastUsableLBA)
2289*57696d54SAkhilesh Sanikop       first = 0;
2290*57696d54SAkhilesh Sanikop    return (first);
2291*57696d54SAkhilesh Sanikop } // GPTData::FindFirstAvailable()
2292*57696d54SAkhilesh Sanikop 
2293*57696d54SAkhilesh Sanikop // Returns the LBA of the start of the first partition on the disk (by
2294*57696d54SAkhilesh Sanikop // sector number), or 0 if there are no partitions defined.
FindFirstUsedLBA(void)2295*57696d54SAkhilesh Sanikop uint64_t GPTData::FindFirstUsedLBA(void) {
2296*57696d54SAkhilesh Sanikop     uint32_t i;
2297*57696d54SAkhilesh Sanikop     uint64_t firstFound = UINT64_MAX;
2298*57696d54SAkhilesh Sanikop 
2299*57696d54SAkhilesh Sanikop     for (i = 0; i < numParts; i++) {
2300*57696d54SAkhilesh Sanikop         if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() < firstFound)) {
2301*57696d54SAkhilesh Sanikop             firstFound = partitions[i].GetFirstLBA();
2302*57696d54SAkhilesh Sanikop         } // if
2303*57696d54SAkhilesh Sanikop     } // for
2304*57696d54SAkhilesh Sanikop     return firstFound;
2305*57696d54SAkhilesh Sanikop } // GPTData::FindFirstUsedLBA()
2306*57696d54SAkhilesh Sanikop 
2307*57696d54SAkhilesh Sanikop // Finds the first available sector in the largest block of unallocated
2308*57696d54SAkhilesh Sanikop // space on the disk. Returns 0 if there are no available blocks left
FindFirstInLargest(void)2309*57696d54SAkhilesh Sanikop uint64_t GPTData::FindFirstInLargest(void) {
2310*57696d54SAkhilesh Sanikop    uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
2311*57696d54SAkhilesh Sanikop 
2312*57696d54SAkhilesh Sanikop    start = 0;
2313*57696d54SAkhilesh Sanikop    do {
2314*57696d54SAkhilesh Sanikop       firstBlock = FindFirstAvailable(start);
2315*57696d54SAkhilesh Sanikop       if (firstBlock != UINT32_C(0)) { // something's free...
2316*57696d54SAkhilesh Sanikop          lastBlock = FindLastInFree(firstBlock);
2317*57696d54SAkhilesh Sanikop          segmentSize = lastBlock - firstBlock + UINT32_C(1);
2318*57696d54SAkhilesh Sanikop          if (segmentSize > selectedSize) {
2319*57696d54SAkhilesh Sanikop             selectedSize = segmentSize;
2320*57696d54SAkhilesh Sanikop             selectedSegment = firstBlock;
2321*57696d54SAkhilesh Sanikop          } // if
2322*57696d54SAkhilesh Sanikop          start = lastBlock + 1;
2323*57696d54SAkhilesh Sanikop       } // if
2324*57696d54SAkhilesh Sanikop    } while (firstBlock != 0);
2325*57696d54SAkhilesh Sanikop    return selectedSegment;
2326*57696d54SAkhilesh Sanikop } // GPTData::FindFirstInLargest()
2327*57696d54SAkhilesh Sanikop 
2328*57696d54SAkhilesh Sanikop // Find the last available block on the disk.
2329*57696d54SAkhilesh Sanikop // Returns 0 if there are no available sectors
FindLastAvailable(void)2330*57696d54SAkhilesh Sanikop uint64_t GPTData::FindLastAvailable(void) {
2331*57696d54SAkhilesh Sanikop    uint64_t last;
2332*57696d54SAkhilesh Sanikop    uint32_t i;
2333*57696d54SAkhilesh Sanikop    int lastMoved = 0;
2334*57696d54SAkhilesh Sanikop 
2335*57696d54SAkhilesh Sanikop    // Start by assuming the last usable LBA is available....
2336*57696d54SAkhilesh Sanikop    last = mainHeader.lastUsableLBA;
2337*57696d54SAkhilesh Sanikop 
2338*57696d54SAkhilesh Sanikop    // ...now, similar to algorithm in FindFirstAvailable(), search
2339*57696d54SAkhilesh Sanikop    // through all partitions, moving last when it's in an existing
2340*57696d54SAkhilesh Sanikop    // partition. Set the lastMoved flag so we repeat to catch cases
2341*57696d54SAkhilesh Sanikop    // where partitions are out of logical order.
2342*57696d54SAkhilesh Sanikop    do {
2343*57696d54SAkhilesh Sanikop       lastMoved = 0;
2344*57696d54SAkhilesh Sanikop       for (i = 0; i < numParts; i++) {
2345*57696d54SAkhilesh Sanikop          if ((last >= partitions[i].GetFirstLBA()) &&
2346*57696d54SAkhilesh Sanikop              (last <= partitions[i].GetLastLBA())) { // in existing part.
2347*57696d54SAkhilesh Sanikop             last = partitions[i].GetFirstLBA() - 1;
2348*57696d54SAkhilesh Sanikop             lastMoved = 1;
2349*57696d54SAkhilesh Sanikop          } // if
2350*57696d54SAkhilesh Sanikop       } // for
2351*57696d54SAkhilesh Sanikop    } while (lastMoved == 1);
2352*57696d54SAkhilesh Sanikop    if (last < mainHeader.firstUsableLBA)
2353*57696d54SAkhilesh Sanikop       last = 0;
2354*57696d54SAkhilesh Sanikop    return (last);
2355*57696d54SAkhilesh Sanikop } // GPTData::FindLastAvailable()
2356*57696d54SAkhilesh Sanikop 
2357*57696d54SAkhilesh Sanikop // Find the last available block in the free space pointed to by start.
2358*57696d54SAkhilesh Sanikop // If align == true, returns the last sector that's aligned on the
2359*57696d54SAkhilesh Sanikop // system alignment value (unless that's less than the start value);
2360*57696d54SAkhilesh Sanikop // if align == false, returns the last available block regardless of
2361*57696d54SAkhilesh Sanikop // alignment. (The align variable is set to false by default.)
FindLastInFree(uint64_t start,bool align)2362*57696d54SAkhilesh Sanikop uint64_t GPTData::FindLastInFree(uint64_t start, bool align) {
2363*57696d54SAkhilesh Sanikop    uint64_t nearestEnd, endPlus;
2364*57696d54SAkhilesh Sanikop    uint32_t i;
2365*57696d54SAkhilesh Sanikop 
2366*57696d54SAkhilesh Sanikop    nearestEnd = mainHeader.lastUsableLBA;
2367*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2368*57696d54SAkhilesh Sanikop       if ((nearestEnd > partitions[i].GetFirstLBA()) &&
2369*57696d54SAkhilesh Sanikop           (partitions[i].GetFirstLBA() > start)) {
2370*57696d54SAkhilesh Sanikop          nearestEnd = partitions[i].GetFirstLBA() - 1;
2371*57696d54SAkhilesh Sanikop       } // if
2372*57696d54SAkhilesh Sanikop    } // for
2373*57696d54SAkhilesh Sanikop    if (align) {
2374*57696d54SAkhilesh Sanikop        endPlus = nearestEnd + 1;
2375*57696d54SAkhilesh Sanikop        if (Align(&endPlus) && IsFree(endPlus - 1) && (endPlus > start)) {
2376*57696d54SAkhilesh Sanikop            nearestEnd = endPlus - 1;
2377*57696d54SAkhilesh Sanikop        } // if
2378*57696d54SAkhilesh Sanikop    } // if
2379*57696d54SAkhilesh Sanikop    return (nearestEnd);
2380*57696d54SAkhilesh Sanikop } // GPTData::FindLastInFree()
2381*57696d54SAkhilesh Sanikop 
2382*57696d54SAkhilesh Sanikop // Finds the total number of free blocks, the number of segments in which
2383*57696d54SAkhilesh Sanikop // they reside, and the size of the largest of those segments
FindFreeBlocks(uint32_t * numSegments,uint64_t * largestSegment)2384*57696d54SAkhilesh Sanikop uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
2385*57696d54SAkhilesh Sanikop    uint64_t start = UINT64_C(0); // starting point for each search
2386*57696d54SAkhilesh Sanikop    uint64_t totalFound = UINT64_C(0); // running total
2387*57696d54SAkhilesh Sanikop    uint64_t firstBlock; // first block in a segment
2388*57696d54SAkhilesh Sanikop    uint64_t lastBlock; // last block in a segment
2389*57696d54SAkhilesh Sanikop    uint64_t segmentSize; // size of segment in blocks
2390*57696d54SAkhilesh Sanikop    uint32_t num = 0;
2391*57696d54SAkhilesh Sanikop 
2392*57696d54SAkhilesh Sanikop    *largestSegment = UINT64_C(0);
2393*57696d54SAkhilesh Sanikop    if (diskSize > 0) {
2394*57696d54SAkhilesh Sanikop       do {
2395*57696d54SAkhilesh Sanikop          firstBlock = FindFirstAvailable(start);
2396*57696d54SAkhilesh Sanikop          if (firstBlock != UINT64_C(0)) { // something's free...
2397*57696d54SAkhilesh Sanikop             lastBlock = FindLastInFree(firstBlock);
2398*57696d54SAkhilesh Sanikop             segmentSize = lastBlock - firstBlock + UINT64_C(1);
2399*57696d54SAkhilesh Sanikop             if (segmentSize > *largestSegment) {
2400*57696d54SAkhilesh Sanikop                *largestSegment = segmentSize;
2401*57696d54SAkhilesh Sanikop             } // if
2402*57696d54SAkhilesh Sanikop             totalFound += segmentSize;
2403*57696d54SAkhilesh Sanikop             num++;
2404*57696d54SAkhilesh Sanikop             start = lastBlock + 1;
2405*57696d54SAkhilesh Sanikop          } // if
2406*57696d54SAkhilesh Sanikop       } while (firstBlock != 0);
2407*57696d54SAkhilesh Sanikop    } // if
2408*57696d54SAkhilesh Sanikop    *numSegments = num;
2409*57696d54SAkhilesh Sanikop    return totalFound;
2410*57696d54SAkhilesh Sanikop } // GPTData::FindFreeBlocks()
2411*57696d54SAkhilesh Sanikop 
2412*57696d54SAkhilesh Sanikop // Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2413*57696d54SAkhilesh Sanikop // If it's allocated, return the partition number to which it's allocated
2414*57696d54SAkhilesh Sanikop // in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2415*57696d54SAkhilesh Sanikop // returned in partNum if the sector is in use by basic GPT data structures.)
IsFree(uint64_t sector,uint32_t * partNum)2416*57696d54SAkhilesh Sanikop int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
2417*57696d54SAkhilesh Sanikop    int isFree = 1;
2418*57696d54SAkhilesh Sanikop    uint32_t i;
2419*57696d54SAkhilesh Sanikop 
2420*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2421*57696d54SAkhilesh Sanikop       if ((sector >= partitions[i].GetFirstLBA()) &&
2422*57696d54SAkhilesh Sanikop            (sector <= partitions[i].GetLastLBA())) {
2423*57696d54SAkhilesh Sanikop          isFree = 0;
2424*57696d54SAkhilesh Sanikop          if (partNum != NULL)
2425*57696d54SAkhilesh Sanikop             *partNum = i;
2426*57696d54SAkhilesh Sanikop       } // if
2427*57696d54SAkhilesh Sanikop    } // for
2428*57696d54SAkhilesh Sanikop    if ((sector < mainHeader.firstUsableLBA) ||
2429*57696d54SAkhilesh Sanikop         (sector > mainHeader.lastUsableLBA)) {
2430*57696d54SAkhilesh Sanikop       isFree = 0;
2431*57696d54SAkhilesh Sanikop       if (partNum != NULL)
2432*57696d54SAkhilesh Sanikop          *partNum = UINT32_MAX;
2433*57696d54SAkhilesh Sanikop    } // if
2434*57696d54SAkhilesh Sanikop    return (isFree);
2435*57696d54SAkhilesh Sanikop } // GPTData::IsFree()
2436*57696d54SAkhilesh Sanikop 
2437*57696d54SAkhilesh Sanikop // Returns 1 if partNum is unused AND if it's a legal value.
IsFreePartNum(uint32_t partNum)2438*57696d54SAkhilesh Sanikop int GPTData::IsFreePartNum(uint32_t partNum) {
2439*57696d54SAkhilesh Sanikop    return ((partNum < numParts) && (partitions != NULL) &&
2440*57696d54SAkhilesh Sanikop            (!partitions[partNum].IsUsed()));
2441*57696d54SAkhilesh Sanikop } // GPTData::IsFreePartNum()
2442*57696d54SAkhilesh Sanikop 
2443*57696d54SAkhilesh Sanikop // Returns 1 if partNum is in use.
IsUsedPartNum(uint32_t partNum)2444*57696d54SAkhilesh Sanikop int GPTData::IsUsedPartNum(uint32_t partNum) {
2445*57696d54SAkhilesh Sanikop    return ((partNum < numParts) && (partitions != NULL) &&
2446*57696d54SAkhilesh Sanikop            (partitions[partNum].IsUsed()));
2447*57696d54SAkhilesh Sanikop } // GPTData::IsUsedPartNum()
2448*57696d54SAkhilesh Sanikop 
2449*57696d54SAkhilesh Sanikop /***********************************************************
2450*57696d54SAkhilesh Sanikop  *                                                         *
2451*57696d54SAkhilesh Sanikop  * Change how functions work or return information on them *
2452*57696d54SAkhilesh Sanikop  *                                                         *
2453*57696d54SAkhilesh Sanikop  ***********************************************************/
2454*57696d54SAkhilesh Sanikop 
2455*57696d54SAkhilesh Sanikop // Set partition alignment value; partitions will begin on multiples of
2456*57696d54SAkhilesh Sanikop // the specified value, and the default end values will be set so that
2457*57696d54SAkhilesh Sanikop // partition sizes are multiples of this value in cgdisk and gdisk, too.
2458*57696d54SAkhilesh Sanikop // (In sgdisk, end-alignment is done only if the '-I' command-line option
2459*57696d54SAkhilesh Sanikop // is used.)
SetAlignment(uint32_t n)2460*57696d54SAkhilesh Sanikop void GPTData::SetAlignment(uint32_t n) {
2461*57696d54SAkhilesh Sanikop    if (n > 0) {
2462*57696d54SAkhilesh Sanikop       sectorAlignment = n;
2463*57696d54SAkhilesh Sanikop       if ((physBlockSize > 0) && (n % (physBlockSize / blockSize) != 0)) {
2464*57696d54SAkhilesh Sanikop          cout << "Warning: Setting alignment to a value that does not match the disk's\n"
2465*57696d54SAkhilesh Sanikop               << "physical block size! Performance degradation may result!\n"
2466*57696d54SAkhilesh Sanikop               << "Physical block size = " << physBlockSize << "\n"
2467*57696d54SAkhilesh Sanikop               << "Logical block size = " << blockSize << "\n"
2468*57696d54SAkhilesh Sanikop               << "Optimal alignment = " << physBlockSize / blockSize << " or multiples thereof.\n";
2469*57696d54SAkhilesh Sanikop       } // if
2470*57696d54SAkhilesh Sanikop    } else {
2471*57696d54SAkhilesh Sanikop       cerr << "Attempt to set partition alignment to 0!\n";
2472*57696d54SAkhilesh Sanikop    } // if/else
2473*57696d54SAkhilesh Sanikop } // GPTData::SetAlignment()
2474*57696d54SAkhilesh Sanikop 
2475*57696d54SAkhilesh Sanikop // Compute sector alignment based on the current partitions (if any). Each
2476*57696d54SAkhilesh Sanikop // partition's starting LBA is examined, and if it's divisible by a power-of-2
2477*57696d54SAkhilesh Sanikop // value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2478*57696d54SAkhilesh Sanikop // sector size), but not by the previously-located alignment value, then the
2479*57696d54SAkhilesh Sanikop // alignment value is adjusted down. If the computed alignment is less than 8
2480*57696d54SAkhilesh Sanikop // and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2481*57696d54SAkhilesh Sanikop // is a safety measure for Advanced Format drives. If no partitions are
2482*57696d54SAkhilesh Sanikop // defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2483*57696d54SAkhilesh Sanikop // adjustment of that based on the current sector size). The result is that new
2484*57696d54SAkhilesh Sanikop // drives are aligned to 2048-sector multiples but the program won't complain
2485*57696d54SAkhilesh Sanikop // about other alignments on existing disks unless a smaller-than-8 alignment
2486*57696d54SAkhilesh Sanikop // is used on big disks (as safety for Advanced Format drives).
2487*57696d54SAkhilesh Sanikop // Returns the computed alignment value.
ComputeAlignment(void)2488*57696d54SAkhilesh Sanikop uint32_t GPTData::ComputeAlignment(void) {
2489*57696d54SAkhilesh Sanikop    uint32_t i = 0, found, exponent;
2490*57696d54SAkhilesh Sanikop    uint32_t align = DEFAULT_ALIGNMENT;
2491*57696d54SAkhilesh Sanikop 
2492*57696d54SAkhilesh Sanikop    if (blockSize > 0)
2493*57696d54SAkhilesh Sanikop       align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2494*57696d54SAkhilesh Sanikop    exponent = (uint32_t) log2(align);
2495*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2496*57696d54SAkhilesh Sanikop       if (partitions[i].IsUsed()) {
2497*57696d54SAkhilesh Sanikop          found = 0;
2498*57696d54SAkhilesh Sanikop          while (!found) {
2499*57696d54SAkhilesh Sanikop             align = UINT64_C(1) << exponent;
2500*57696d54SAkhilesh Sanikop             if ((partitions[i].GetFirstLBA() % align) == 0) {
2501*57696d54SAkhilesh Sanikop                found = 1;
2502*57696d54SAkhilesh Sanikop             } else {
2503*57696d54SAkhilesh Sanikop                exponent--;
2504*57696d54SAkhilesh Sanikop             } // if/else
2505*57696d54SAkhilesh Sanikop          } // while
2506*57696d54SAkhilesh Sanikop       } // if
2507*57696d54SAkhilesh Sanikop    } // for
2508*57696d54SAkhilesh Sanikop    if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2509*57696d54SAkhilesh Sanikop       align = MIN_AF_ALIGNMENT;
2510*57696d54SAkhilesh Sanikop    sectorAlignment = align;
2511*57696d54SAkhilesh Sanikop    return align;
2512*57696d54SAkhilesh Sanikop } // GPTData::ComputeAlignment()
2513*57696d54SAkhilesh Sanikop 
2514*57696d54SAkhilesh Sanikop /********************************
2515*57696d54SAkhilesh Sanikop  *                              *
2516*57696d54SAkhilesh Sanikop  * Endianness support functions *
2517*57696d54SAkhilesh Sanikop  *                              *
2518*57696d54SAkhilesh Sanikop  ********************************/
2519*57696d54SAkhilesh Sanikop 
ReverseHeaderBytes(struct GPTHeader * header)2520*57696d54SAkhilesh Sanikop void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
2521*57696d54SAkhilesh Sanikop    ReverseBytes(&header->signature, 8);
2522*57696d54SAkhilesh Sanikop    ReverseBytes(&header->revision, 4);
2523*57696d54SAkhilesh Sanikop    ReverseBytes(&header->headerSize, 4);
2524*57696d54SAkhilesh Sanikop    ReverseBytes(&header->headerCRC, 4);
2525*57696d54SAkhilesh Sanikop    ReverseBytes(&header->reserved, 4);
2526*57696d54SAkhilesh Sanikop    ReverseBytes(&header->currentLBA, 8);
2527*57696d54SAkhilesh Sanikop    ReverseBytes(&header->backupLBA, 8);
2528*57696d54SAkhilesh Sanikop    ReverseBytes(&header->firstUsableLBA, 8);
2529*57696d54SAkhilesh Sanikop    ReverseBytes(&header->lastUsableLBA, 8);
2530*57696d54SAkhilesh Sanikop    ReverseBytes(&header->partitionEntriesLBA, 8);
2531*57696d54SAkhilesh Sanikop    ReverseBytes(&header->numParts, 4);
2532*57696d54SAkhilesh Sanikop    ReverseBytes(&header->sizeOfPartitionEntries, 4);
2533*57696d54SAkhilesh Sanikop    ReverseBytes(&header->partitionEntriesCRC, 4);
2534*57696d54SAkhilesh Sanikop    ReverseBytes(header->reserved2, GPT_RESERVED);
2535*57696d54SAkhilesh Sanikop } // GPTData::ReverseHeaderBytes()
2536*57696d54SAkhilesh Sanikop 
2537*57696d54SAkhilesh Sanikop // Reverse byte order for all partitions.
ReversePartitionBytes()2538*57696d54SAkhilesh Sanikop void GPTData::ReversePartitionBytes() {
2539*57696d54SAkhilesh Sanikop    uint32_t i;
2540*57696d54SAkhilesh Sanikop 
2541*57696d54SAkhilesh Sanikop    for (i = 0; i < numParts; i++) {
2542*57696d54SAkhilesh Sanikop       partitions[i].ReversePartBytes();
2543*57696d54SAkhilesh Sanikop    } // for
2544*57696d54SAkhilesh Sanikop } // GPTData::ReversePartitionBytes()
2545*57696d54SAkhilesh Sanikop 
2546*57696d54SAkhilesh Sanikop // Validate partition number
ValidPartNum(const uint32_t partNum)2547*57696d54SAkhilesh Sanikop bool GPTData::ValidPartNum (const uint32_t partNum) {
2548*57696d54SAkhilesh Sanikop    if (partNum >= numParts) {
2549*57696d54SAkhilesh Sanikop       cerr << "Partition number out of range: " << partNum << "\n";
2550*57696d54SAkhilesh Sanikop       return false;
2551*57696d54SAkhilesh Sanikop    } // if
2552*57696d54SAkhilesh Sanikop    return true;
2553*57696d54SAkhilesh Sanikop } // GPTData::ValidPartNum
2554*57696d54SAkhilesh Sanikop 
2555*57696d54SAkhilesh Sanikop // Return a single partition for inspection (not modification!) by other
2556*57696d54SAkhilesh Sanikop // functions.
operator [](uint32_t partNum) const2557*57696d54SAkhilesh Sanikop const GPTPart & GPTData::operator[](uint32_t partNum) const {
2558*57696d54SAkhilesh Sanikop    if (partNum >= numParts) {
2559*57696d54SAkhilesh Sanikop       cerr << "Partition number out of range (" << partNum << " requested, but only "
2560*57696d54SAkhilesh Sanikop            << numParts << " available)\n";
2561*57696d54SAkhilesh Sanikop       exit(1);
2562*57696d54SAkhilesh Sanikop    } // if
2563*57696d54SAkhilesh Sanikop    if (partitions == NULL) {
2564*57696d54SAkhilesh Sanikop       cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2565*57696d54SAkhilesh Sanikop       exit(1);
2566*57696d54SAkhilesh Sanikop    } // if
2567*57696d54SAkhilesh Sanikop    return partitions[partNum];
2568*57696d54SAkhilesh Sanikop } // operator[]
2569*57696d54SAkhilesh Sanikop 
2570*57696d54SAkhilesh Sanikop // Return (not for modification!) the disk's GUID value
GetDiskGUID(void) const2571*57696d54SAkhilesh Sanikop const GUIDData & GPTData::GetDiskGUID(void) const {
2572*57696d54SAkhilesh Sanikop    return mainHeader.diskGUID;
2573*57696d54SAkhilesh Sanikop } // GPTData::GetDiskGUID()
2574*57696d54SAkhilesh Sanikop 
2575*57696d54SAkhilesh Sanikop // Manage attributes for a partition, based on commands passed to this function.
2576*57696d54SAkhilesh Sanikop // (Function is non-interactive.)
2577*57696d54SAkhilesh Sanikop // Returns 1 if a modification command succeeded, 0 if the command should not have
2578*57696d54SAkhilesh Sanikop // modified data, and -1 if a modification command failed.
ManageAttributes(int partNum,const string & command,const string & bits)2579*57696d54SAkhilesh Sanikop int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2580*57696d54SAkhilesh Sanikop    int retval = 0;
2581*57696d54SAkhilesh Sanikop    Attributes theAttr;
2582*57696d54SAkhilesh Sanikop 
2583*57696d54SAkhilesh Sanikop    if (partNum >= (int) numParts) {
2584*57696d54SAkhilesh Sanikop       cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2585*57696d54SAkhilesh Sanikop       retval = -1;
2586*57696d54SAkhilesh Sanikop    } else {
2587*57696d54SAkhilesh Sanikop       if (command == "show") {
2588*57696d54SAkhilesh Sanikop          ShowAttributes(partNum);
2589*57696d54SAkhilesh Sanikop       } else if (command == "get") {
2590*57696d54SAkhilesh Sanikop          GetAttribute(partNum, bits);
2591*57696d54SAkhilesh Sanikop       } else {
2592*57696d54SAkhilesh Sanikop          theAttr = partitions[partNum].GetAttributes();
2593*57696d54SAkhilesh Sanikop          if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2594*57696d54SAkhilesh Sanikop             partitions[partNum].SetAttributes(theAttr.GetAttributes());
2595*57696d54SAkhilesh Sanikop             retval = 1;
2596*57696d54SAkhilesh Sanikop          } else {
2597*57696d54SAkhilesh Sanikop             retval = -1;
2598*57696d54SAkhilesh Sanikop          } // if/else
2599*57696d54SAkhilesh Sanikop       } // if/elseif/else
2600*57696d54SAkhilesh Sanikop    } // if/else invalid partition #
2601*57696d54SAkhilesh Sanikop 
2602*57696d54SAkhilesh Sanikop    return retval;
2603*57696d54SAkhilesh Sanikop } // GPTData::ManageAttributes()
2604*57696d54SAkhilesh Sanikop 
2605*57696d54SAkhilesh Sanikop // Show all attributes for a specified partition....
ShowAttributes(const uint32_t partNum)2606*57696d54SAkhilesh Sanikop void GPTData::ShowAttributes(const uint32_t partNum) {
2607*57696d54SAkhilesh Sanikop    if ((partNum < numParts) && partitions[partNum].IsUsed())
2608*57696d54SAkhilesh Sanikop       partitions[partNum].ShowAttributes(partNum);
2609*57696d54SAkhilesh Sanikop } // GPTData::ShowAttributes
2610*57696d54SAkhilesh Sanikop 
2611*57696d54SAkhilesh Sanikop // Show whether a single attribute bit is set (terse output)...
GetAttribute(const uint32_t partNum,const string & attributeBits)2612*57696d54SAkhilesh Sanikop void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
2613*57696d54SAkhilesh Sanikop    if (partNum < numParts)
2614*57696d54SAkhilesh Sanikop       partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
2615*57696d54SAkhilesh Sanikop } // GPTData::GetAttribute
2616*57696d54SAkhilesh Sanikop 
2617*57696d54SAkhilesh Sanikop 
2618*57696d54SAkhilesh Sanikop /******************************************
2619*57696d54SAkhilesh Sanikop  *                                        *
2620*57696d54SAkhilesh Sanikop  * Additional non-class support functions *
2621*57696d54SAkhilesh Sanikop  *                                        *
2622*57696d54SAkhilesh Sanikop  ******************************************/
2623*57696d54SAkhilesh Sanikop 
2624*57696d54SAkhilesh Sanikop // Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2625*57696d54SAkhilesh Sanikop // never fail these tests, but the struct types may fail depending on compile options.
2626*57696d54SAkhilesh Sanikop // Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2627*57696d54SAkhilesh Sanikop // sizes.
SizesOK(void)2628*57696d54SAkhilesh Sanikop int SizesOK(void) {
2629*57696d54SAkhilesh Sanikop    int allOK = 1;
2630*57696d54SAkhilesh Sanikop 
2631*57696d54SAkhilesh Sanikop    if (sizeof(uint8_t) != 1) {
2632*57696d54SAkhilesh Sanikop       cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
2633*57696d54SAkhilesh Sanikop       allOK = 0;
2634*57696d54SAkhilesh Sanikop    } // if
2635*57696d54SAkhilesh Sanikop    if (sizeof(uint16_t) != 2) {
2636*57696d54SAkhilesh Sanikop       cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
2637*57696d54SAkhilesh Sanikop       allOK = 0;
2638*57696d54SAkhilesh Sanikop    } // if
2639*57696d54SAkhilesh Sanikop    if (sizeof(uint32_t) != 4) {
2640*57696d54SAkhilesh Sanikop       cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
2641*57696d54SAkhilesh Sanikop       allOK = 0;
2642*57696d54SAkhilesh Sanikop    } // if
2643*57696d54SAkhilesh Sanikop    if (sizeof(uint64_t) != 8) {
2644*57696d54SAkhilesh Sanikop       cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
2645*57696d54SAkhilesh Sanikop       allOK = 0;
2646*57696d54SAkhilesh Sanikop    } // if
2647*57696d54SAkhilesh Sanikop    if (sizeof(struct MBRRecord) != 16) {
2648*57696d54SAkhilesh Sanikop       cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
2649*57696d54SAkhilesh Sanikop       allOK = 0;
2650*57696d54SAkhilesh Sanikop    } // if
2651*57696d54SAkhilesh Sanikop    if (sizeof(struct TempMBR) != 512) {
2652*57696d54SAkhilesh Sanikop       cerr << "TempMBR is " <<  sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
2653*57696d54SAkhilesh Sanikop       allOK = 0;
2654*57696d54SAkhilesh Sanikop    } // if
2655*57696d54SAkhilesh Sanikop    if (sizeof(struct GPTHeader) != 512) {
2656*57696d54SAkhilesh Sanikop       cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
2657*57696d54SAkhilesh Sanikop       allOK = 0;
2658*57696d54SAkhilesh Sanikop    } // if
2659*57696d54SAkhilesh Sanikop    if (sizeof(GPTPart) != 128) {
2660*57696d54SAkhilesh Sanikop       cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
2661*57696d54SAkhilesh Sanikop       allOK = 0;
2662*57696d54SAkhilesh Sanikop    } // if
2663*57696d54SAkhilesh Sanikop    if (sizeof(GUIDData) != 16) {
2664*57696d54SAkhilesh Sanikop       cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2665*57696d54SAkhilesh Sanikop       allOK = 0;
2666*57696d54SAkhilesh Sanikop    } // if
2667*57696d54SAkhilesh Sanikop    if (sizeof(PartType) != 16) {
2668*57696d54SAkhilesh Sanikop       cerr << "PartType is " << sizeof(PartType) << " bytes, should be 16 bytes; aborting!\n";
2669*57696d54SAkhilesh Sanikop       allOK = 0;
2670*57696d54SAkhilesh Sanikop    } // if
2671*57696d54SAkhilesh Sanikop    return (allOK);
2672*57696d54SAkhilesh Sanikop } // SizesOK()
2673*57696d54SAkhilesh Sanikop 
2674