gpt.cc revision bdbab02f71097593c879a552951d73969305d0ae
1fb3e5ca53b412a41d26bb4316f10e68aa72f65f6Bill Wendling/* gpt.cc -- Functions for loading, saving, and manipulating legacy MBR and GPT partition
21999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky   data. */
31999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky
41999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky/* By Rod Smith, initial coding January to February, 2009 */
51999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky
61999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
71999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky  under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
81999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky
91999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#define __STDC_LIMIT_MACROS
101999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#ifndef __STDC_CONSTANT_MACROS
11de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar#define __STDC_CONSTANT_MACROS
122e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman#endif
135a88dda4be791426ab4d20a6a6c9c65d66614a27Chandler Carruth
14f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <stdio.h>
151999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include <stdlib.h>
161999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include <stdint.h>
171999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include <fcntl.h>
181999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include <string.h>
191999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include <math.h>
20f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <time.h>
21f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <sys/stat.h>
22f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <errno.h>
23f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <iostream>
24f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include <algorithm>
25f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include "crc32.h"
26f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar#include "gpt.h"
271999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include "bsd.h"
281999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include "support.h"
291999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include "parttypes.h"
301999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky#include "attributes.h"
3148b17fa5bebf46ecdbcb51ebab1c3d8b483afd3cChandler Carruth#include "diskio.h"
3248b17fa5bebf46ecdbcb51ebab1c3d8b483afd3cChandler Carruth
332d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwinusing namespace std;
342d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
352e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman#ifdef __FreeBSD__
36e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman#define log2(x) (log(x) / M_LN2)
372d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#endif // __FreeBSD__
382d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
392d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#ifdef _MSC_VER
40e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman#define log2(x) (log((double) x) / log(2.0))
412d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#endif // Microsoft Visual C++
422d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
432d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#ifdef EFI
442d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin// in UEFI mode MMX registers are not yet available so using the
452d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin// x86_64 ABI to move "double" values around is not an option.
462d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#ifdef log2
472d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#undef log2
482d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#endif
492d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#define log2(x) log2_32( x )
50bc9c36bb7c436d7691d12d51d2b67f309b25df4fJakob Stoklund Olesenstatic inline uint32_t log2_32(uint32_t v) {
51bc9c36bb7c436d7691d12d51d2b67f309b25df4fJakob Stoklund Olesen   int r = -1;
52bc9c36bb7c436d7691d12d51d2b67f309b25df4fJakob Stoklund Olesen   while (v >= 1) {
532e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      r++;
54e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman      v >>= 1;
552d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   }
562d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   return r;
572d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin}
582d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin#endif
592d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
602d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin/****************************************
612d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin *                                      *
622d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin * GPTData class and related structures *
632d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin *                                      *
64bc9c36bb7c436d7691d12d51d2b67f309b25df4fJakob Stoklund Olesen ****************************************/
65bc9c36bb7c436d7691d12d51d2b67f309b25df4fJakob Stoklund Olesen
662e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman// Default constructor
6735b1423ee67a6ec7052016dda486e6ee4a118db4Meador IngeGPTData::GPTData(void) {
6835b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   blockSize = SECTOR_SIZE; // set a default
6935b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   diskSize = 0;
7035b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   partitions = NULL;
7135b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   state = gpt_valid;
7235b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   device = "";
7335b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   justLooking = 0;
7435b1423ee67a6ec7052016dda486e6ee4a118db4Meador Inge   mainCrcOk = 0;
752d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   secondCrcOk = 0;
767a874ddda037349184fbeb22838cc11a1a9bb78fJay Foad   mainPartsCrcOk = 0;
772d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   secondPartsCrcOk = 0;
782d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   apmFound = 0;
792d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   bsdFound = 0;
802d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
812d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   beQuiet = 0;
822d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   whichWasUsed = use_new;
832d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   mainHeader.numParts = 0;
842e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   numParts = 0;
852d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   SetGPTSize(NUM_GPT_ENTRIES);
862d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   // Initialize CRC functions...
872d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   chksum_crc32gentab();
882d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin} // GPTData default constructor
892d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
902d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin// The following constructor loads GPT data from a device file
912d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok EdwinGPTData::GPTData(string filename) {
922d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   blockSize = SECTOR_SIZE; // set a default
93e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman   diskSize = 0;
942d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   partitions = NULL;
952d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   state = gpt_invalid;
962d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   device = "";
972d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   justLooking = 0;
982d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   mainCrcOk = 0;
992d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   secondCrcOk = 0;
1002d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   mainPartsCrcOk = 0;
1012d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   secondPartsCrcOk = 0;
1022d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   apmFound = 0;
1032d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   bsdFound = 0;
1042d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   sectorAlignment = MIN_AF_ALIGNMENT; // Align partitions on 4096-byte boundaries by default
1052d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   beQuiet = 0;
1062d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   whichWasUsed = use_new;
1072d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   mainHeader.numParts = 0;
1082d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   numParts = 0;
1092d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   // Initialize CRC functions...
1102d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   chksum_crc32gentab();
1112d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   if (!LoadPartitions(filename))
1122d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin      exit(2);
1132d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin} // GPTData(string filename) constructor
1142d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
1152d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin// Destructor
1162d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok EdwinGPTData::~GPTData(void) {
1172d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin   delete[] partitions;
1182d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin} // GPTData destructor
1192d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin
1202d0f1c57c3f95e43a8b18bfe8481d90b665d5efeTorok Edwin// Assignment operator
1211999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick LewyckyGPTData & GPTData::operator=(const GPTData & orig) {
1221999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky   uint32_t i;
1232e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
124e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman   mainHeader = orig.mainHeader;
125e3bc46ede58d9c02b8f1a630e70ee1c98a1e4229Misha Brukman   numParts = orig.numParts;
1262e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   secondHeader = orig.secondHeader;
1272e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   protectiveMBR = orig.protectiveMBR;
1282e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   device = orig.device;
1292e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   blockSize = orig.blockSize;
1302e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   diskSize = orig.diskSize;
1312e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   state = orig.state;
1322e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   justLooking = orig.justLooking;
1332e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   mainCrcOk = orig.mainCrcOk;
1342e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   secondCrcOk = orig.secondCrcOk;
1352e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   mainPartsCrcOk = orig.mainPartsCrcOk;
1362e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   secondPartsCrcOk = orig.secondPartsCrcOk;
1372e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   apmFound = orig.apmFound;
1382e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   bsdFound = orig.bsdFound;
1392e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   sectorAlignment = orig.sectorAlignment;
1402e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   beQuiet = orig.beQuiet;
1412e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   whichWasUsed = orig.whichWasUsed;
1422e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
1432e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   myDisk.OpenForRead(orig.myDisk.GetName());
1442e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
1456948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   delete[] partitions;
1466948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   partitions = new GPTPart [numParts];
1476948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if (partitions == NULL) {
1486948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cerr << "Error! Could not allocate memory for partitions in GPTData::operator=()!\n"
1496948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar           << "Terminating!\n";
1506948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      exit(1);
1512e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // if
1522e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   for (i = 0; i < numParts; i++) {
1532e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      partitions[i] = orig.partitions[i];
1542e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // for
1552e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
1562e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   return *this;
1572e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman} // GPTData::operator=()
1582e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
1592e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman/*********************************************************************
1602e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman *                                                                   *
1612e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman * Begin functions that verify data, or that adjust the verification *
1622e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman * information (compute CRCs, rebuild headers)                       *
1632e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman *                                                                   *
1642e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman *********************************************************************/
1652e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman
1662e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman// Perform detailed verification, reporting on any problems found, but
1672e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman// do *NOT* recover from these problems. Returns the total number of
1682e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman// problems identified.
1693a3a424a248717487de826ddb48f14deec1d2446Eli Friedmanint GPTData::Verify(void) {
1703a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   int problems = 0, alignProbs = 0;
1713a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   uint32_t i, numSegments;
1723a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   uint64_t totalFree, largestSegment;
1733a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
1743a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   // First, check for CRC errors in the GPT data....
1752e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   if (!mainCrcOk) {
1762e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      problems++;
1772e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      cout << "\nProblem: The CRC for the main GPT header is invalid. The main GPT header may\n"
1782e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "be corrupt. Consider loading the backup GPT header to rebuild the main GPT\n"
1792e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "header ('b' on the recovery & transformation menu). This report may be a false\n"
1802e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "alarm if you've already corrected other problems.\n";
1812e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // if
1822e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   if (!mainPartsCrcOk) {
1832e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      problems++;
1842e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      cout << "\nProblem: The CRC for the main partition table is invalid. This table may be\n"
1852e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "corrupt. Consider loading the backup partition table ('c' on the recovery &\n"
1862e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "transformation menu). This report may be a false alarm if you've already\n"
1872e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "corrected other problems.\n";
1882e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // if
1892e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   if (!secondCrcOk) {
1902e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      problems++;
1912e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman      cout << "\nProblem: The CRC for the backup GPT header is invalid. The backup GPT header\n"
1922e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "may be corrupt. Consider using the main GPT header to rebuild the backup GPT\n"
1932e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "header ('d' on the recovery & transformation menu). This report may be a false\n"
1942e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << "alarm if you've already corrected other problems.\n";
1952e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // if
196a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   if (!secondPartsCrcOk) {
197a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      problems++;
198a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      cout << "\nCaution: The CRC for the backup partition table is invalid. This table may\n"
199a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "be corrupt. This program will automatically create a new backup partition\n"
200a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "table when you save your partitions.\n";
201a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   } // if
202a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes
203a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   // Now check that the main and backup headers both point to themselves....
204a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   if (mainHeader.currentLBA != 1) {
205a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      problems++;
206a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      cout << "\nProblem: The main header's self-pointer doesn't point to itself. This problem\n"
207a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "is being automatically corrected, but it may be a symptom of more serious\n"
208a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "problems. Think carefully before saving changes with 'w' or using this disk.\n";
209a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      mainHeader.currentLBA = 1;
210a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   } // if
211a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   if (secondHeader.currentLBA != (diskSize - UINT64_C(1))) {
212a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      problems++;
213a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      cout << "\nProblem: The secondary header's self-pointer indicates that it doesn't reside\n"
214a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "at the end of the disk. If you've added a disk to a RAID array, use the 'e'\n"
215a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "option on the experts' menu to adjust the secondary header's and partition\n"
216a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << "table's locations.\n";
217a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   } // if
218a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes
219a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   // Now check that critical main and backup GPT entries match each other
220a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes   if (mainHeader.currentLBA != secondHeader.backupLBA) {
221a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      problems++;
222a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes      cout << "\nProblem: main GPT header's current LBA pointer (" << mainHeader.currentLBA
223a7a2a3635f2fbe46d7d9074798e79e853f69d40bNuno Lopes           << ") doesn't\nmatch the backup GPT header's alternate LBA pointer("
2242e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman           << secondHeader.backupLBA << ").\n";
2252e734269e3f354e52bd9e55d791e1885aa7d4cd8Misha Brukman   } // if
226f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.backupLBA != secondHeader.currentLBA) {
227f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
228f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main GPT header's backup LBA pointer (" << mainHeader.backupLBA
229f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") doesn't\nmatch the backup GPT header's current LBA pointer ("
230f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.currentLBA << ").\n"
231f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "The 'e' option on the experts' menu may fix this problem.\n";
232f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
233f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.firstUsableLBA != secondHeader.firstUsableLBA) {
234f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
235f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main GPT header's first usable LBA pointer (" << mainHeader.firstUsableLBA
236f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") doesn't\nmatch the backup GPT header's first usable LBA pointer ("
237f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.firstUsableLBA << ")\n";
238f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
239f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.lastUsableLBA != secondHeader.lastUsableLBA) {
240f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
241f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main GPT header's last usable LBA pointer (" << mainHeader.lastUsableLBA
242f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") doesn't\nmatch the backup GPT header's last usable LBA pointer ("
243f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.lastUsableLBA << ")\n"
244f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "The 'e' option on the experts' menu can probably fix this problem.\n";
245f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
246f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if ((mainHeader.diskGUID != secondHeader.diskGUID)) {
247f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
248f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main header's disk GUID (" << mainHeader.diskGUID
249f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") doesn't\nmatch the backup GPT header's disk GUID ("
250f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.diskGUID << ")\n"
251f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
252f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "select one or the other header.\n";
253f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
254f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.numParts != secondHeader.numParts) {
255f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
256f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main GPT header's number of partitions (" << mainHeader.numParts
257f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") doesn't\nmatch the backup GPT header's number of partitions ("
258f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.numParts << ")\n"
259f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "Resizing the partition table ('s' on the experts' menu) may help.\n";
260f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
261f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.sizeOfPartitionEntries != secondHeader.sizeOfPartitionEntries) {
262f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
263f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: main GPT header's size of partition entries ("
264f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << mainHeader.sizeOfPartitionEntries << ") doesn't\n"
265f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "match the backup GPT header's size of partition entries ("
266f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << secondHeader.sizeOfPartitionEntries << ")\n"
267f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "You should use the 'b' or 'd' option on the recovery & transformation menu to\n"
268f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "select one or the other header.\n";
269f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
270f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
271f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Now check for a few other miscellaneous problems...
272f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check that the disk size will hold the data...
273f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (mainHeader.backupLBA >= diskSize) {
274f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
275f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: Disk is too small to hold all the data!\n"
276f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "(Disk size is " << diskSize << " sectors, needs to be "
277f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << mainHeader.backupLBA + UINT64_C(1) << " sectors.)\n"
278f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "The 'e' option on the experts' menu may fix this problem.\n";
279f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if
280f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
281f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
282f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
283f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nProblem: GPT claims the disk is larger than it is! (Claimed last usable\n"
284f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "sector is " << mainHeader.lastUsableLBA << ", but backup header is at\n"
285f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << mainHeader.backupLBA << " and disk size is " << diskSize << " sectors.\n"
286f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "The 'e' option on the experts' menu will probably fix this problem\n";
287f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   }
288f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
289f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check for overlapping partitions....
290f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   problems += FindOverlaps();
291f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
292f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check for insane partitions (start after end, hugely big, etc.)
293f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   problems += FindInsanePartitions();
294f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
295f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check for mismatched MBR and GPT partitions...
296f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   problems += FindHybridMismatches();
297f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
298f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check for MBR-specific problems....
299f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   problems += VerifyMBR();
300f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
301f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check for a 0xEE protective partition that's marked as active....
302f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (protectiveMBR.IsEEActive()) {
303f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nWarning: The 0xEE protective partition in the MBR is marked as active. This is\n"
304f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "technically a violation of the GPT specification, and can cause some EFIs to\n"
305f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "ignore the disk, but it is required to boot from a GPT disk on some BIOS-based\n"
306f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "computers. You can clear this flag by creating a fresh protective MBR using\n"
307f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "the 'n' option on the experts' menu.\n";
308f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   }
309f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
310f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Verify that partitions don't run into GPT data areas....
311f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   problems += CheckGPTSize();
312f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
313f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (!protectiveMBR.DoTheyFit()) {
314f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
315f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << "fresh protective or hybrid MBR is recommended.\n";
316f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      problems++;
317f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   }
318f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
319f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Check that partitions are aligned on proper boundaries (for WD Advanced
320f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Format and similar disks)....
321f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   for (i = 0; i < numParts; i++) {
322f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if ((partitions[i].IsUsed()) && (partitions[i].GetFirstLBA() % sectorAlignment) != 0) {
323f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         cout << "\nCaution: Partition " << i + 1 << " doesn't begin on a "
324f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar              << sectorAlignment << "-sector boundary. This may\nresult "
325f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar              << "in degraded performance on some modern (2009 and later) hard disks.\n";
326f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         alignProbs++;
327f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      } // if
328f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // for
329f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (alignProbs > 0)
330f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nConsult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/\n"
331f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      << "for information on disk alignment.\n";
332f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
333f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // Now compute available space, but only if no problems found, since
334f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // problems could affect the results
335f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (problems == 0) {
336f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      totalFree = FindFreeBlocks(&numSegments, &largestSegment);
337f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nNo problems found. " << totalFree << " free sectors ("
338f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << BytesToIeee(totalFree, blockSize) << ") available in "
339f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << numSegments << "\nsegments, the largest of which is "
340f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << largestSegment << " (" << BytesToIeee(largestSegment, blockSize)
341f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar           << ") in size.\n";
342f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } else {
343f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      cout << "\nIdentified " << problems << " problems!\n";
344f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // if/else
345f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
346f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   return (problems);
347f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar} // GPTData::Verify()
348f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
349f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar// Checks to see if the GPT tables overrun existing partitions; if they
350f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar// do, issues a warning but takes no action. Returns number of problems
351f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar// detected (0 if OK, 1 to 2 if problems).
352f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainarint GPTData::CheckGPTSize(void) {
353f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   uint64_t overlap, firstUsedBlock, lastUsedBlock;
354f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   uint32_t i;
355f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   int numProbs = 0;
356f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
357f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // first, locate the first & last used blocks
358f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   firstUsedBlock = UINT64_MAX;
359f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   lastUsedBlock = 0;
360f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   for (i = 0; i < numParts; i++) {
361f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (partitions[i].IsUsed()) {
362f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         if (partitions[i].GetFirstLBA() < firstUsedBlock)
363f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            firstUsedBlock = partitions[i].GetFirstLBA();
364f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         if (partitions[i].GetLastLBA() > lastUsedBlock) {
365f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            lastUsedBlock = partitions[i].GetLastLBA();
366f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         } // if
367f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      } // if
368f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   } // for
369f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar
370f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // If the disk size is 0 (the default), then it means that various
371f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // variables aren't yet set, so the below tests will be useless;
372f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   // therefore we should skip everything
373f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar   if (diskSize != 0) {
374f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (mainHeader.firstUsableLBA > firstUsedBlock) {
375f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         overlap = mainHeader.firstUsableLBA - firstUsedBlock;
376f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         cout << "Warning! Main partition table overlaps the first partition by "
377f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar              << overlap << " blocks!\n";
378f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         if (firstUsedBlock > 2) {
379f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            cout << "Try reducing the partition table size by " << overlap * 4
380f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar                 << " entries.\n(Use the 's' item on the experts' menu.)\n";
381f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         } else {
382f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar            cout << "You will need to delete this partition or resize it in another utility.\n";
383f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         } // if/else
384f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         numProbs++;
385f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      } // Problem at start of disk
386f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar      if (mainHeader.lastUsableLBA < lastUsedBlock) {
387f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         overlap = lastUsedBlock - mainHeader.lastUsableLBA;
388f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         cout << "\nWarning! Secondary partition table overlaps the last partition by\n"
389f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar              << overlap << " blocks!\n";
390f3ef5332fa3f4d5ec72c178a2b19dac363a19383Pirama Arumuga Nainar         if (lastUsedBlock > (diskSize - 2)) {
391de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            cout << "You will need to delete this partition or resize it in another utility.\n";
392de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         } else {
393de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            cout << "Try reducing the partition table size by " << overlap * 4
394de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar                 << " entries.\n(Use the 's' item on the experts' menu.)\n";
395de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         } // if/else
396de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         numProbs++;
397de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      } // Problem at end of disk
398de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   } // if (diskSize != 0)
399de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   return numProbs;
400de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar} // GPTData::CheckGPTSize()
401de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
402de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// Check the validity of the GPT header. Returns 1 if the main header
403de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// is valid, 2 if the backup header is valid, 3 if both are valid, and
404de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// 0 if neither is valid. Note that this function checks the GPT signature,
405de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// revision value, and CRCs in both headers.
406de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarint GPTData::CheckHeaderValidity(void) {
407de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   int valid = 3;
408de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
409de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   cout.setf(ios::uppercase);
410de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   cout.fill('0');
411de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
412de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // Note: failed GPT signature checks produce no error message because
413de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // a message is displayed in the ReversePartitionBytes() function
414de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if ((mainHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&mainHeader, 1))) {
415de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      valid -= 1;
416de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   } else if ((mainHeader.revision != 0x00010000) && valid) {
417de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      valid -= 1;
418de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      cout << "Unsupported GPT version in main header; read 0x";
4196948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout.width(8);
4206948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << hex << mainHeader.revision << ", should be\n0x";
4216948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout.width(8);
4226948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << UINT32_C(0x00010000) << dec << "\n";
4236948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } // if/else/if
4244c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
4254c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   if ((secondHeader.signature != GPT_SIGNATURE) || (!CheckHeaderCRC(&secondHeader))) {
4266948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      valid -= 2;
4274c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   } else if ((secondHeader.revision != 0x00010000) && valid) {
4284c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      valid -= 2;
4296948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << "Unsupported GPT version in backup header; read 0x";
4306948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout.width(8);
4314c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      cout << hex << secondHeader.revision << ", should be\n0x";
4326948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout.width(8);
4336948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << UINT32_C(0x00010000) << dec << "\n";
4344c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   } // if/else/if
4354c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
4366948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   // Check for an Apple disk signature
4376948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if (((mainHeader.signature << 32) == APM_SIGNATURE1) ||
4384c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar        (mainHeader.signature << 32) == APM_SIGNATURE2) {
4396948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      apmFound = 1; // Will display warning message later
4406948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } // if
4416948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   cout.fill(' ');
4426948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
4436948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   return valid;
4446948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar} // GPTData::CheckHeaderValidity()
4456948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
4466948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar// Check the header CRC to see if it's OK...
4476948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar// Note: Must be called with header in platform-ordered byte order.
4486948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar// Returns 1 if header's computed CRC matches the stored value, 0 if the
4496948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar// computed and stored values don't match
4506948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainarint GPTData::CheckHeaderCRC(struct GPTHeader* header, int warn) {
4516948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   uint32_t oldCRC, newCRC, hSize;
4526948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   uint8_t *temp;
4536948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
4546948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   // Back up old header CRC and then blank it, since it must be 0 for
4556948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   // computation to be valid
4566948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   oldCRC = header->headerCRC;
4576948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   header->headerCRC = UINT32_C(0);
4584c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
4594c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   hSize = header->headerSize;
4606948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
4614c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   if (IsLittleEndian() == 0)
4626948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ReverseHeaderBytes(header);
4636948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
4646948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if ((hSize > blockSize) || (hSize < HEADER_SIZE)) {
4656948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      if (warn) {
4664c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         cerr << "\aWarning! Header size is specified as " << hSize << ", which is invalid.\n";
4676948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar         cerr << "Setting the header size for CRC computation to " << HEADER_SIZE << "\n";
4686948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      } // if
4696948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      hSize = HEADER_SIZE;
4706948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } else if ((hSize > sizeof(GPTHeader)) && warn) {
4716948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << "\aCaution! Header size for CRC check is " << hSize << ", which is greater than " << sizeof(GPTHeader) << ".\n";
4726948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      cout << "If stray data exists after the header on the header sector, it will be ignored,\n"
4736948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar           << "which may result in a CRC false alarm.\n";
4746948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } // if/elseif
4756948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   temp = new uint8_t[hSize];
4766948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if (temp != NULL) {
4776948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      memset(temp, 0, hSize);
4786948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      if (hSize < sizeof(GPTHeader))
4794c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         memcpy(temp, header, hSize);
4804c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      else
4814c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         memcpy(temp, header, sizeof(GPTHeader));
4824c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
4836948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      newCRC = chksum_crc32((unsigned char*) temp, hSize);
4846948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      delete[] temp;
4856948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } else {
4864c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      cerr << "Could not allocate memory in GPTData::CheckHeaderCRC()! Aborting!\n";
4874c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      exit(1);
4884c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   }
4894c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   if (IsLittleEndian() == 0)
4906948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ReverseHeaderBytes(header);
4916948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   header->headerCRC = oldCRC;
4926948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   return (oldCRC == newCRC);
4934c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar} // GPTData::CheckHeaderCRC()
4944c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
4954c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// Recompute all the CRCs. Must be called before saving if any changes have
4964c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// been made. Must be called on platform-ordered data (this function reverses
4976948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar// byte order and then undoes that reversal.)
4986948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainarvoid GPTData::RecomputeCRCs(void) {
4996948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   uint32_t crc, hSize;
5006948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   int littleEndian = 1;
5014c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
5026948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   // If the header size is bigger than the GPT header data structure, reset it;
5036948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   // otherwise, set both header sizes to whatever the main one is....
5046948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if (mainHeader.headerSize > sizeof(GPTHeader))
5056948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      hSize = secondHeader.headerSize = mainHeader.headerSize = HEADER_SIZE;
5066948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   else
5076948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      hSize = secondHeader.headerSize = mainHeader.headerSize;
5086948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
5096948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   if ((littleEndian = IsLittleEndian()) == 0) {
5106948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ReversePartitionBytes();
5116948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ReverseHeaderBytes(&mainHeader);
5126948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ReverseHeaderBytes(&secondHeader);
5136948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar   } // if
5144c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
5154c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   // Compute CRC of partition tables & store in main and secondary headers
51638300e91f5ff2d427d98f81fb25df8cc2800d985Chris Lattner   crc = chksum_crc32((unsigned char*) partitions, numParts * GPT_SIZE);
517bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.partitionEntriesCRC = crc;
518bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.partitionEntriesCRC = crc;
519bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   if (littleEndian == 0) {
520bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReverseBytes(&mainHeader.partitionEntriesCRC, 4);
521bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReverseBytes(&secondHeader.partitionEntriesCRC, 4);
522bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   } // if
523bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar
524bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   // Zero out GPT headers' own CRCs (required for correct computation)
525bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.headerCRC = 0;
526bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.headerCRC = 0;
527bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar
528bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   crc = chksum_crc32((unsigned char*) &mainHeader, hSize);
529393317975c0620360c54a6a3052c06db0b56f7e9Daniel Dunbar   if (littleEndian == 0)
530393317975c0620360c54a6a3052c06db0b56f7e9Daniel Dunbar      ReverseBytes(&crc, 4);
531393317975c0620360c54a6a3052c06db0b56f7e9Daniel Dunbar   mainHeader.headerCRC = crc;
532393317975c0620360c54a6a3052c06db0b56f7e9Daniel Dunbar   crc = chksum_crc32((unsigned char*) &secondHeader, hSize);
533393317975c0620360c54a6a3052c06db0b56f7e9Daniel Dunbar   if (littleEndian == 0)
534bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReverseBytes(&crc, 4);
535bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.headerCRC = crc;
536bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar
537bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   if (littleEndian == 0) {
538bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReverseHeaderBytes(&mainHeader);
539bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReverseHeaderBytes(&secondHeader);
540bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar      ReversePartitionBytes();
541bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   } // if
542bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar} // GPTData::RecomputeCRCs()
543bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar
544bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar// Rebuild the main GPT header, using the secondary header as a model.
545bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar// Typically called when the main header has been found to be corrupt.
546bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaarvoid GPTData::RebuildMainHeader(void) {
547bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.signature = GPT_SIGNATURE;
548bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.revision = secondHeader.revision;
549bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.headerSize = secondHeader.headerSize;
550f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.headerCRC = UINT32_C(0);
551f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.reserved = secondHeader.reserved;
552f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.currentLBA = secondHeader.backupLBA;
553f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.backupLBA = secondHeader.currentLBA;
554f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.firstUsableLBA = secondHeader.firstUsableLBA;
555f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   mainHeader.lastUsableLBA = secondHeader.lastUsableLBA;
556bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.diskGUID = secondHeader.diskGUID;
557bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.partitionEntriesLBA = UINT64_C(2);
558bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.numParts = secondHeader.numParts;
559bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.sizeOfPartitionEntries = secondHeader.sizeOfPartitionEntries;
560bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainHeader.partitionEntriesCRC = secondHeader.partitionEntriesCRC;
561bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   memcpy(mainHeader.reserved2, secondHeader.reserved2, sizeof(mainHeader.reserved2));
562bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   mainCrcOk = secondCrcOk;
563bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   SetGPTSize(mainHeader.numParts, 0);
564bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar} // GPTData::RebuildMainHeader()
565f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar
566f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar// Rebuild the secondary GPT header, using the main header as a model.
567f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbarvoid GPTData::RebuildSecondHeader(void) {
568f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondHeader.signature = GPT_SIGNATURE;
569f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondHeader.revision = mainHeader.revision;
570f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondHeader.headerSize = mainHeader.headerSize;
571bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.headerCRC = UINT32_C(0);
572bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.reserved = mainHeader.reserved;
573bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.currentLBA = mainHeader.backupLBA;
574bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.backupLBA = mainHeader.currentLBA;
575bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
576bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.lastUsableLBA = mainHeader.lastUsableLBA;
577bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.diskGUID = mainHeader.diskGUID;
578bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
579bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar   secondHeader.numParts = mainHeader.numParts;
580f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondHeader.sizeOfPartitionEntries = mainHeader.sizeOfPartitionEntries;
581f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondHeader.partitionEntriesCRC = mainHeader.partitionEntriesCRC;
582f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   memcpy(secondHeader.reserved2, mainHeader.reserved2, sizeof(secondHeader.reserved2));
583f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   secondCrcOk = mainCrcOk;
584f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar   SetGPTSize(secondHeader.numParts, 0);
585f74610b5e79031ecb39a7ca67093ff9cda8852f3Daniel Dunbar} // GPTData::RebuildSecondHeader()
586dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor
587dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor// Search for hybrid MBR entries that have no corresponding GPT partition.
588dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor// Returns number of such mismatches found
589dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregorint GPTData::FindHybridMismatches(void) {
590dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   int i, found, numFound = 0;
591dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   uint32_t j;
592dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   uint64_t mbrFirst, mbrLast;
593dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor
594dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   for (i = 0; i < 4; i++) {
595dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor      if ((protectiveMBR.GetType(i) != 0xEE) && (protectiveMBR.GetType(i) != 0x00)) {
596dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor         j = 0;
597dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor         found = 0;
598dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor         mbrFirst = (uint64_t) protectiveMBR.GetFirstSector(i);
599dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor         mbrLast = mbrFirst + (uint64_t) protectiveMBR.GetLength(i) - UINT64_C(1);
60038300e91f5ff2d427d98f81fb25df8cc2800d985Chris Lattner         do {
60138300e91f5ff2d427d98f81fb25df8cc2800d985Chris Lattner            if ((j < numParts) && (partitions[j].GetFirstLBA() == mbrFirst) &&
6023ba292dbc2acee2d1052fb7ffe332e2164147b47Jeffrey Yasskin                (partitions[j].GetLastLBA() == mbrLast) && (partitions[j].IsUsed()))
6033ba292dbc2acee2d1052fb7ffe332e2164147b47Jeffrey Yasskin               found = 1;
6043ba292dbc2acee2d1052fb7ffe332e2164147b47Jeffrey Yasskin            j++;
6053ba292dbc2acee2d1052fb7ffe332e2164147b47Jeffrey Yasskin         } while ((!found) && (j < numParts));
606ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         if (!found) {
607ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            numFound++;
608ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << "\nWarning! Mismatched GPT and MBR partition! MBR partition "
609ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar                 << i + 1 << ", of type 0x";
610ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout.fill('0');
611ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout.setf(ios::uppercase);
612ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout.width(2);
613ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << hex << (int) protectiveMBR.GetType(i) << ",\n"
614ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar                 << "has no corresponding GPT partition! You may continue, but this condition\n"
615ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar                 << "might cause data loss in the future!\a\n" << dec;
616ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout.fill(' ');
617ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         } // if
618ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      } // if
619ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   } // for
620ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   return numFound;
621ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar} // GPTData::FindHybridMismatches
622ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
623ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Find overlapping partitions and warn user about them. Returns number of
624ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// overlapping partitions.
625ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Returns number of overlapping segments found.
626ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaarint GPTData::FindOverlaps(void) {
627ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   int problems = 0;
628ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   uint32_t i, j;
629ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
630ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   for (i = 1; i < numParts; i++) {
631ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      for (j = 0; j < i; j++) {
632ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         if ((partitions[i].IsUsed()) && (partitions[j].IsUsed()) &&
633ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar             (partitions[i].DoTheyOverlap(partitions[j]))) {
634ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            problems++;
635ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << "\nProblem: partitions " << i + 1 << " and " << j + 1 << " overlap:\n";
636ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << "  Partition " << i + 1 << ": " << partitions[i].GetFirstLBA()
637ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar                 << " to " << partitions[i].GetLastLBA() << "\n";
638ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << "  Partition " << j + 1 << ": " << partitions[j].GetFirstLBA()
639ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar                 << " to " << partitions[j].GetLastLBA() << "\n";
640ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         } // if
641ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      } // for j...
642ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   } // for i...
643ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   return problems;
644ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar} // GPTData::FindOverlaps()
645ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
646ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Find partitions that are insane -- they start after they end or are too
647ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// big for the disk. (The latter should duplicate detection of overlaps
648ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// with GPT backup data structures, but better to err on the side of
649ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// redundant tests than to miss something....)
650ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Returns number of problems found.
651ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaarint GPTData::FindInsanePartitions(void) {
652ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   uint32_t i;
653ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   int problems = 0;
654ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
655ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   for (i = 0; i < numParts; i++) {
656ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      if (partitions[i].IsUsed()) {
657ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         if (partitions[i].GetFirstLBA() > partitions[i].GetLastLBA()) {
658ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            problems++;
659ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            cout << "\nProblem: partition " << i + 1 << " ends before it begins.\n";
660ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         } // if
661ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         if (partitions[i].GetLastLBA() >= diskSize) {
662ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar            problems++;
663ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         cout << "\nProblem: partition " << i + 1 << " is too big for the disk.\n";
664ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         } // if
665ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      } // if
666ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   } // for
667ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   return problems;
668ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar} // GPTData::FindInsanePartitions(void)
669ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
670ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
671ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar/******************************************************************
672ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar *                                                                *
673ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar * Begin functions that load data from disk or save data to disk. *
674ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar *                                                                *
675ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar ******************************************************************/
676ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
677ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Change the filename associated with the GPT. Used for duplicating
678ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// the partition table to a new disk and saving backups.
679ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar// Returns 1 on success, 0 on failure.
680ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaarint GPTData::SetDisk(const string & deviceFilename) {
681ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   int err, allOK = 1;
682ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar
683ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   device = deviceFilename;
684ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar   if (allOK && myDisk.OpenForRead(deviceFilename)) {
685ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      // store disk information....
686ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar      diskSize = myDisk.DiskSize(&err);
6875f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      blockSize = (uint32_t) myDisk.GetBlockSize();
6885f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   } // if
6895f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   protectiveMBR.SetDisk(&myDisk);
6905f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   protectiveMBR.SetDiskSize(diskSize);
6915f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   protectiveMBR.SetBlockSize(blockSize);
6925f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   return allOK;
6935f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith} // GPTData::SetDisk()
6945f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
6955f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith// Scan for partition data. This function loads the MBR data (regular MBR or
6965f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith// protective MBR) and loads BSD disklabel data (which is probably invalid).
6975f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith// It also looks for APM data, forces a load of GPT data, and summarizes
6985f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith// the results.
6995f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmithvoid GPTData::PartitionScan(void) {
7005f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   BSDData bsdDisklabel;
7015f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
7025f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   // Read the MBR & check for BSD disklabel
703efb0d1e42f266efbd3d15b0c12c0790e90c5be66Dylan Noblesmith   protectiveMBR.ReadMBRData(&myDisk);
704dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
705dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor
7065f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   // Load the GPT data, whether or not it's valid
7075f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   ForceLoadGPTData();
7085f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
7095f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   // Some tools create a 0xEE partition that's too big. If this is detected,
7105f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   // normalize it....
7115f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   if ((state == gpt_valid) && !protectiveMBR.DoTheyFit() && (protectiveMBR.GetValidity() == gpt)) {
7125f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      if (!beQuiet) {
7135f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith         cerr << "\aThe protective MBR's 0xEE partition is oversized! Auto-repairing.\n\n";
7145f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      } // if
7155f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      protectiveMBR.MakeProtectiveMBR();
7165f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   } // if
7175f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
7185f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   if (!beQuiet) {
7195f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      cout << "Partition table scan:\n";
720efb0d1e42f266efbd3d15b0c12c0790e90c5be66Dylan Noblesmith      protectiveMBR.ShowState();
721dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor      bsdDisklabel.ShowState();
722dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor      ShowAPMState(); // Show whether there's an Apple Partition Map present
7235f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      ShowGPTState(); // Show GPT status
7245f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      cout << "\n";
7255f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   } // if
7265f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
7275f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   if (apmFound) {
7285f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      cout << "\n*******************************************************************\n"
7295f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith           << "This disk appears to contain an Apple-format (APM) partition table!\n";
7305f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      if (!justLooking) {
7315f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith         cout << "It will be destroyed if you continue!\n";
7325f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      } // if
7335f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith      cout << "*******************************************************************\n\n\a";
7345f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   } // if
7355f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith} // GPTData::PartitionScan()
7365f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith
737efb0d1e42f266efbd3d15b0c12c0790e90c5be66Dylan Noblesmith// Read GPT data from a disk.
738dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregorint GPTData::LoadPartitions(const string & deviceFilename) {
739dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor   BSDData bsdDisklabel;
7405f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   int err, allOK = 1;
7415f36bb1759e35bd3aef4b6ce226e091849f6b816Dylan Noblesmith   MBRValidity mbrState;
742cbc7cc63b6c7ee1008f92064388c37327c183328Dan Gohman
743937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands   if (myDisk.OpenForRead(deviceFilename)) {
744937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands      err = myDisk.OpenForWrite(deviceFilename);
745cbc7cc63b6c7ee1008f92064388c37327c183328Dan Gohman      if ((err == 0) && (!justLooking)) {
746937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands         cout << "\aNOTE: Write test failed with error number " << errno
747937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands              << ". It will be impossible to save\nchanges to this disk's partition table!\n";
748cbc7cc63b6c7ee1008f92064388c37327c183328Dan Gohman#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
749937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands         cout << "You may be able to enable writes by exiting this program, typing\n"
750937708cea9de4bc65c8d3297fcf0396686729912Duncan Sands              << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
751cbc7cc63b6c7ee1008f92064388c37327c183328Dan Gohman              << "program.\n";
752cbc7cc63b6c7ee1008f92064388c37327c183328Dan Gohman#endif
753ae8f78d4de403965603ed2b61898d820db2449f9Erick Tryzelaar         cout << "\n";
7548d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      } // if
7558d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      myDisk.Close(); // Close and re-open read-only in case of bugs
7568d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich   } else allOK = 0; // if
7578d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich
7588d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich   if (allOK && myDisk.OpenForRead(deviceFilename)) {
7598d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      // store disk information....
7608d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      diskSize = myDisk.DiskSize(&err);
7618d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      blockSize = (uint32_t) myDisk.GetBlockSize();
7628d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      device = deviceFilename;
7638d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      PartitionScan(); // Check for partition types, load GPT, & print summary
7648d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich
7658d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      whichWasUsed = UseWhichPartitions();
7668d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich      switch (whichWasUsed) {
7678d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich         case use_mbr:
7688d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich            XFormPartitions();
7698d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich            break;
770d9103df51b858cf051a1650ac7eb33d416e9ac41Benjamin Kramer         case use_bsd:
771d9103df51b858cf051a1650ac7eb33d416e9ac41Benjamin Kramer            bsdDisklabel.ReadBSDData(&myDisk, 0, diskSize - 1);
7728d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich//            bsdDisklabel.DisplayBSDData();
7738d7285d0e5eb5937a6682e884b883516377e903dCameron Zwarich            ClearGPTData();
7742ad40a3663cb06c5f6d89a22933e22dc8b985574Erick Tryzelaar            protectiveMBR.MakeProtectiveMBR(1); // clear boot area (option 1)
775b5f59f5cf07babed5b4ba872815238e29386b0c5Jeffrey Yasskin            XFormDisklabel(&bsdDisklabel);
7761b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar            break;
777bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar         case use_gpt:
778bb97531a5a13c9d5b2f04b3b714037b1eff7e9a9Erick Tryzelaar            mbrState = protectiveMBR.GetValidity();
779dcd999624159842886d4be21efcc3ba0e61bab99Douglas Gregor            if ((mbrState == invalid) || (mbrState == mbr))
7801b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar               protectiveMBR.MakeProtectiveMBR();
7815504225c2accd5331ec56a739576c5b027ca868aBill Wendling            break;
7821b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar         case use_new:
7831b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar            ClearGPTData();
7841b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar            protectiveMBR.MakeProtectiveMBR();
7851b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar            break;
7861b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar         case use_abort:
7872ad40a3663cb06c5f6d89a22933e22dc8b985574Erick Tryzelaar            allOK = 0;
788b5f59f5cf07babed5b4ba872815238e29386b0c5Jeffrey Yasskin            cerr << "Invalid partition data!\n";
7891b9104ff80ec708dee522128b1f6a929fdd323ddErick Tryzelaar            break;
7909eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman      } // switch
7919eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman
7929eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman      if (allOK)
7939eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman         CheckGPTSize();
7949eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman      myDisk.Close();
7959eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman      ComputeAlignment();
7969eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman   } else {
7979eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman      allOK = 0;
7989eb6b4d91b83448ec818089754c74bbdcf7dfd7aEli Friedman   } // if/else
7993a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   return (allOK);
8003a3a424a248717487de826ddb48f14deec1d2446Eli Friedman} // GPTData::LoadPartitions()
8013a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
8023a3a424a248717487de826ddb48f14deec1d2446Eli Friedman// Loads the GPT, as much as possible. Returns 1 if this seems to have
8033a3a424a248717487de826ddb48f14deec1d2446Eli Friedman// succeeded, 0 if there are obvious problems....
8043a3a424a248717487de826ddb48f14deec1d2446Eli Friedmanint GPTData::ForceLoadGPTData(void) {
8053a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   int allOK, validHeaders, loadedTable = 1;
8063a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
8073a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   allOK = LoadHeader(&mainHeader, myDisk, 1, &mainCrcOk);
8083a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
8093a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   if (mainCrcOk && (mainHeader.backupLBA < diskSize)) {
8103a3a424a248717487de826ddb48f14deec1d2446Eli Friedman      allOK = LoadHeader(&secondHeader, myDisk, mainHeader.backupLBA, &secondCrcOk) && allOK;
8113a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   } else {
8123a3a424a248717487de826ddb48f14deec1d2446Eli Friedman      allOK = LoadHeader(&secondHeader, myDisk, diskSize - UINT64_C(1), &secondCrcOk) && allOK;
8133a3a424a248717487de826ddb48f14deec1d2446Eli Friedman      if (mainCrcOk && (mainHeader.backupLBA >= diskSize))
8143a3a424a248717487de826ddb48f14deec1d2446Eli Friedman         cout << "Warning! Disk size is smaller than the main header indicates! Loading\n"
8153a3a424a248717487de826ddb48f14deec1d2446Eli Friedman              << "secondary header from the last sector of the disk! You should use 'v' to\n"
8163a3a424a248717487de826ddb48f14deec1d2446Eli Friedman              << "verify disk integrity, and perhaps options on the experts' menu to repair\n"
8173a3a424a248717487de826ddb48f14deec1d2446Eli Friedman              << "the disk.\n";
8183a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   } // if/else
8193a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   if (!allOK)
8203a3a424a248717487de826ddb48f14deec1d2446Eli Friedman      state = gpt_invalid;
8213a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
8223a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   // Return valid headers code: 0 = both headers bad; 1 = main header
8230ae29a6b37204d95761a859d647f3e13a415c2d2Benjamin Kramer   // good, backup bad; 2 = backup header good, main header bad;
8240ae29a6b37204d95761a859d647f3e13a415c2d2Benjamin Kramer   // 3 = both headers good. Note these codes refer to valid GPT
8250ae29a6b37204d95761a859d647f3e13a415c2d2Benjamin Kramer   // signatures, version numbers, and CRCs.
8260ae29a6b37204d95761a859d647f3e13a415c2d2Benjamin Kramer   validHeaders = CheckHeaderValidity();
8273a3a424a248717487de826ddb48f14deec1d2446Eli Friedman
8283a3a424a248717487de826ddb48f14deec1d2446Eli Friedman   // Read partitions (from primary array)
829ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer   if (validHeaders > 0) { // if at least one header is OK....
830ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      // GPT appears to be valid....
831ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      state = gpt_valid;
832ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer
833ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      // We're calling the GPT valid, but there's a possibility that one
834ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      // of the two headers is corrupt. If so, use the one that seems to
835ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      // be in better shape to regenerate the bad one
836ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer      if (validHeaders == 1) { // valid main header, invalid backup header
837ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer         cerr << "\aCaution: invalid backup GPT header, but valid main header; regenerating\n"
838ad4da0fc321230261b4d0387f0ec216eb8aa50caBenjamin Kramer              << "backup header from main header.\n\n";
839a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         RebuildSecondHeader();
840a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         state = gpt_corrupt;
841a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         secondCrcOk = mainCrcOk; // Since regenerated, use CRC validity of main
842a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } else if (validHeaders == 2) { // valid backup header, invalid main header
843a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         cerr << "\aCaution: invalid main GPT header, but valid backup; regenerating main header\n"
844a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman              << "from backup!\n\n";
845a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         RebuildMainHeader();
846a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         state = gpt_corrupt;
847a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         mainCrcOk = secondCrcOk; // Since copied, use CRC validity of backup
848a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } // if/else/if
849a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman
850a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      // Figure out which partition table to load....
851a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      // Load the main partition table, since either its header's CRC is OK or the
852a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      // backup header's CRC is not OK....
853a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      if (mainCrcOk || !secondCrcOk) {
854a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         if (LoadMainTable() == 0)
855a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman            allOK = 0;
856a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } else { // bad main header CRC and backup header CRC is OK
857a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         state = gpt_corrupt;
858a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         if (LoadSecondTableAsMain()) {
859a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman            loadedTable = 2;
860a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman            cerr << "\aWarning: Invalid CRC on main header data; loaded backup partition table.\n";
861a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         } else { // backup table bad, bad main header CRC, but try main table in desperation....
862a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman            if (LoadMainTable() == 0) {
863a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman               allOK = 0;
864a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman               loadedTable = 0;
865a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman               cerr << "\a\aWarning! Unable to load either main or backup partition table!\n";
866a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman            } // if
867a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         } // if/else (LoadSecondTableAsMain())
868a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } // if/else (load partition table)
869a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman
870a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      if (loadedTable == 1)
871a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         secondPartsCrcOk = CheckTable(&secondHeader);
872a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      else if (loadedTable == 2)
873a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         mainPartsCrcOk = CheckTable(&mainHeader);
874a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      else
875a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         mainPartsCrcOk = secondPartsCrcOk = 0;
876a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman
877a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      // Problem with main partition table; if backup is OK, use it instead....
878a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      if (secondPartsCrcOk && secondCrcOk && !mainPartsCrcOk) {
879a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         state = gpt_corrupt;
880a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         allOK = allOK && LoadSecondTableAsMain();
881a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         mainPartsCrcOk = 0; // LoadSecondTableAsMain() resets this, so re-flag as bad
882a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         cerr << "\aWarning! Main partition table CRC mismatch! Loaded backup "
883a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman              << "partition table\ninstead of main partition table!\n\n";
884a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } // if */
885a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman
886a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      // Check for valid CRCs and warn if there are problems
887a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      if ((mainCrcOk == 0) || (secondCrcOk == 0) || (mainPartsCrcOk == 0) ||
888a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman           (secondPartsCrcOk == 0)) {
889a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         cerr << "Warning! One or more CRCs don't match. You should repair the disk!\n\n";
890a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman         state = gpt_corrupt;
891a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      } // if
892a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman   } else {
893a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman      state = gpt_invalid;
894a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman   } // if/else
895a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman   return allOK;
896a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman} // GPTData::ForceLoadGPTData()
897a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman
898a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman// Loads the partition table pointed to by the main GPT header. The
899a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman// main GPT header in memory MUST be valid for this call to do anything
900a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman// sensible!
901a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
902a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesmanint GPTData::LoadMainTable(void) {
903a32edcfbc5b99b808b67360311d513af650eab44Michael Gottesman   return LoadPartitionTable(mainHeader, myDisk);
90436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines} // GPTData::LoadMainTable()
90536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
90636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Load the second (backup) partition table as the primary partition
90736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// table. Used in repair functions, and when starting up if the main
90836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// partition table is damaged.
90936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
91036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesint GPTData::LoadSecondTableAsMain(void) {
91136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   return LoadPartitionTable(secondHeader, myDisk);
91236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines} // GPTData::LoadSecondTableAsMain()
91336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
91436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Load a single GPT header (main or backup) from the specified disk device and
91536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// sector. Applies byte-order corrections on big-endian platforms. Sets crcOk
91636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// value appropriately.
91736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Returns 1 on success, 0 on failure. Note that CRC errors do NOT qualify as
91836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// failure.
91936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesint GPTData::LoadHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector, int *crcOk) {
92036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   int allOK = 1;
92137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   GPTHeader tempHeader;
92236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
92336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   disk.Seek(sector);
92436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   if (disk.Read(&tempHeader, 512) != 512) {
92536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      cerr << "Warning! Read error " << errno << "; strange behavior now likely!\n";
92636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      allOK = 0;
92736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   } // if
92836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
92936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   // Reverse byte order, if necessary
93036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   if (IsLittleEndian() == 0) {
93136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      ReverseHeaderBytes(&tempHeader);
93236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   } // if
93336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   *crcOk = CheckHeaderCRC(&tempHeader);
93436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
93536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   if (allOK && (numParts != tempHeader.numParts) && *crcOk) {
93636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      allOK = SetGPTSize(tempHeader.numParts, 0);
93736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   }
93836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
93936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   *header = tempHeader;
94036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   return allOK;
94136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines} // GPTData::LoadHeader
94236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
94336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Load a partition table (either main or secondary) from the specified disk,
94436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// using header as a reference for what to load. If sector != 0 (the default
94536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// is 0), loads from the specified sector; otherwise loads from the sector
94636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// indicated in header.
94736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Returns 1 on success, 0 on failure. CRC errors do NOT count as failure.
94836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesint GPTData::LoadPartitionTable(const struct GPTHeader & header, DiskIO & disk, uint64_t sector) {
94936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   uint32_t sizeOfParts, newCRC;
95036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   int retval;
95136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
95236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   if (disk.OpenForRead()) {
95336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (sector == 0) {
95436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         retval = disk.Seek(header.partitionEntriesLBA);
95536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } else {
95636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         retval = disk.Seek(sector);
95736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } // if/else
95836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (retval == 1)
95936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         retval = SetGPTSize(header.numParts, 0);
96037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (retval == 1) {
96136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         sizeOfParts = header.numParts * header.sizeOfPartitionEntries;
96236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         if (disk.Read(partitions, sizeOfParts) != (int) sizeOfParts) {
96336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines            cerr << "Warning! Read error " << errno << "! Misbehavior now likely!\n";
96436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines            retval = 0;
96537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines         } // if
96636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         newCRC = chksum_crc32((unsigned char*) partitions, sizeOfParts);
96736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         mainPartsCrcOk = secondPartsCrcOk = (newCRC == header.partitionEntriesCRC);
96836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         if (IsLittleEndian() == 0)
96936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines            ReversePartitionBytes();
97037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines         if (!mainPartsCrcOk) {
97136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines            cout << "Caution! After loading partitions, the CRC doesn't check out!\n";
97236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         } // if
97336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } else {
97436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         cerr << "Error! Couldn't seek to partition table!\n";
97536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      } // if/else
97636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   } else {
97736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      cerr << "Error! Couldn't open device " << device
97836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines           << " when reading partition table!\n";
97936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      retval = 0;
98036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   } // if/else
98136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines   return retval;
98236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines} // GPTData::LoadPartitionsTable()
98336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
98436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// Check the partition table pointed to by header, but don't keep it
9854c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// around.
9864c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// Returns 1 if the CRC is OK & this table matches the one already in memory,
9874c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// 0 if not or if there was a read error.
9884c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarint GPTData::CheckTable(struct GPTHeader *header) {
9894c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   uint32_t sizeOfParts, newCRC;
9904c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   GPTPart *partsToCheck;
9914c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   GPTHeader *otherHeader;
9924c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   int allOK = 0;
9934c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
9944c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   // Load partition table into temporary storage to check
9954c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   // its CRC and store the results, then discard this temporary
9964c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   // storage, since we don't use it in any but recovery operations
9974c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   if (myDisk.Seek(header->partitionEntriesLBA)) {
9984c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      partsToCheck = new GPTPart[header->numParts];
9994c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      sizeOfParts = header->numParts * header->sizeOfPartitionEntries;
10004c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (partsToCheck == NULL) {
10014c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         cerr << "Could not allocate memory in GPTData::CheckTable()! Terminating!\n";
10024c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         exit(1);
10034c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      } // if
10044c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      if (myDisk.Read(partsToCheck, sizeOfParts) != (int) sizeOfParts) {
10054c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         cerr << "Warning! Error " << errno << " reading partition table for CRC check!\n";
10064c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      } else {
10074c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         newCRC = chksum_crc32((unsigned char*) partsToCheck, sizeOfParts);
10084c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         allOK = (newCRC == header->partitionEntriesCRC);
10094c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         if (header == &mainHeader)
10104c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            otherHeader = &secondHeader;
10114c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         else
10124c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            otherHeader = &mainHeader;
10134c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         if (newCRC != otherHeader->partitionEntriesCRC) {
10144c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            cerr << "Warning! Main and backup partition tables differ! Use the 'c' and 'e' options\n"
10154c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                 << "on the recovery & transformation menu to examine the two tables.\n\n";
10164c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar            allOK = 0;
10174c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar         } // if
10184c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      } // if/else
10194c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar      delete[] partsToCheck;
10204c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   } // if
10214c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar   return allOK;
10224c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar} // GPTData::CheckTable()
10234c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar
10244c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar// Writes GPT (and protective MBR) to disk. If quiet==1, moves the second
1025de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// header later on the disk without asking for permission, if necessary, and
1026de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// doesn't confirm the operation before writing. If quiet==0, asks permission
1027de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// before moving the second header and asks for final confirmation of any
1028de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// write.
1029de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar// Returns 1 on successful write, 0 if there was a problem.
1030de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainarint GPTData::SaveGPTData(int quiet) {
1031de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   int allOK = 1, syncIt = 1;
1032de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   char answer;
1033de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1034de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // First do some final sanity checks....
1035de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1036de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // This test should only fail on read-only disks....
1037de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if (justLooking) {
1038de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      cout << "The justLooking flag is set. This probably means you can't write to the disk.\n";
1039de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      allOK = 0;
1040de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   } // if
1041de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1042ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines   // Check that disk is really big enough to handle the second header...
1043ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines   if (mainHeader.backupLBA >= diskSize) {
1044ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      cerr << "Caution! Secondary header was placed beyond the disk's limits! Moving the\n"
1045ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines           << "header, but other problems may occur!\n";
1046ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      MoveSecondHeaderToEnd();
1047ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines   } // if
1048ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
1049ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines   // Is there enough space to hold the GPT headers and partition tables,
105037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   // given the partition sizes?
105137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   if (CheckGPTSize() > 0) {
105237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      allOK = 0;
105337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   } // if
105437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
105537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   // Check that second header is properly placed. Warn and ask if this should
105637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   // be corrected if the test fails....
105737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines   if (mainHeader.backupLBA < (diskSize - UINT64_C(1))) {
105837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (quiet == 0) {
105937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines         cout << "Warning! Secondary header is placed too early on the disk! Do you want to\n"
106037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines              << "correct this problem? ";
106137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines         if (GetYN() == 'Y') {
106237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MoveSecondHeaderToEnd();
106337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            cout << "Have moved second header and partition table to correct location.\n";
106437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines         } else {
106537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1066ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines         } // if correction requested
1067ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      } else { // Go ahead and do correction automatically
1068ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines         MoveSecondHeaderToEnd();
1069ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      } // if/else quiet
10701999ff1d810b13425fcb80ac8bbccdff4c3a7cf8Nick Lewycky   } // if
1071de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1072de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if ((mainHeader.lastUsableLBA >= diskSize) || (mainHeader.lastUsableLBA > mainHeader.backupLBA)) {
1073de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (quiet == 0) {
1074de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         cout << "Warning! The claimed last usable sector is incorrect! Do you want to correct\n"
1075de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar              << "this problem? ";
1076de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         if (GetYN() == 'Y') {
1077de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            MoveSecondHeaderToEnd();
1078de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            cout << "Have adjusted the second header and last usable sector value.\n";
1079de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         } else {
1080de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar            cout << "Have not corrected the problem. Strange problems may occur in the future!\n";
1081de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         } // if correction requested
1082de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      } else { // go ahead and do correction automatically
1083de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         MoveSecondHeaderToEnd();
1084de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      } // if/else quiet
1085de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   } // if
1086de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1087de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // Check for overlapping or insane partitions....
1088de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if ((FindOverlaps() > 0) || (FindInsanePartitions() > 0)) {
1089de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      allOK = 0;
1090de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      cerr << "Aborting write operation!\n";
1091de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   } // if
1092de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1093de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // Check that protective MBR fits, and warn if it doesn't....
1094de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if (!protectiveMBR.DoTheyFit()) {
1095de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      cerr << "\nPartition(s) in the protective MBR are too big for the disk! Creating a\n"
1096de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar           << "fresh protective or hybrid MBR is recommended.\n";
1097de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   }
1098de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1099de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // Check for mismatched MBR and GPT data, but let it pass if found
1100de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   // (function displays warning message)
1101de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   FindHybridMismatches();
1102de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1103de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   RecomputeCRCs();
1104de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar
1105de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar   if ((allOK) && (!quiet)) {
1106de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      cout << "\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\n"
1107de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar           << "PARTITIONS!!\n\nDo you want to proceed? ";
1108de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      answer = GetYN();
1109de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      if (answer == 'Y') {
1110de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         cout << "OK; writing new GUID partition table (GPT) to " << myDisk.GetName() << ".\n";
1111de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar      } else {
1112de2d8694e25a814696358e95141f4b1aa4d8847ePirama Arumuga Nainar         allOK = 0;
1113      } // if/else
1114   } // if
1115
1116   // Do it!
1117   if (allOK) {
1118      if (myDisk.OpenForWrite()) {
1119         // As per UEFI specs, write the secondary table and GPT first....
1120         allOK = SavePartitionTable(myDisk, secondHeader.partitionEntriesLBA);
1121         if (!allOK) {
1122            cerr << "Unable to save backup partition table! Perhaps the 'e' option on the experts'\n"
1123                 << "menu will resolve this problem.\n";
1124            syncIt = 0;
1125         } // if
1126
1127         // Now write the secondary GPT header...
1128         allOK = allOK && SaveHeader(&secondHeader, myDisk, mainHeader.backupLBA);
1129
1130         // Now write the main partition tables...
1131         allOK = allOK && SavePartitionTable(myDisk, mainHeader.partitionEntriesLBA);
1132
1133         // Now write the main GPT header...
1134         allOK = allOK && SaveHeader(&mainHeader, myDisk, 1);
1135
1136         // To top it off, write the protective MBR...
1137         allOK = allOK && protectiveMBR.WriteMBRData(&myDisk);
1138
1139         // re-read the partition table
1140         // Note: Done even if some write operations failed, but not if all of them failed.
1141         // Done this way because I've received one problem report from a user one whose
1142         // system the MBR write failed but everything else was OK (on a GPT disk under
1143         // Windows), and the failure to sync therefore caused Windows to restore the
1144         // original partition table from its cache. OTOH, such restoration might be
1145         // desirable if the error occurs later; but that seems unlikely unless the initial
1146         // write fails....
1147         if (syncIt)
1148            myDisk.DiskSync();
1149
1150         if (allOK) { // writes completed OK
1151            cout << "The operation has completed successfully.\n";
1152         } else {
1153            cerr << "Warning! An error was reported when writing the partition table! This error\n"
1154                 << "MIGHT be harmless, or the disk might be damaged! Checking it is advisable.\n";
1155         } // if/else
1156
1157         myDisk.Close();
1158      } else {
1159         cerr << "Unable to open device '" << myDisk.GetName() << "' for writing! Errno is "
1160              << errno << "! Aborting write!\n";
1161         allOK = 0;
1162      } // if/else
1163   } else {
1164      cout << "Aborting write of new partition table.\n";
1165   } // if
1166
1167   return (allOK);
1168} // GPTData::SaveGPTData()
1169
1170// Save GPT data to a backup file. This function does much less error
1171// checking than SaveGPTData(). It can therefore preserve many types of
1172// corruption for later analysis; however, it preserves only the MBR,
1173// the main GPT header, the backup GPT header, and the main partition
1174// table; it discards the backup partition table, since it should be
1175// identical to the main partition table on healthy disks.
1176int GPTData::SaveGPTBackup(const string & filename) {
1177   int allOK = 1;
1178   DiskIO backupFile;
1179
1180   if (backupFile.OpenForWrite(filename)) {
1181      // Recomputing the CRCs is likely to alter them, which could be bad
1182      // if the intent is to save a potentially bad GPT for later analysis;
1183      // but if we don't do this, we get bogus errors when we load the
1184      // backup. I'm favoring misses over false alarms....
1185      RecomputeCRCs();
1186
1187      protectiveMBR.WriteMBRData(&backupFile);
1188      protectiveMBR.SetDisk(&myDisk);
1189
1190      if (allOK) {
1191         // MBR write closed disk, so re-open and seek to end....
1192         backupFile.OpenForWrite();
1193         allOK = SaveHeader(&mainHeader, backupFile, 1);
1194      } // if (allOK)
1195
1196      if (allOK)
1197         allOK = SaveHeader(&secondHeader, backupFile, 2);
1198
1199      if (allOK)
1200         allOK = SavePartitionTable(backupFile, 3);
1201
1202      if (allOK) { // writes completed OK
1203         cout << "The operation has completed successfully.\n";
1204      } else {
1205         cerr << "Warning! An error was reported when writing the backup file.\n"
1206              << "It may not be usable!\n";
1207      } // if/else
1208      backupFile.Close();
1209   } else {
1210      cerr << "Unable to open file '" << filename << "' for writing! Aborting!\n";
1211      allOK = 0;
1212   } // if/else
1213   return allOK;
1214} // GPTData::SaveGPTBackup()
1215
1216// Write a GPT header (main or backup) to the specified sector. Used by both
1217// the SaveGPTData() and SaveGPTBackup() functions.
1218// Should be passed an architecture-appropriate header (DO NOT call
1219// ReverseHeaderBytes() on the header before calling this function)
1220// Returns 1 on success, 0 on failure
1221int GPTData::SaveHeader(struct GPTHeader *header, DiskIO & disk, uint64_t sector) {
1222   int littleEndian, allOK = 1;
1223
1224   littleEndian = IsLittleEndian();
1225   if (!littleEndian)
1226      ReverseHeaderBytes(header);
1227   if (disk.Seek(sector)) {
1228      if (disk.Write(header, 512) == -1)
1229         allOK = 0;
1230   } else allOK = 0; // if (disk.Seek()...)
1231   if (!littleEndian)
1232      ReverseHeaderBytes(header);
1233   return allOK;
1234} // GPTData::SaveHeader()
1235
1236// Save the partitions to the specified sector. Used by both the SaveGPTData()
1237// and SaveGPTBackup() functions.
1238// Should be passed an architecture-appropriate header (DO NOT call
1239// ReverseHeaderBytes() on the header before calling this function)
1240// Returns 1 on success, 0 on failure
1241int GPTData::SavePartitionTable(DiskIO & disk, uint64_t sector) {
1242   int littleEndian, allOK = 1;
1243
1244   littleEndian = IsLittleEndian();
1245   if (disk.Seek(sector)) {
1246      if (!littleEndian)
1247         ReversePartitionBytes();
1248      if (disk.Write(partitions, mainHeader.sizeOfPartitionEntries * numParts) == -1)
1249         allOK = 0;
1250      if (!littleEndian)
1251         ReversePartitionBytes();
1252   } else allOK = 0; // if (myDisk.Seek()...)
1253   return allOK;
1254} // GPTData::SavePartitionTable()
1255
1256// Load GPT data from a backup file created by SaveGPTBackup(). This function
1257// does minimal error checking. It returns 1 if it completed successfully,
1258// 0 if there was a problem. In the latter case, it creates a new empty
1259// set of partitions.
1260int GPTData::LoadGPTBackup(const string & filename) {
1261   int allOK = 1, val, err;
1262   int shortBackup = 0;
1263   DiskIO backupFile;
1264
1265   if (backupFile.OpenForRead(filename)) {
1266      // Let the MBRData class load the saved MBR...
1267      protectiveMBR.ReadMBRData(&backupFile, 0); // 0 = don't check block size
1268      protectiveMBR.SetDisk(&myDisk);
1269
1270      LoadHeader(&mainHeader, backupFile, 1, &mainCrcOk);
1271
1272      // Check backup file size and rebuild second header if file is right
1273      // size to be direct dd copy of MBR, main header, and main partition
1274      // table; if other size, treat it like a GPT fdisk-generated backup
1275      // file
1276      shortBackup = ((backupFile.DiskSize(&err) * backupFile.GetBlockSize()) ==
1277                     (mainHeader.numParts * mainHeader.sizeOfPartitionEntries) + 1024);
1278      if (shortBackup) {
1279         RebuildSecondHeader();
1280         secondCrcOk = mainCrcOk;
1281      } else {
1282         LoadHeader(&secondHeader, backupFile, 2, &secondCrcOk);
1283      } // if/else
1284
1285      // Return valid headers code: 0 = both headers bad; 1 = main header
1286      // good, backup bad; 2 = backup header good, main header bad;
1287      // 3 = both headers good. Note these codes refer to valid GPT
1288      // signatures and version numbers; more subtle problems will elude
1289      // this check!
1290      if ((val = CheckHeaderValidity()) > 0) {
1291         if (val == 2) { // only backup header seems to be good
1292            SetGPTSize(secondHeader.numParts, 0);
1293         } else { // main header is OK
1294            SetGPTSize(mainHeader.numParts, 0);
1295         } // if/else
1296
1297         if (secondHeader.currentLBA != diskSize - UINT64_C(1)) {
1298            cout << "Warning! Current disk size doesn't match that of the backup!\n"
1299                 << "Adjusting sizes to match, but subsequent problems are possible!\n";
1300            MoveSecondHeaderToEnd();
1301         } // if
1302
1303         if (!LoadPartitionTable(mainHeader, backupFile, (uint64_t) (3 - shortBackup)))
1304            cerr << "Warning! Read error " << errno
1305                 << " loading partition table; strange behavior now likely!\n";
1306      } else {
1307         allOK = 0;
1308      } // if/else
1309      // Something went badly wrong, so blank out partitions
1310      if (allOK == 0) {
1311         cerr << "Improper backup file! Clearing all partition data!\n";
1312         ClearGPTData();
1313         protectiveMBR.MakeProtectiveMBR();
1314      } // if
1315   } else {
1316      allOK = 0;
1317      cerr << "Unable to open file '" << filename << "' for reading! Aborting!\n";
1318   } // if/else
1319
1320   return allOK;
1321} // GPTData::LoadGPTBackup()
1322
1323int GPTData::SaveMBR(void) {
1324   return protectiveMBR.WriteMBRData(&myDisk);
1325} // GPTData::SaveMBR()
1326
1327// This function destroys the on-disk GPT structures, but NOT the on-disk
1328// MBR.
1329// Returns 1 if the operation succeeds, 0 if not.
1330int GPTData::DestroyGPT(void) {
1331   int sum, tableSize, allOK = 1;
1332   uint8_t blankSector[512];
1333   uint8_t* emptyTable;
1334
1335   memset(blankSector, 0, sizeof(blankSector));
1336   ClearGPTData();
1337
1338   if (myDisk.OpenForWrite()) {
1339      if (!myDisk.Seek(mainHeader.currentLBA))
1340         allOK = 0;
1341      if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1342         cerr << "Warning! GPT main header not overwritten! Error is " << errno << "\n";
1343         allOK = 0;
1344      } // if
1345      if (!myDisk.Seek(mainHeader.partitionEntriesLBA))
1346         allOK = 0;
1347      tableSize = numParts * mainHeader.sizeOfPartitionEntries;
1348      emptyTable = new uint8_t[tableSize];
1349      if (emptyTable == NULL) {
1350         cerr << "Could not allocate memory in GPTData::DestroyGPT()! Terminating!\n";
1351         exit(1);
1352      } // if
1353      memset(emptyTable, 0, tableSize);
1354      if (allOK) {
1355         sum = myDisk.Write(emptyTable, tableSize);
1356         if (sum != tableSize) {
1357            cerr << "Warning! GPT main partition table not overwritten! Error is " << errno << "\n";
1358            allOK = 0;
1359         } // if write failed
1360      } // if
1361      if (!myDisk.Seek(secondHeader.partitionEntriesLBA))
1362         allOK = 0;
1363      if (allOK) {
1364         sum = myDisk.Write(emptyTable, tableSize);
1365         if (sum != tableSize) {
1366            cerr << "Warning! GPT backup partition table not overwritten! Error is "
1367                 << errno << "\n";
1368            allOK = 0;
1369         } // if wrong size written
1370      } // if
1371      if (!myDisk.Seek(secondHeader.currentLBA))
1372         allOK = 0;
1373      if (allOK) {
1374         if (myDisk.Write(blankSector, 512) != 512) { // blank it out
1375            cerr << "Warning! GPT backup header not overwritten! Error is " << errno << "\n";
1376            allOK = 0;
1377         } // if
1378      } // if
1379      myDisk.DiskSync();
1380      myDisk.Close();
1381      cout << "GPT data structures destroyed! You may now partition the disk using fdisk or\n"
1382           << "other utilities.\n";
1383      delete[] emptyTable;
1384   } else {
1385      cerr << "Problem opening '" << device << "' for writing! Program will now terminate.\n";
1386   } // if/else (fd != -1)
1387   return (allOK);
1388} // GPTDataTextUI::DestroyGPT()
1389
1390// Wipe MBR data from the disk (zero it out completely)
1391// Returns 1 on success, 0 on failure.
1392int GPTData::DestroyMBR(void) {
1393   int allOK;
1394   uint8_t blankSector[512];
1395
1396   memset(blankSector, 0, sizeof(blankSector));
1397
1398   allOK = myDisk.OpenForWrite() && myDisk.Seek(0) && (myDisk.Write(blankSector, 512) == 512);
1399
1400   if (!allOK)
1401      cerr << "Warning! MBR not overwritten! Error is " << errno << "!\n";
1402   return allOK;
1403} // GPTData::DestroyMBR(void)
1404
1405// Tell user whether Apple Partition Map (APM) was discovered....
1406void GPTData::ShowAPMState(void) {
1407   if (apmFound)
1408      cout << "  APM: present\n";
1409   else
1410      cout << "  APM: not present\n";
1411} // GPTData::ShowAPMState()
1412
1413// Tell user about the state of the GPT data....
1414void GPTData::ShowGPTState(void) {
1415   switch (state) {
1416      case gpt_invalid:
1417         cout << "  GPT: not present\n";
1418         break;
1419      case gpt_valid:
1420         cout << "  GPT: present\n";
1421         break;
1422      case gpt_corrupt:
1423         cout << "  GPT: damaged\n";
1424         break;
1425      default:
1426         cout << "\a  GPT: unknown -- bug!\n";
1427         break;
1428   } // switch
1429} // GPTData::ShowGPTState()
1430
1431// Display the basic GPT data
1432void GPTData::DisplayGPTData(void) {
1433   uint32_t i;
1434   uint64_t temp, totalFree;
1435
1436   cout << "Disk " << device << ": " << diskSize << " sectors, "
1437        << BytesToIeee(diskSize, blockSize) << "\n";
1438   cout << "Logical sector size: " << blockSize << " bytes\n";
1439   cout << "Disk identifier (GUID): " << mainHeader.diskGUID << "\n";
1440   cout << "Partition table holds up to " << numParts << " entries\n";
1441   cout << "First usable sector is " << mainHeader.firstUsableLBA
1442        << ", last usable sector is " << mainHeader.lastUsableLBA << "\n";
1443   totalFree = FindFreeBlocks(&i, &temp);
1444   cout << "Partitions will be aligned on " << sectorAlignment << "-sector boundaries\n";
1445   cout << "Total free space is " << totalFree << " sectors ("
1446        << BytesToIeee(totalFree, blockSize) << ")\n";
1447   cout << "\nNumber  Start (sector)    End (sector)  Size       Code  Name\n";
1448   for (i = 0; i < numParts; i++) {
1449      partitions[i].ShowSummary(i, blockSize);
1450   } // for
1451} // GPTData::DisplayGPTData()
1452
1453// Show detailed information on the specified partition
1454void GPTData::ShowPartDetails(uint32_t partNum) {
1455   if ((partNum < numParts) && !IsFreePartNum(partNum)) {
1456      partitions[partNum].ShowDetails(blockSize);
1457   } else {
1458      cout << "Partition #" << partNum + 1 << " does not exist.\n";
1459   } // if
1460} // GPTData::ShowPartDetails()
1461
1462/**************************************************************************
1463 *                                                                        *
1464 * Partition table transformation functions (MBR or BSD disklabel to GPT) *
1465 * (some of these functions may require user interaction)                 *
1466 *                                                                        *
1467 **************************************************************************/
1468
1469// Examines the MBR & GPT data to determine which set of data to use: the
1470// MBR (use_mbr), the GPT (use_gpt), the BSD disklabel (use_bsd), or create
1471// a new set of partitions (use_new). A return value of use_abort indicates
1472// that this function couldn't determine what to do. Overriding functions
1473// in derived classes may ask users questions in such cases.
1474WhichToUse GPTData::UseWhichPartitions(void) {
1475   WhichToUse which = use_new;
1476   MBRValidity mbrState;
1477
1478   mbrState = protectiveMBR.GetValidity();
1479
1480   if ((state == gpt_invalid) && ((mbrState == mbr) || (mbrState == hybrid))) {
1481      cout << "\n***************************************************************\n"
1482           << "Found invalid GPT and valid MBR; converting MBR to GPT format\n"
1483           << "in memory. ";
1484      if (!justLooking) {
1485         cout << "\aTHIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by\n"
1486              << "typing 'q' if you don't want to convert your MBR partitions\n"
1487              << "to GPT format!";
1488      } // if
1489      cout << "\n***************************************************************\n\n";
1490      which = use_mbr;
1491   } // if
1492
1493   if ((state == gpt_invalid) && bsdFound) {
1494      cout << "\n**********************************************************************\n"
1495           << "Found invalid GPT and valid BSD disklabel; converting BSD disklabel\n"
1496           << "to GPT format.";
1497      if ((!justLooking) && (!beQuiet)) {
1498      cout << "\a THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Your first\n"
1499           << "BSD partition will likely be unusable. Exit by typing 'q' if you don't\n"
1500           << "want to convert your BSD partitions to GPT format!";
1501      } // if
1502      cout << "\n**********************************************************************\n\n";
1503      which = use_bsd;
1504   } // if
1505
1506   if ((state == gpt_valid) && (mbrState == gpt)) {
1507      which = use_gpt;
1508      if (!beQuiet)
1509         cout << "Found valid GPT with protective MBR; using GPT.\n";
1510   } // if
1511   if ((state == gpt_valid) && (mbrState == hybrid)) {
1512      which = use_gpt;
1513      if (!beQuiet)
1514         cout << "Found valid GPT with hybrid MBR; using GPT.\n";
1515   } // if
1516   if ((state == gpt_valid) && (mbrState == invalid)) {
1517      cout << "\aFound valid GPT with corrupt MBR; using GPT and will write new\n"
1518           << "protective MBR on save.\n";
1519      which = use_gpt;
1520   } // if
1521   if ((state == gpt_valid) && (mbrState == mbr)) {
1522      which = use_abort;
1523   } // if
1524
1525   if (state == gpt_corrupt) {
1526      if (mbrState == gpt) {
1527         cout << "\a\a****************************************************************************\n"
1528              << "Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk\n"
1529              << "verification and recovery are STRONGLY recommended.\n"
1530              << "****************************************************************************\n";
1531         which = use_gpt;
1532      } else {
1533         which = use_abort;
1534      } // if/else MBR says disk is GPT
1535   } // if GPT corrupt
1536
1537   if (which == use_new)
1538      cout << "Creating new GPT entries.\n";
1539
1540   return which;
1541} // UseWhichPartitions()
1542
1543// Convert MBR partition table into GPT form.
1544void GPTData::XFormPartitions(void) {
1545   int i, numToConvert;
1546   uint8_t origType;
1547
1548   // Clear out old data & prepare basics....
1549   ClearGPTData();
1550
1551   // Convert the smaller of the # of GPT or MBR partitions
1552   if (numParts > MAX_MBR_PARTS)
1553      numToConvert = MAX_MBR_PARTS;
1554   else
1555      numToConvert = numParts;
1556
1557   for (i = 0; i < numToConvert; i++) {
1558      origType = protectiveMBR.GetType(i);
1559      // don't waste CPU time trying to convert extended, hybrid protective, or
1560      // null (non-existent) partitions
1561      if ((origType != 0x05) && (origType != 0x0f) && (origType != 0x85) &&
1562          (origType != 0x00) && (origType != 0xEE))
1563         partitions[i] = protectiveMBR.AsGPT(i);
1564   } // for
1565
1566   // Convert MBR into protective MBR
1567   protectiveMBR.MakeProtectiveMBR();
1568
1569   // Record that all original CRCs were OK so as not to raise flags
1570   // when doing a disk verification
1571   mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1572} // GPTData::XFormPartitions()
1573
1574// Transforms BSD disklabel on the specified partition (numbered from 0).
1575// If an invalid partition number is given, the program does nothing.
1576// Returns the number of new partitions created.
1577int GPTData::XFormDisklabel(uint32_t partNum) {
1578   uint32_t low, high;
1579   int goOn = 1, numDone = 0;
1580   BSDData disklabel;
1581
1582   if (GetPartRange(&low, &high) == 0) {
1583      goOn = 0;
1584      cout << "No partitions!\n";
1585   } // if
1586   if (partNum > high) {
1587      goOn = 0;
1588      cout << "Specified partition is invalid!\n";
1589   } // if
1590
1591   // If all is OK, read the disklabel and convert it.
1592   if (goOn) {
1593      goOn = disklabel.ReadBSDData(&myDisk, partitions[partNum].GetFirstLBA(),
1594                                   partitions[partNum].GetLastLBA());
1595      if ((goOn) && (disklabel.IsDisklabel())) {
1596         numDone = XFormDisklabel(&disklabel);
1597         if (numDone == 1)
1598            cout << "Converted 1 BSD partition.\n";
1599         else
1600            cout << "Converted " << numDone << " BSD partitions.\n";
1601      } else {
1602         cout << "Unable to convert partitions! Unrecognized BSD disklabel.\n";
1603      } // if/else
1604   } // if
1605   if (numDone > 0) { // converted partitions; delete carrier
1606      partitions[partNum].BlankPartition();
1607   } // if
1608   return numDone;
1609} // GPTData::XFormDisklabel(uint32_t i)
1610
1611// Transform the partitions on an already-loaded BSD disklabel...
1612int GPTData::XFormDisklabel(BSDData* disklabel) {
1613   int i, partNum = 0, numDone = 0;
1614
1615   if (disklabel->IsDisklabel()) {
1616      for (i = 0; i < disklabel->GetNumParts(); i++) {
1617         partNum = FindFirstFreePart();
1618         if (partNum >= 0) {
1619            partitions[partNum] = disklabel->AsGPT(i);
1620            if (partitions[partNum].IsUsed())
1621               numDone++;
1622         } // if
1623      } // for
1624      if (partNum == -1)
1625         cerr << "Warning! Too many partitions to convert!\n";
1626   } // if
1627
1628   // Record that all original CRCs were OK so as not to raise flags
1629   // when doing a disk verification
1630   mainCrcOk = secondCrcOk = mainPartsCrcOk = secondPartsCrcOk = 1;
1631
1632   return numDone;
1633} // GPTData::XFormDisklabel(BSDData* disklabel)
1634
1635// Add one GPT partition to MBR. Used by PartsToMBR() functions. Created
1636// partition has the active/bootable flag UNset and uses the GPT fdisk
1637// type code divided by 0x0100 as the MBR type code.
1638// Returns 1 if operation was 100% successful, 0 if there were ANY
1639// problems.
1640int GPTData::OnePartToMBR(uint32_t gptPart, int mbrPart) {
1641   int allOK = 1;
1642
1643   if ((mbrPart < 0) || (mbrPart > 3)) {
1644      cout << "MBR partition " << mbrPart + 1 << " is out of range; omitting it.\n";
1645      allOK = 0;
1646   } // if
1647   if (gptPart >= numParts) {
1648      cout << "GPT partition " << gptPart + 1 << " is out of range; omitting it.\n";
1649      allOK = 0;
1650   } // if
1651   if (allOK && (partitions[gptPart].GetLastLBA() == UINT64_C(0))) {
1652      cout << "GPT partition " << gptPart + 1 << " is undefined; omitting it.\n";
1653      allOK = 0;
1654   } // if
1655   if (allOK && (partitions[gptPart].GetFirstLBA() <= UINT32_MAX) &&
1656       (partitions[gptPart].GetLengthLBA() <= UINT32_MAX)) {
1657      if (partitions[gptPart].GetLastLBA() > UINT32_MAX) {
1658         cout << "Caution: Partition end point past 32-bit pointer boundary;"
1659              << " some OSes may\nreact strangely.\n";
1660      } // if
1661      protectiveMBR.MakePart(mbrPart, (uint32_t) partitions[gptPart].GetFirstLBA(),
1662                             (uint32_t) partitions[gptPart].GetLengthLBA(),
1663                             partitions[gptPart].GetHexType() / 256, 0);
1664   } else { // partition out of range
1665      if (allOK) // Display only if "else" triggered by out-of-bounds condition
1666         cout << "Partition " << gptPart + 1 << " begins beyond the 32-bit pointer limit of MBR "
1667              << "partitions, or is\n too big; omitting it.\n";
1668      allOK = 0;
1669   } // if/else
1670   return allOK;
1671} // GPTData::OnePartToMBR()
1672
1673
1674/**********************************************************************
1675 *                                                                    *
1676 * Functions that adjust GPT data structures WITHOUT user interaction *
1677 * (they may display information for the user's benefit, though)      *
1678 *                                                                    *
1679 **********************************************************************/
1680
1681// Resizes GPT to specified number of entries. Creates a new table if
1682// necessary, copies data if it already exists. If fillGPTSectors is 1
1683// (the default), rounds numEntries to fill all the sectors necessary to
1684// hold the GPT.
1685// Returns 1 if all goes well, 0 if an error is encountered.
1686int GPTData::SetGPTSize(uint32_t numEntries, int fillGPTSectors) {
1687   GPTPart* newParts;
1688   uint32_t i, high, copyNum, entriesPerSector;
1689   int allOK = 1;
1690
1691   // First, adjust numEntries upward, if necessary, to get a number
1692   // that fills the allocated sectors
1693   entriesPerSector = blockSize / GPT_SIZE;
1694   if (fillGPTSectors && ((numEntries % entriesPerSector) != 0)) {
1695      cout << "Adjusting GPT size from " << numEntries << " to ";
1696      numEntries = ((numEntries / entriesPerSector) + 1) * entriesPerSector;
1697      cout << numEntries << " to fill the sector\n";
1698   } // if
1699
1700   // Do the work only if the # of partitions is changing. Along with being
1701   // efficient, this prevents mucking with the location of the secondary
1702   // partition table, which causes problems when loading data from a RAID
1703   // array that's been expanded because this function is called when loading
1704   // data.
1705   if (((numEntries != numParts) || (partitions == NULL)) && (numEntries > 0)) {
1706      newParts = new GPTPart [numEntries];
1707      if (newParts != NULL) {
1708         if (partitions != NULL) { // existing partitions; copy them over
1709            GetPartRange(&i, &high);
1710            if (numEntries < (high + 1)) { // Highest entry too high for new #
1711               cout << "The highest-numbered partition is " << high + 1
1712                    << ", which is greater than the requested\n"
1713                    << "partition table size of " << numEntries
1714                    << "; cannot resize. Perhaps sorting will help.\n";
1715               allOK = 0;
1716               delete[] newParts;
1717            } else { // go ahead with copy
1718               if (numEntries < numParts)
1719                  copyNum = numEntries;
1720               else
1721                  copyNum = numParts;
1722               for (i = 0; i < copyNum; i++) {
1723                  newParts[i] = partitions[i];
1724               } // for
1725               delete[] partitions;
1726               partitions = newParts;
1727            } // if
1728         } else { // No existing partition table; just create it
1729            partitions = newParts;
1730         } // if/else existing partitions
1731         numParts = numEntries;
1732         mainHeader.firstUsableLBA = ((numEntries * GPT_SIZE) / blockSize) + (((numEntries * GPT_SIZE) % blockSize) != 0) + 2 ;
1733         secondHeader.firstUsableLBA = mainHeader.firstUsableLBA;
1734         MoveSecondHeaderToEnd();
1735         if (diskSize > 0)
1736            CheckGPTSize();
1737      } else { // Bad memory allocation
1738         cerr << "Error allocating memory for partition table! Size is unchanged!\n";
1739         allOK = 0;
1740      } // if/else
1741   } // if/else
1742   mainHeader.numParts = numParts;
1743   secondHeader.numParts = numParts;
1744   return (allOK);
1745} // GPTData::SetGPTSize()
1746
1747// Blank the partition array
1748void GPTData::BlankPartitions(void) {
1749   uint32_t i;
1750
1751   for (i = 0; i < numParts; i++) {
1752      partitions[i].BlankPartition();
1753   } // for
1754} // GPTData::BlankPartitions()
1755
1756// Delete a partition by number. Returns 1 if successful,
1757// 0 if there was a problem. Returns 1 if partition was in
1758// range, 0 if it was out of range.
1759int GPTData::DeletePartition(uint32_t partNum) {
1760   uint64_t startSector, length;
1761   uint32_t low, high, numUsedParts, retval = 1;;
1762
1763   numUsedParts = GetPartRange(&low, &high);
1764   if ((numUsedParts > 0) && (partNum >= low) && (partNum <= high)) {
1765      // In case there's a protective MBR, look for & delete matching
1766      // MBR partition....
1767      startSector = partitions[partNum].GetFirstLBA();
1768      length = partitions[partNum].GetLengthLBA();
1769      protectiveMBR.DeleteByLocation(startSector, length);
1770
1771      // Now delete the GPT partition
1772      partitions[partNum].BlankPartition();
1773   } else {
1774      cerr << "Partition number " << partNum + 1 << " out of range!\n";
1775      retval = 0;
1776   } // if/else
1777   return retval;
1778} // GPTData::DeletePartition(uint32_t partNum)
1779
1780// Non-interactively create a partition.
1781// Returns 1 if the operation was successful, 0 if a problem was discovered.
1782uint32_t GPTData::CreatePartition(uint32_t partNum, uint64_t startSector, uint64_t endSector) {
1783   int retval = 1; // assume there'll be no problems
1784   uint64_t origSector = startSector;
1785
1786   if (IsFreePartNum(partNum)) {
1787      if (Align(&startSector)) {
1788         cout << "Information: Moved requested sector from " << origSector << " to "
1789              << startSector << " in\norder to align on " << sectorAlignment
1790              << "-sector boundaries.\n";
1791      } // if
1792      if (IsFree(startSector) && (startSector <= endSector)) {
1793         if (FindLastInFree(startSector) >= endSector) {
1794            partitions[partNum].SetFirstLBA(startSector);
1795            partitions[partNum].SetLastLBA(endSector);
1796            partitions[partNum].SetType(DEFAULT_GPT_TYPE);
1797            partitions[partNum].RandomizeUniqueGUID();
1798         } else retval = 0; // if free space until endSector
1799      } else retval = 0; // if startSector is free
1800   } else retval = 0; // if legal partition number
1801   return retval;
1802} // GPTData::CreatePartition(partNum, startSector, endSector)
1803
1804// Sort the GPT entries, eliminating gaps and making for a logical
1805// ordering.
1806void GPTData::SortGPT(void) {
1807   if (numParts > 0)
1808      sort(partitions, partitions + numParts);
1809} // GPTData::SortGPT()
1810
1811// Swap the contents of two partitions.
1812// Returns 1 if successful, 0 if either partition is out of range
1813// (that is, not a legal number; either or both can be empty).
1814// Note that if partNum1 = partNum2 and this number is in range,
1815// it will be considered successful.
1816int GPTData::SwapPartitions(uint32_t partNum1, uint32_t partNum2) {
1817   GPTPart temp;
1818   int allOK = 1;
1819
1820   if ((partNum1 < numParts) && (partNum2 < numParts)) {
1821      if (partNum1 != partNum2) {
1822         temp = partitions[partNum1];
1823         partitions[partNum1] = partitions[partNum2];
1824         partitions[partNum2] = temp;
1825      } // if
1826   } else allOK = 0; // partition numbers are valid
1827   return allOK;
1828} // GPTData::SwapPartitions()
1829
1830// Set up data structures for entirely new set of partitions on the
1831// specified device. Returns 1 if OK, 0 if there were problems.
1832// Note that this function does NOT clear the protectiveMBR data
1833// structure, since it may hold the original MBR partitions if the
1834// program was launched on an MBR disk, and those may need to be
1835// converted to GPT format.
1836int GPTData::ClearGPTData(void) {
1837   int goOn = 1, i;
1838
1839   // Set up the partition table....
1840   delete[] partitions;
1841   partitions = NULL;
1842   SetGPTSize(NUM_GPT_ENTRIES);
1843
1844   // Now initialize a bunch of stuff that's static....
1845   mainHeader.signature = GPT_SIGNATURE;
1846   mainHeader.revision = 0x00010000;
1847   mainHeader.headerSize = HEADER_SIZE;
1848   mainHeader.reserved = 0;
1849   mainHeader.currentLBA = UINT64_C(1);
1850   mainHeader.partitionEntriesLBA = (uint64_t) 2;
1851   mainHeader.sizeOfPartitionEntries = GPT_SIZE;
1852   for (i = 0; i < GPT_RESERVED; i++) {
1853      mainHeader.reserved2[i] = '\0';
1854   } // for
1855   if (blockSize > 0)
1856      sectorAlignment = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
1857   else
1858      sectorAlignment = DEFAULT_ALIGNMENT;
1859
1860   // Now some semi-static items (computed based on end of disk)
1861   mainHeader.backupLBA = diskSize - UINT64_C(1);
1862   mainHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1863
1864   // Set a unique GUID for the disk, based on random numbers
1865   mainHeader.diskGUID.Randomize();
1866
1867   // Copy main header to backup header
1868   RebuildSecondHeader();
1869
1870   // Blank out the partitions array....
1871   BlankPartitions();
1872
1873   // Flag all CRCs as being OK....
1874   mainCrcOk = 1;
1875   secondCrcOk = 1;
1876   mainPartsCrcOk = 1;
1877   secondPartsCrcOk = 1;
1878
1879   return (goOn);
1880} // GPTData::ClearGPTData()
1881
1882// Set the location of the second GPT header data to the end of the disk.
1883// If the disk size has actually changed, this also adjusts the protective
1884// entry in the MBR, since it's probably no longer correct.
1885// Used internally and called by the 'e' option on the recovery &
1886// transformation menu, to help users of RAID arrays who add disk space
1887// to their arrays or to adjust data structures in restore operations
1888// involving unequal-sized disks.
1889void GPTData::MoveSecondHeaderToEnd() {
1890   mainHeader.backupLBA = secondHeader.currentLBA = diskSize - UINT64_C(1);
1891   if (mainHeader.lastUsableLBA != diskSize - mainHeader.firstUsableLBA) {
1892      if (protectiveMBR.GetValidity() == hybrid) {
1893         protectiveMBR.OptimizeEESize();
1894         RecomputeCHS();
1895      } // if
1896      if (protectiveMBR.GetValidity() == gpt)
1897         MakeProtectiveMBR();
1898   } // if
1899   mainHeader.lastUsableLBA = secondHeader.lastUsableLBA = diskSize - mainHeader.firstUsableLBA;
1900   secondHeader.partitionEntriesLBA = secondHeader.lastUsableLBA + UINT64_C(1);
1901} // GPTData::FixSecondHeaderLocation()
1902
1903// Sets the partition's name to the specified UnicodeString without
1904// user interaction.
1905// Returns 1 on success, 0 on failure (invalid partition number).
1906int GPTData::SetName(uint32_t partNum, const UnicodeString & theName) {
1907   int retval = 1;
1908
1909   if (IsUsedPartNum(partNum))
1910      partitions[partNum].SetName(theName);
1911   else
1912      retval = 0;
1913
1914   return retval;
1915} // GPTData::SetName
1916
1917// Set the disk GUID to the specified value. Note that the header CRCs must
1918// be recomputed after calling this function.
1919void GPTData::SetDiskGUID(GUIDData newGUID) {
1920   mainHeader.diskGUID = newGUID;
1921   secondHeader.diskGUID = newGUID;
1922} // SetDiskGUID()
1923
1924// Set the unique GUID of the specified partition. Returns 1 on
1925// successful completion, 0 if there were problems (invalid
1926// partition number).
1927int GPTData::SetPartitionGUID(uint32_t pn, GUIDData theGUID) {
1928   int retval = 0;
1929
1930   if (pn < numParts) {
1931      if (partitions[pn].IsUsed()) {
1932         partitions[pn].SetUniqueGUID(theGUID);
1933         retval = 1;
1934      } // if
1935   } // if
1936   return retval;
1937} // GPTData::SetPartitionGUID()
1938
1939// Set new random GUIDs for the disk and all partitions. Intended to be used
1940// after disk cloning or similar operations that don't randomize the GUIDs.
1941void GPTData::RandomizeGUIDs(void) {
1942   uint32_t i;
1943
1944   mainHeader.diskGUID.Randomize();
1945   secondHeader.diskGUID = mainHeader.diskGUID;
1946   for (i = 0; i < numParts; i++)
1947      if (partitions[i].IsUsed())
1948         partitions[i].RandomizeUniqueGUID();
1949} // GPTData::RandomizeGUIDs()
1950
1951// Change partition type code non-interactively. Returns 1 if
1952// successful, 0 if not....
1953int GPTData::ChangePartType(uint32_t partNum, PartType theGUID) {
1954   int retval = 1;
1955
1956   if (!IsFreePartNum(partNum)) {
1957      partitions[partNum].SetType(theGUID);
1958   } else retval = 0;
1959   return retval;
1960} // GPTData::ChangePartType()
1961
1962// Recompute the CHS values of all the MBR partitions. Used to reset
1963// CHS values that some BIOSes require, despite the fact that the
1964// resulting CHS values violate the GPT standard.
1965void GPTData::RecomputeCHS(void) {
1966   int i;
1967
1968   for (i = 0; i < 4; i++)
1969      protectiveMBR.RecomputeCHS(i);
1970} // GPTData::RecomputeCHS()
1971
1972// Adjust sector number so that it falls on a sector boundary that's a
1973// multiple of sectorAlignment. This is done to improve the performance
1974// of Western Digital Advanced Format disks and disks with similar
1975// technology from other companies, which use 4096-byte sectors
1976// internally although they translate to 512-byte sectors for the
1977// benefit of the OS. If partitions aren't properly aligned on these
1978// disks, some filesystem data structures can span multiple physical
1979// sectors, degrading performance. This function should be called
1980// only on the FIRST sector of the partition, not the last!
1981// This function returns 1 if the alignment was altered, 0 if it
1982// was unchanged.
1983int GPTData::Align(uint64_t* sector) {
1984   int retval = 0, sectorOK = 0;
1985   uint64_t earlier, later, testSector;
1986
1987   if ((*sector % sectorAlignment) != 0) {
1988      earlier = (*sector / sectorAlignment) * sectorAlignment;
1989      later = earlier + (uint64_t) sectorAlignment;
1990
1991      // Check to see that every sector between the earlier one and the
1992      // requested one is clear, and that it's not too early....
1993      if (earlier >= mainHeader.firstUsableLBA) {
1994         sectorOK = 1;
1995         testSector = earlier;
1996         do {
1997            sectorOK = IsFree(testSector++);
1998         } while ((sectorOK == 1) && (testSector < *sector));
1999         if (sectorOK == 1) {
2000            *sector = earlier;
2001            retval = 1;
2002         } // if
2003      } // if firstUsableLBA check
2004
2005      // If couldn't move the sector earlier, try to move it later instead....
2006      if ((sectorOK != 1) && (later <= mainHeader.lastUsableLBA)) {
2007         sectorOK = 1;
2008         testSector = later;
2009         do {
2010            sectorOK = IsFree(testSector--);
2011         } while ((sectorOK == 1) && (testSector > *sector));
2012         if (sectorOK == 1) {
2013            *sector = later;
2014            retval = 1;
2015         } // if
2016      } // if
2017   } // if
2018   return retval;
2019} // GPTData::Align()
2020
2021/********************************************************
2022 *                                                      *
2023 * Functions that return data about GPT data structures *
2024 * (most of these are inline in gpt.h)                  *
2025 *                                                      *
2026 ********************************************************/
2027
2028// Find the low and high used partition numbers (numbered from 0).
2029// Return value is the number of partitions found. Note that the
2030// *low and *high values are both set to 0 when no partitions
2031// are found, as well as when a single partition in the first
2032// position exists. Thus, the return value is the only way to
2033// tell when no partitions exist.
2034int GPTData::GetPartRange(uint32_t *low, uint32_t *high) {
2035   uint32_t i;
2036   int numFound = 0;
2037
2038   *low = numParts + 1; // code for "not found"
2039   *high = 0;
2040   for (i = 0; i < numParts; i++) {
2041      if (partitions[i].IsUsed()) { // it exists
2042         *high = i; // since we're counting up, set the high value
2043         // Set the low value only if it's not yet found...
2044         if (*low == (numParts + 1)) *low = i;
2045            numFound++;
2046      } // if
2047   } // for
2048
2049   // Above will leave *low pointing to its "not found" value if no partitions
2050   // are defined, so reset to 0 if this is the case....
2051   if (*low == (numParts + 1))
2052      *low = 0;
2053   return numFound;
2054} // GPTData::GetPartRange()
2055
2056// Returns the value of the first free partition, or -1 if none is
2057// unused.
2058int GPTData::FindFirstFreePart(void) {
2059   int i = 0;
2060
2061   if (partitions != NULL) {
2062      while ((i < (int) numParts) && (partitions[i].IsUsed()))
2063         i++;
2064      if (i >= (int) numParts)
2065         i = -1;
2066   } else i = -1;
2067   return i;
2068} // GPTData::FindFirstFreePart()
2069
2070// Returns the number of defined partitions.
2071uint32_t GPTData::CountParts(void) {
2072   uint32_t i, counted = 0;
2073
2074   for (i = 0; i < numParts; i++) {
2075      if (partitions[i].IsUsed())
2076         counted++;
2077   } // for
2078   return counted;
2079} // GPTData::CountParts()
2080
2081/****************************************************
2082 *                                                  *
2083 * Functions that return data about disk free space *
2084 *                                                  *
2085 ****************************************************/
2086
2087// Find the first available block after the starting point; returns 0 if
2088// there are no available blocks left
2089uint64_t GPTData::FindFirstAvailable(uint64_t start) {
2090   uint64_t first;
2091   uint32_t i;
2092   int firstMoved = 0;
2093
2094   // Begin from the specified starting point or from the first usable
2095   // LBA, whichever is greater...
2096   if (start < mainHeader.firstUsableLBA)
2097      first = mainHeader.firstUsableLBA;
2098   else
2099      first = start;
2100
2101   // ...now search through all partitions; if first is within an
2102   // existing partition, move it to the next sector after that
2103   // partition and repeat. If first was moved, set firstMoved
2104   // flag; repeat until firstMoved is not set, so as to catch
2105   // cases where partitions are out of sequential order....
2106   do {
2107      firstMoved = 0;
2108      for (i = 0; i < numParts; i++) {
2109         if ((partitions[i].IsUsed()) && (first >= partitions[i].GetFirstLBA()) &&
2110             (first <= partitions[i].GetLastLBA())) { // in existing part.
2111            first = partitions[i].GetLastLBA() + 1;
2112            firstMoved = 1;
2113         } // if
2114      } // for
2115   } while (firstMoved == 1);
2116   if (first > mainHeader.lastUsableLBA)
2117      first = 0;
2118   return (first);
2119} // GPTData::FindFirstAvailable()
2120
2121// Finds the first available sector in the largest block of unallocated
2122// space on the disk. Returns 0 if there are no available blocks left
2123uint64_t GPTData::FindFirstInLargest(void) {
2124   uint64_t start, firstBlock, lastBlock, segmentSize, selectedSize = 0, selectedSegment = 0;
2125
2126   start = 0;
2127   do {
2128      firstBlock = FindFirstAvailable(start);
2129      if (firstBlock != UINT32_C(0)) { // something's free...
2130         lastBlock = FindLastInFree(firstBlock);
2131         segmentSize = lastBlock - firstBlock + UINT32_C(1);
2132         if (segmentSize > selectedSize) {
2133            selectedSize = segmentSize;
2134            selectedSegment = firstBlock;
2135         } // if
2136         start = lastBlock + 1;
2137      } // if
2138   } while (firstBlock != 0);
2139   return selectedSegment;
2140} // GPTData::FindFirstInLargest()
2141
2142// Find the last available block on the disk.
2143// Returns 0 if there are no available sectors
2144uint64_t GPTData::FindLastAvailable(void) {
2145   uint64_t last;
2146   uint32_t i;
2147   int lastMoved = 0;
2148
2149   // Start by assuming the last usable LBA is available....
2150   last = mainHeader.lastUsableLBA;
2151
2152   // ...now, similar to algorithm in FindFirstAvailable(), search
2153   // through all partitions, moving last when it's in an existing
2154   // partition. Set the lastMoved flag so we repeat to catch cases
2155   // where partitions are out of logical order.
2156   do {
2157      lastMoved = 0;
2158      for (i = 0; i < numParts; i++) {
2159         if ((last >= partitions[i].GetFirstLBA()) &&
2160             (last <= partitions[i].GetLastLBA())) { // in existing part.
2161            last = partitions[i].GetFirstLBA() - 1;
2162            lastMoved = 1;
2163         } // if
2164      } // for
2165   } while (lastMoved == 1);
2166   if (last < mainHeader.firstUsableLBA)
2167      last = 0;
2168   return (last);
2169} // GPTData::FindLastAvailable()
2170
2171// Find the last available block in the free space pointed to by start.
2172uint64_t GPTData::FindLastInFree(uint64_t start) {
2173   uint64_t nearestStart;
2174   uint32_t i;
2175
2176   nearestStart = mainHeader.lastUsableLBA;
2177   for (i = 0; i < numParts; i++) {
2178      if ((nearestStart > partitions[i].GetFirstLBA()) &&
2179          (partitions[i].GetFirstLBA() > start)) {
2180         nearestStart = partitions[i].GetFirstLBA() - 1;
2181      } // if
2182   } // for
2183   return (nearestStart);
2184} // GPTData::FindLastInFree()
2185
2186// Finds the total number of free blocks, the number of segments in which
2187// they reside, and the size of the largest of those segments
2188uint64_t GPTData::FindFreeBlocks(uint32_t *numSegments, uint64_t *largestSegment) {
2189   uint64_t start = UINT64_C(0); // starting point for each search
2190   uint64_t totalFound = UINT64_C(0); // running total
2191   uint64_t firstBlock; // first block in a segment
2192   uint64_t lastBlock; // last block in a segment
2193   uint64_t segmentSize; // size of segment in blocks
2194   uint32_t num = 0;
2195
2196   *largestSegment = UINT64_C(0);
2197   if (diskSize > 0) {
2198      do {
2199         firstBlock = FindFirstAvailable(start);
2200         if (firstBlock != UINT64_C(0)) { // something's free...
2201            lastBlock = FindLastInFree(firstBlock);
2202            segmentSize = lastBlock - firstBlock + UINT64_C(1);
2203            if (segmentSize > *largestSegment) {
2204               *largestSegment = segmentSize;
2205            } // if
2206            totalFound += segmentSize;
2207            num++;
2208            start = lastBlock + 1;
2209         } // if
2210      } while (firstBlock != 0);
2211   } // if
2212   *numSegments = num;
2213   return totalFound;
2214} // GPTData::FindFreeBlocks()
2215
2216// Returns 1 if sector is unallocated, 0 if it's allocated to a partition.
2217// If it's allocated, return the partition number to which it's allocated
2218// in partNum, if that variable is non-NULL. (A value of UINT32_MAX is
2219// returned in partNum if the sector is in use by basic GPT data structures.)
2220int GPTData::IsFree(uint64_t sector, uint32_t *partNum) {
2221   int isFree = 1;
2222   uint32_t i;
2223
2224   for (i = 0; i < numParts; i++) {
2225      if ((sector >= partitions[i].GetFirstLBA()) &&
2226           (sector <= partitions[i].GetLastLBA())) {
2227         isFree = 0;
2228         if (partNum != NULL)
2229            *partNum = i;
2230      } // if
2231   } // for
2232   if ((sector < mainHeader.firstUsableLBA) ||
2233        (sector > mainHeader.lastUsableLBA)) {
2234      isFree = 0;
2235      if (partNum != NULL)
2236         *partNum = UINT32_MAX;
2237   } // if
2238   return (isFree);
2239} // GPTData::IsFree()
2240
2241// Returns 1 if partNum is unused AND if it's a legal value.
2242int GPTData::IsFreePartNum(uint32_t partNum) {
2243   return ((partNum < numParts) && (partitions != NULL) &&
2244           (!partitions[partNum].IsUsed()));
2245} // GPTData::IsFreePartNum()
2246
2247// Returns 1 if partNum is in use.
2248int GPTData::IsUsedPartNum(uint32_t partNum) {
2249   return ((partNum < numParts) && (partitions != NULL) &&
2250           (partitions[partNum].IsUsed()));
2251} // GPTData::IsUsedPartNum()
2252
2253/***********************************************************
2254 *                                                         *
2255 * Change how functions work or return information on them *
2256 *                                                         *
2257 ***********************************************************/
2258
2259// Set partition alignment value; partitions will begin on multiples of
2260// the specified value
2261void GPTData::SetAlignment(uint32_t n) {
2262   if (n > 0)
2263      sectorAlignment = n;
2264   else
2265      cerr << "Attempt to set partition alignment to 0!\n";
2266} // GPTData::SetAlignment()
2267
2268// Compute sector alignment based on the current partitions (if any). Each
2269// partition's starting LBA is examined, and if it's divisible by a power-of-2
2270// value less than or equal to the DEFAULT_ALIGNMENT value (adjusted for the
2271// sector size), but not by the previously-located alignment value, then the
2272// alignment value is adjusted down. If the computed alignment is less than 8
2273// and the disk is bigger than SMALLEST_ADVANCED_FORMAT, resets it to 8. This
2274// is a safety measure for Advanced Format drives. If no partitions are
2275// defined, the alignment value is set to DEFAULT_ALIGNMENT (2048) (or an
2276// adjustment of that based on the current sector size). The result is that new
2277// drives are aligned to 2048-sector multiples but the program won't complain
2278// about other alignments on existing disks unless a smaller-than-8 alignment
2279// is used on big disks (as safety for Advanced Format drives).
2280// Returns the computed alignment value.
2281uint32_t GPTData::ComputeAlignment(void) {
2282   uint32_t i = 0, found, exponent = 31;
2283   uint32_t align = DEFAULT_ALIGNMENT;
2284
2285   if (blockSize > 0)
2286      align = DEFAULT_ALIGNMENT * SECTOR_SIZE / blockSize;
2287   exponent = (uint32_t) log2(align);
2288   for (i = 0; i < numParts; i++) {
2289      if (partitions[i].IsUsed()) {
2290         found = 0;
2291         while (!found) {
2292            align = UINT64_C(1) << exponent;
2293            if ((partitions[i].GetFirstLBA() % align) == 0) {
2294               found = 1;
2295            } else {
2296               exponent--;
2297            } // if/else
2298         } // while
2299      } // if
2300   } // for
2301   if ((align < MIN_AF_ALIGNMENT) && (diskSize >= SMALLEST_ADVANCED_FORMAT))
2302      align = MIN_AF_ALIGNMENT;
2303   sectorAlignment = align;
2304   return align;
2305} // GPTData::ComputeAlignment()
2306
2307/********************************
2308 *                              *
2309 * Endianness support functions *
2310 *                              *
2311 ********************************/
2312
2313void GPTData::ReverseHeaderBytes(struct GPTHeader* header) {
2314   ReverseBytes(&header->signature, 8);
2315   ReverseBytes(&header->revision, 4);
2316   ReverseBytes(&header->headerSize, 4);
2317   ReverseBytes(&header->headerCRC, 4);
2318   ReverseBytes(&header->reserved, 4);
2319   ReverseBytes(&header->currentLBA, 8);
2320   ReverseBytes(&header->backupLBA, 8);
2321   ReverseBytes(&header->firstUsableLBA, 8);
2322   ReverseBytes(&header->lastUsableLBA, 8);
2323   ReverseBytes(&header->partitionEntriesLBA, 8);
2324   ReverseBytes(&header->numParts, 4);
2325   ReverseBytes(&header->sizeOfPartitionEntries, 4);
2326   ReverseBytes(&header->partitionEntriesCRC, 4);
2327   ReverseBytes(header->reserved2, GPT_RESERVED);
2328} // GPTData::ReverseHeaderBytes()
2329
2330// Reverse byte order for all partitions.
2331void GPTData::ReversePartitionBytes() {
2332   uint32_t i;
2333
2334   for (i = 0; i < numParts; i++) {
2335      partitions[i].ReversePartBytes();
2336   } // for
2337} // GPTData::ReversePartitionBytes()
2338
2339// Validate partition number
2340bool GPTData::ValidPartNum (const uint32_t partNum) {
2341   if (partNum >= numParts) {
2342      cerr << "Partition number out of range: " << partNum << "\n";
2343      return false;
2344   } // if
2345   return true;
2346} // GPTData::ValidPartNum
2347
2348// Return a single partition for inspection (not modification!) by other
2349// functions.
2350const GPTPart & GPTData::operator[](uint32_t partNum) const {
2351   if (partNum >= numParts) {
2352      cerr << "Partition number out of range (" << partNum << " requested, but only "
2353           << numParts << " available)\n";
2354      exit(1);
2355   } // if
2356   if (partitions == NULL) {
2357      cerr << "No partitions defined in GPTData::operator[]; fatal error!\n";
2358      exit(1);
2359   } // if
2360   return partitions[partNum];
2361} // operator[]
2362
2363// Return (not for modification!) the disk's GUID value
2364const GUIDData & GPTData::GetDiskGUID(void) const {
2365   return mainHeader.diskGUID;
2366} // GPTData::GetDiskGUID()
2367
2368// Manage attributes for a partition, based on commands passed to this function.
2369// (Function is non-interactive.)
2370// Returns 1 if a modification command succeeded, 0 if the command should not have
2371// modified data, and -1 if a modification command failed.
2372int GPTData::ManageAttributes(int partNum, const string & command, const string & bits) {
2373   int retval = 0;
2374   Attributes theAttr;
2375
2376   if (partNum >= (int) numParts) {
2377      cerr << "Invalid partition number (" << partNum + 1 << ")\n";
2378      retval = -1;
2379   } else {
2380      if (command == "show") {
2381         ShowAttributes(partNum);
2382      } else if (command == "get") {
2383         GetAttribute(partNum, bits);
2384      } else {
2385         theAttr = partitions[partNum].GetAttributes();
2386         if (theAttr.OperateOnAttributes(partNum, command, bits)) {
2387            partitions[partNum].SetAttributes(theAttr.GetAttributes());
2388            retval = 1;
2389         } else {
2390            retval = -1;
2391         } // if/else
2392      } // if/elseif/else
2393   } // if/else invalid partition #
2394
2395   return retval;
2396} // GPTData::ManageAttributes()
2397
2398// Show all attributes for a specified partition....
2399void GPTData::ShowAttributes(const uint32_t partNum) {
2400   if ((partNum < numParts) && partitions[partNum].IsUsed())
2401      partitions[partNum].ShowAttributes(partNum);
2402} // GPTData::ShowAttributes
2403
2404// Show whether a single attribute bit is set (terse output)...
2405void GPTData::GetAttribute(const uint32_t partNum, const string& attributeBits) {
2406   if (partNum < numParts)
2407      partitions[partNum].GetAttributes().OperateOnAttributes(partNum, "get", attributeBits);
2408} // GPTData::GetAttribute
2409
2410
2411/******************************************
2412 *                                        *
2413 * Additional non-class support functions *
2414 *                                        *
2415 ******************************************/
2416
2417// Check to be sure that data type sizes are correct. The basic types (uint*_t) should
2418// never fail these tests, but the struct types may fail depending on compile options.
2419// Specifically, the -fpack-struct option to gcc may be required to ensure proper structure
2420// sizes.
2421int SizesOK(void) {
2422   int allOK = 1;
2423
2424   if (sizeof(uint8_t) != 1) {
2425      cerr << "uint8_t is " << sizeof(uint8_t) << " bytes, should be 1 byte; aborting!\n";
2426      allOK = 0;
2427   } // if
2428   if (sizeof(uint16_t) != 2) {
2429      cerr << "uint16_t is " << sizeof(uint16_t) << " bytes, should be 2 bytes; aborting!\n";
2430      allOK = 0;
2431   } // if
2432   if (sizeof(uint32_t) != 4) {
2433      cerr << "uint32_t is " << sizeof(uint32_t) << " bytes, should be 4 bytes; aborting!\n";
2434      allOK = 0;
2435   } // if
2436   if (sizeof(uint64_t) != 8) {
2437      cerr << "uint64_t is " << sizeof(uint64_t) << " bytes, should be 8 bytes; aborting!\n";
2438      allOK = 0;
2439   } // if
2440   if (sizeof(struct MBRRecord) != 16) {
2441      cerr << "MBRRecord is " << sizeof(MBRRecord) << " bytes, should be 16 bytes; aborting!\n";
2442      allOK = 0;
2443   } // if
2444   if (sizeof(struct TempMBR) != 512) {
2445      cerr << "TempMBR is " <<  sizeof(TempMBR) << " bytes, should be 512 bytes; aborting!\n";
2446      allOK = 0;
2447   } // if
2448   if (sizeof(struct GPTHeader) != 512) {
2449      cerr << "GPTHeader is " << sizeof(GPTHeader) << " bytes, should be 512 bytes; aborting!\n";
2450      allOK = 0;
2451   } // if
2452   if (sizeof(GPTPart) != 128) {
2453      cerr << "GPTPart is " << sizeof(GPTPart) << " bytes, should be 128 bytes; aborting!\n";
2454      allOK = 0;
2455   } // if
2456   if (sizeof(GUIDData) != 16) {
2457      cerr << "GUIDData is " << sizeof(GUIDData) << " bytes, should be 16 bytes; aborting!\n";
2458      allOK = 0;
2459   } // if
2460   if (sizeof(PartType) != 16) {
2461      cerr << "PartType is " << sizeof(PartType) << " bytes, should be 16 bytes; aborting!\n";
2462      allOK = 0;
2463   } // if
2464   return (allOK);
2465} // SizesOK()
2466
2467