resetting manifest requested domain to floor
[platform/upstream/gptfdisk.git] / basicmbr.cc
1 /* basicmbr.cc -- Functions for loading, saving, and manipulating legacy MBR partition
2    data. */
3
4 /* Initial coding by Rod Smith, January to February, 2009 */
5
6 /* This program is copyright (c) 2009-2011 by Roderick W. Smith. It is distributed
7   under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
9 #define __STDC_LIMIT_MACROS
10 #define __STDC_CONSTANT_MACROS
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdint.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <time.h>
18 #include <sys/stat.h>
19 #include <errno.h>
20 #include <iostream>
21 #include <algorithm>
22 #include "mbr.h"
23 #include "support.h"
24
25 using namespace std;
26
27 /****************************************
28  *                                      *
29  * MBRData class and related structures *
30  *                                      *
31  ****************************************/
32
33 BasicMBRData::BasicMBRData(void) {
34    blockSize = SECTOR_SIZE;
35    diskSize = 0;
36    device = "";
37    state = invalid;
38    numHeads = MAX_HEADS;
39    numSecspTrack = MAX_SECSPERTRACK;
40    myDisk = NULL;
41    canDeleteMyDisk = 0;
42 //   memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
43    EmptyMBR();
44 } // BasicMBRData default constructor
45
46 BasicMBRData::BasicMBRData(string filename) {
47    blockSize = SECTOR_SIZE;
48    diskSize = 0;
49    device = filename;
50    state = invalid;
51    numHeads = MAX_HEADS;
52    numSecspTrack = MAX_SECSPERTRACK;
53    myDisk = NULL;
54    canDeleteMyDisk = 0;
55 //   memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
56    
57    // Try to read the specified partition table, but if it fails....
58    if (!ReadMBRData(filename)) {
59       EmptyMBR();
60       device = "";
61    } // if
62 } // BasicMBRData(string filename) constructor
63
64 // Free space used by myDisk only if that's OK -- sometimes it will be
65 // copied from an outside source, in which case that source should handle
66 // it!
67 BasicMBRData::~BasicMBRData(void) {
68    if (canDeleteMyDisk)
69       delete myDisk;
70 } // BasicMBRData destructor
71
72 // Assignment operator -- copy entire set of MBR data.
73 BasicMBRData & BasicMBRData::operator=(const BasicMBRData & orig) {
74    int i;
75
76    memcpy(code, orig.code, 440);
77    diskSignature = orig.diskSignature;
78    nulls = orig.nulls;
79    MBRSignature = orig.MBRSignature;
80    blockSize = orig.blockSize;
81    diskSize = orig.diskSize;
82    numHeads = orig.numHeads;
83    numSecspTrack = orig.numSecspTrack;
84    canDeleteMyDisk = orig.canDeleteMyDisk;
85    device = orig.device;
86    state = orig.state;
87
88    myDisk = new DiskIO;
89    if (myDisk == NULL) {
90       cerr << "Unable to allocate memory in BasicMBRData::operator=()! Terminating!\n";
91       exit(1);
92    } // if
93    if (orig.myDisk != NULL)
94       myDisk->OpenForRead(orig.myDisk->GetName());
95
96    for (i = 0; i < MAX_MBR_PARTS; i++) {
97       partitions[i] = orig.partitions[i];
98    } // for
99    return *this;
100 } // BasicMBRData::operator=()
101
102 /**********************
103  *                    *
104  * Disk I/O functions *
105  *                    *
106  **********************/
107
108 // Read data from MBR. Returns 1 if read was successful (even if the
109 // data isn't a valid MBR), 0 if the read failed.
110 int BasicMBRData::ReadMBRData(const string & deviceFilename) {
111    int allOK = 1;
112
113    if (myDisk == NULL) {
114       myDisk = new DiskIO;
115       if (myDisk == NULL) {
116          cerr << "Unable to allocate memory in BasicMBRData::ReadMBRData()! Terminating!\n";
117          exit(1);
118       } // if
119       canDeleteMyDisk = 1;
120    } // if
121    if (myDisk->OpenForRead(deviceFilename)) {
122       allOK = ReadMBRData(myDisk);
123    } else {
124       allOK = 0;
125    } // if
126
127    if (allOK)
128       device = deviceFilename;
129
130    return allOK;
131 } // BasicMBRData::ReadMBRData(const string & deviceFilename)
132
133 // Read data from MBR. If checkBlockSize == 1 (the default), the block
134 // size is checked; otherwise it's set to the default (512 bytes).
135 // Note that any extended partition(s) present will be omitted from
136 // in the partitions[] array; these partitions must be re-created when
137 // the partition table is saved in MBR format.
138 int BasicMBRData::ReadMBRData(DiskIO * theDisk, int checkBlockSize) {
139    int allOK = 1, i, logicalNum = 3;
140    int err = 1;
141    TempMBR tempMBR;
142
143    if ((myDisk != NULL) && (myDisk != theDisk) && (canDeleteMyDisk)) {
144       delete myDisk;
145       canDeleteMyDisk = 0;
146    } // if
147
148    myDisk = theDisk;
149
150    // Empty existing MBR data, including the logical partitions...
151    EmptyMBR(0);
152
153    if (myDisk->Seek(0))
154      if (myDisk->Read(&tempMBR, 512))
155         err = 0;
156    if (err) {
157       cerr << "Problem reading disk in BasicMBRData::ReadMBRData()!\n";
158    } else {
159       for (i = 0; i < 440; i++)
160          code[i] = tempMBR.code[i];
161       diskSignature = tempMBR.diskSignature;
162       nulls = tempMBR.nulls;
163       for (i = 0; i < 4; i++) {
164          partitions[i] = tempMBR.partitions[i];
165          if (partitions[i].GetLengthLBA() > 0)
166             partitions[i].SetInclusion(PRIMARY);
167       } // for i... (reading all four partitions)
168       MBRSignature = tempMBR.MBRSignature;
169       ReadCHSGeom();
170
171       // Reverse the byte order, if necessary
172       if (IsLittleEndian() == 0) {
173          ReverseBytes(&diskSignature, 4);
174          ReverseBytes(&nulls, 2);
175          ReverseBytes(&MBRSignature, 2);
176          for (i = 0; i < 4; i++) {
177             partitions[i].ReverseByteOrder();
178          } // for
179       } // if
180
181       if (MBRSignature != MBR_SIGNATURE) {
182          allOK = 0;
183          state = invalid;
184       } // if
185
186       // Find disk size
187       diskSize = myDisk->DiskSize(&err);
188
189       // Find block size
190       if (checkBlockSize) {
191          blockSize = myDisk->GetBlockSize();
192       } // if (checkBlockSize)
193
194       // Load logical partition data, if any is found....
195       if (allOK) {
196          for (i = 0; i < 4; i++) {
197             if ((partitions[i].GetType() == 0x05) || (partitions[i].GetType() == 0x0f)
198                 || (partitions[i].GetType() == 0x85)) {
199                // Found it, so call a function to load everything from them....
200                logicalNum = ReadLogicalParts(partitions[i].GetStartLBA(), abs(logicalNum) + 1);
201                if (logicalNum < 0) {
202                   cerr << "Error reading logical partitions! List may be truncated!\n";
203                } // if maxLogicals valid
204                DeletePartition(i);
205             } // if primary partition is extended
206          } // for primary partition loop
207          if (allOK) { // Loaded logicals OK
208             state = mbr;
209          } else {
210             state = invalid;
211          } // if
212       } // if
213
214       // Check to see if it's in GPT format....
215       if (allOK) {
216          for (i = 0; i < 4; i++) {
217             if (partitions[i].GetType() == UINT8_C(0xEE)) {
218                state = gpt;
219             } // if
220          } // for
221       } // if
222
223       // If there's an EFI GPT partition, look for other partition types,
224       // to flag as hybrid
225       if (state == gpt) {
226          for (i = 0 ; i < 4; i++) {
227             if ((partitions[i].GetType() != UINT8_C(0xEE)) &&
228                 (partitions[i].GetType() != UINT8_C(0x00)))
229                state = hybrid;
230             if (logicalNum != 3)
231                cerr << "Warning! MBR Logical partitions found on a hybrid MBR disk! This is an\n"
232                     << "EXTREMELY dangerous configuration!\n\a";
233          } // for
234       } // if (hybrid detection code)
235    } // no initial error
236    return allOK;
237 } // BasicMBRData::ReadMBRData(DiskIO * theDisk, int checkBlockSize)
238
239 // This is a function to read all the logical partitions, following the
240 // logical partition linked list from the disk and storing the basic data in the
241 // partitions[] array. Returns last index to partitions[] used, or -1 times the
242 // that index if there was a problem. (Some problems can leave valid logical
243 // partition data.)
244 // Parameters:
245 // extendedStart = LBA of the start of the extended partition
246 // partNum = number of first partition in extended partition (normally 4).
247 int BasicMBRData::ReadLogicalParts(uint64_t extendedStart, int partNum) {
248    struct TempMBR ebr;
249    int i, another = 1, allOK = 1;
250    uint8_t ebrType;
251    uint64_t offset;
252    uint64_t EbrLocations[MAX_MBR_PARTS];
253
254    offset = extendedStart;
255    memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint64_t));
256    while (another && (partNum < MAX_MBR_PARTS) && (partNum >= 0) && (allOK > 0)) {
257       for (i = 0; i < MAX_MBR_PARTS; i++) {
258          if (EbrLocations[i] == offset) { // already read this one; infinite logical partition loop!
259             cerr << "Logical partition infinite loop detected! This is being corrected.\n";
260             allOK = -1;
261             partNum -= 1;
262          } // if
263       } // for
264       EbrLocations[partNum] = offset;
265       if (myDisk->Seek(offset) == 0) { // seek to EBR record
266          cerr << "Unable to seek to " << offset << "! Aborting!\n";
267          allOK = -1;
268       }
269       if (myDisk->Read(&ebr, 512) != 512) { // Load the data....
270          cerr << "Error seeking to or reading logical partition data from " << offset
271               << "!\nSome logical partitions may be missing!\n";
272          allOK = -1;
273       } else if (IsLittleEndian() != 1) { // Reverse byte ordering of some data....
274          ReverseBytes(&ebr.MBRSignature, 2);
275          ReverseBytes(&ebr.partitions[0].firstLBA, 4);
276          ReverseBytes(&ebr.partitions[0].lengthLBA, 4);
277          ReverseBytes(&ebr.partitions[1].firstLBA, 4);
278          ReverseBytes(&ebr.partitions[1].lengthLBA, 4);
279       } // if/else/if
280
281       if (ebr.MBRSignature != MBR_SIGNATURE) {
282          allOK = -1;
283          cerr << "EBR signature for logical partition invalid; read 0x";
284          cerr.fill('0');
285          cerr.width(4);
286          cerr.setf(ios::uppercase);
287          cerr << hex << ebr.MBRSignature << ", but should be 0x";
288          cerr.width(4);
289          cerr << MBR_SIGNATURE << dec << "\n";
290          cerr.fill(' ');
291       } // if
292
293       if ((partNum >= 0) && (partNum < MAX_MBR_PARTS) && (allOK > 0)) {
294          // Sometimes an EBR points directly to another EBR, rather than defining
295          // a logical partition and then pointing to another EBR. Thus, we skip
296          // the logical partition when this is the case....
297          ebrType = ebr.partitions[0].partitionType;
298          if ((ebrType == 0x05) || (ebrType == 0x0f) || (ebrType == 0x85)) {
299             cout << "EBR describes a logical partition!\n";
300             offset = extendedStart + ebr.partitions[0].firstLBA;
301          } else {
302             // Copy over the basic data....
303             partitions[partNum] = ebr.partitions[0];
304             // Adjust the start LBA, since it's encoded strangely....
305             partitions[partNum].SetStartLBA(ebr.partitions[0].firstLBA + offset);
306             partitions[partNum].SetInclusion(LOGICAL);
307             
308             // Find the next partition (if there is one)
309             if ((ebr.partitions[1].firstLBA != UINT32_C(0)) && (partNum < (MAX_MBR_PARTS - 1))) {
310                offset = extendedStart + ebr.partitions[1].firstLBA;
311                partNum++;
312             } else {
313                another = 0;
314             } // if another partition
315          } // if/else
316       } // if
317    } // while()
318    return (partNum * allOK);
319 } // BasicMBRData::ReadLogicalPart()
320
321 // Write the MBR data to the default defined device. This writes both the
322 // MBR itself and any defined logical partitions, provided there's an
323 // MBR extended partition.
324 int BasicMBRData::WriteMBRData(void) {
325    int allOK = 1;
326
327    if (myDisk != NULL) {
328       if (myDisk->OpenForWrite() != 0) {
329          allOK = WriteMBRData(myDisk);
330          cout << "Done writing data!\n";
331       } else {
332          allOK = 0;
333       } // if/else
334       myDisk->Close();
335    } else allOK = 0;
336    return allOK;
337 } // BasicMBRData::WriteMBRData(void)
338
339 // Save the MBR data to a file. This writes both the
340 // MBR itself and any defined logical partitions.
341 int BasicMBRData::WriteMBRData(DiskIO *theDisk) {
342    int i, j, partNum, next, allOK = 1, moreLogicals = 0;
343    uint64_t extFirstLBA = 0;
344    uint64_t writeEbrTo; // 64-bit because we support extended in 2-4TiB range
345    TempMBR tempMBR;
346
347    allOK = CreateExtended();
348    if (allOK) {
349       // First write the main MBR data structure....
350       memcpy(tempMBR.code, code, 440);
351       tempMBR.diskSignature = diskSignature;
352       tempMBR.nulls = nulls;
353       tempMBR.MBRSignature = MBRSignature;
354       for (i = 0; i < 4; i++) {
355          partitions[i].StoreInStruct(&tempMBR.partitions[i]);
356          if (partitions[i].GetType() == 0x0f) {
357             extFirstLBA = partitions[i].GetStartLBA();
358             moreLogicals = 1;
359          } // if
360       } // for i...
361    } // if
362    allOK = allOK && WriteMBRData(tempMBR, theDisk, 0);
363
364    // Set up tempMBR with some constant data for logical partitions...
365    tempMBR.diskSignature = 0;
366    for (i = 2; i < 4; i++) {
367       tempMBR.partitions[i].firstLBA = tempMBR.partitions[i].lengthLBA = 0;
368       tempMBR.partitions[i].partitionType = 0x00;
369       for (j = 0; j < 3; j++) {
370          tempMBR.partitions[i].firstSector[j] = 0;
371          tempMBR.partitions[i].lastSector[j] = 0;
372       } // for j
373    } // for i
374
375    partNum = FindNextInUse(4);
376    writeEbrTo = (uint64_t) extFirstLBA;
377    // Write logicals...
378    while (allOK && moreLogicals && (partNum < MAX_MBR_PARTS) && (partNum >= 0)) {
379       partitions[partNum].StoreInStruct(&tempMBR.partitions[0]);
380       tempMBR.partitions[0].firstLBA = 1;
381       // tempMBR.partitions[1] points to next EBR or terminates EBR linked list...
382       next = FindNextInUse(partNum + 1);
383       if ((next < MAX_MBR_PARTS) && (next > 0) && (partitions[next].GetStartLBA() > 0)) {
384          tempMBR.partitions[1].partitionType = 0x0f;
385          tempMBR.partitions[1].firstLBA = (uint32_t) (partitions[next].GetStartLBA() - extFirstLBA - 1);
386          tempMBR.partitions[1].lengthLBA = (uint32_t) (partitions[next].GetLengthLBA() + 1);
387          LBAtoCHS((uint64_t) tempMBR.partitions[1].firstLBA,
388                   (uint8_t *) &tempMBR.partitions[1].firstSector);
389          LBAtoCHS(tempMBR.partitions[1].lengthLBA - extFirstLBA,
390                   (uint8_t *) &tempMBR.partitions[1].lastSector);
391       } else {
392          tempMBR.partitions[1].partitionType = 0x00;
393          tempMBR.partitions[1].firstLBA = 0;
394          tempMBR.partitions[1].lengthLBA = 0;
395          moreLogicals = 0;
396       } // if/else
397       allOK = WriteMBRData(tempMBR, theDisk, writeEbrTo);
398       writeEbrTo = (uint64_t) tempMBR.partitions[1].firstLBA + (uint64_t) extFirstLBA;
399       partNum = next;
400    } // while
401    DeleteExtendedParts();
402    return allOK;
403 } // BasicMBRData::WriteMBRData(DiskIO *theDisk)
404
405 int BasicMBRData::WriteMBRData(const string & deviceFilename) {
406    device = deviceFilename;
407    return WriteMBRData();
408 } // BasicMBRData::WriteMBRData(const string & deviceFilename)
409
410 // Write a single MBR record to the specified sector. Used by the like-named
411 // function to write both the MBR and multiple EBR (for logical partition)
412 // records.
413 // Returns 1 on success, 0 on failure
414 int BasicMBRData::WriteMBRData(struct TempMBR & mbr, DiskIO *theDisk, uint64_t sector) {
415    int i, allOK;
416
417    // Reverse the byte order, if necessary
418    if (IsLittleEndian() == 0) {
419       ReverseBytes(&mbr.diskSignature, 4);
420       ReverseBytes(&mbr.nulls, 2);
421       ReverseBytes(&mbr.MBRSignature, 2);
422       for (i = 0; i < 4; i++) {
423          ReverseBytes(&mbr.partitions[i].firstLBA, 4);
424          ReverseBytes(&mbr.partitions[i].lengthLBA, 4);
425       } // for
426    } // if
427
428    // Now write the data structure...
429    allOK = theDisk->OpenForWrite();
430    if (allOK && theDisk->Seek(sector)) {
431       if (theDisk->Write(&mbr, 512) != 512) {
432          allOK = 0;
433          cerr << "Error " << errno << " when saving MBR!\n";
434       } // if
435    } else {
436       allOK = 0;
437       cerr << "Error " << errno << " when seeking to MBR to write it!\n";
438    } // if/else
439    theDisk->Close();
440
441    // Reverse the byte order back, if necessary
442    if (IsLittleEndian() == 0) {
443       ReverseBytes(&mbr.diskSignature, 4);
444       ReverseBytes(&mbr.nulls, 2);
445       ReverseBytes(&mbr.MBRSignature, 2);
446       for (i = 0; i < 4; i++) {
447          ReverseBytes(&mbr.partitions[i].firstLBA, 4);
448          ReverseBytes(&mbr.partitions[i].lengthLBA, 4);
449       } // for
450    }// if
451    return allOK;
452 } // BasicMBRData::WriteMBRData(uint64_t sector)
453
454 // Set a new disk device; used in copying one disk's partition
455 // table to another disk.
456 void BasicMBRData::SetDisk(DiskIO *theDisk) {
457    int err;
458
459    myDisk = theDisk;
460    diskSize = theDisk->DiskSize(&err);
461    canDeleteMyDisk = 0;
462    ReadCHSGeom();
463 } // BasicMBRData::SetDisk()
464
465 /********************************************
466  *                                          *
467  * Functions that display data for the user *
468  *                                          *
469  ********************************************/
470
471 // Show the MBR data to the user, up to the specified maximum number
472 // of partitions....
473 void BasicMBRData::DisplayMBRData(void) {
474    int i;
475
476    cout << "\nDisk size is " << diskSize << " sectors ("
477         << BytesToIeee(diskSize, blockSize) << ")\n";
478    cout << "MBR disk identifier: 0x";
479    cout.width(8);
480    cout.fill('0');
481    cout.setf(ios::uppercase);
482    cout << hex << diskSignature << dec << "\n";
483    cout << "MBR partitions:\n\n";
484    if ((state == gpt) || (state == hybrid)) {
485       cout << "Number  Boot  Start Sector   End Sector   Status      Code\n";
486    } else {
487       cout << "                                                   Can Be   Can Be\n";
488       cout << "Number  Boot  Start Sector   End Sector   Status   Logical  Primary   Code\n";
489       UpdateCanBeLogical();
490    } // 
491    for (i = 0; i < MAX_MBR_PARTS; i++) {
492       if (partitions[i].GetLengthLBA() != 0) {
493          cout.fill(' ');
494          cout.width(4);
495          cout << i + 1 << "      ";
496          partitions[i].ShowData((state == gpt) || (state == hybrid));
497       } // if
498       cout.fill(' ');
499    } // for
500 } // BasicMBRData::DisplayMBRData()
501
502 // Displays the state, as a word, on stdout. Used for debugging & to
503 // tell the user about the MBR state when the program launches....
504 void BasicMBRData::ShowState(void) {
505    switch (state) {
506       case invalid:
507          cout << "  MBR: not present\n";
508          break;
509       case gpt:
510          cout << "  MBR: protective\n";
511          break;
512       case hybrid:
513          cout << "  MBR: hybrid\n";
514          break;
515       case mbr:
516          cout << "  MBR: MBR only\n";
517          break;
518       default:
519          cout << "\a  MBR: unknown -- bug!\n";
520          break;
521    } // switch
522 } // BasicMBRData::ShowState()
523
524 /************************
525  *                      *
526  * GPT Checks and fixes *
527  *                      *
528  ************************/
529
530 // Perform a very rudimentary check for GPT data on the disk; searches for
531 // the GPT signature in the main and backup metadata areas.
532 // Returns 0 if GPT data not found, 1 if main data only is found, 2 if
533 // backup only is found, 3 if both main and backup data are found, and
534 // -1 if a disk error occurred.
535 int BasicMBRData::CheckForGPT(void) {
536    int retval = 0, err;
537    char signature1[9], signature2[9];
538
539    if (myDisk != NULL) {
540       if (myDisk->OpenForRead() != 0) {
541          if (myDisk->Seek(1)) {
542             myDisk->Read(signature1, 8);
543             signature1[8] = '\0';
544          } else retval = -1;
545          if (myDisk->Seek(myDisk->DiskSize(&err) - 1)) {
546             myDisk->Read(signature2, 8);
547             signature2[8] = '\0';
548          } else retval = -1;
549          if ((retval >= 0) && (strcmp(signature1, "EFI PART") == 0))
550             retval += 1;
551          if ((retval >= 0) && (strcmp(signature2, "EFI PART") == 0))
552             retval += 2;
553       } else {
554          retval = -1;
555       } // if/else
556       myDisk->Close();
557    } else retval = -1;
558    return retval;
559 } // BasicMBRData::CheckForGPT()
560
561 // Blanks the 2nd (sector #1, numbered from 0) and last sectors of the disk,
562 // but only if GPT data are verified on the disk, and only for the sector(s)
563 // with GPT signatures.
564 // Returns 1 if operation completes successfully, 0 if not (returns 1 if
565 // no GPT data are found on the disk).
566 int BasicMBRData::BlankGPTData(void) {
567    int allOK = 1, err;
568    uint8_t blank[512];
569
570    memset(blank, 0, 512);
571    switch (CheckForGPT()) {
572       case -1:
573          allOK = 0;
574          break;
575       case 0:
576          break;
577       case 1:
578          if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
579             if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
580                allOK = 0;
581             myDisk->Close();
582          } else allOK = 0;
583          break;
584       case 2:
585          if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
586             if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
587                (myDisk->Write(blank, 512) == 512)))
588                allOK = 0;
589             myDisk->Close();
590          } else allOK = 0;
591          break;
592       case 3:
593          if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
594             if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
595                allOK = 0;
596             if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
597                 (myDisk->Write(blank, 512) == 512)))
598                 allOK = 0;
599             myDisk->Close();
600          } else allOK = 0;
601          break;
602       default:
603          break;
604    } // switch()
605    return allOK;
606 } // BasicMBRData::BlankGPTData
607
608 /*********************************************************************
609  *                                                                   *
610  * Functions that set or get disk metadata (CHS geometry, disk size, *
611  * etc.)                                                             *
612  *                                                                   *
613  *********************************************************************/
614
615 // Read the CHS geometry using OS calls, or if that fails, set to
616 // the most common value for big disks (255 heads, 63 sectors per
617 // track, & however many cylinders that computes to).
618 void BasicMBRData::ReadCHSGeom(void) {
619    int err;
620
621    numHeads = myDisk->GetNumHeads();
622    numSecspTrack = myDisk->GetNumSecsPerTrack();
623    diskSize = myDisk->DiskSize(&err);
624    blockSize = myDisk->GetBlockSize();
625    partitions[0].SetGeometry(numHeads, numSecspTrack, diskSize, blockSize);
626 } // BasicMBRData::ReadCHSGeom()
627
628 // Find the low and high used partition numbers (numbered from 0).
629 // Return value is the number of partitions found. Note that the
630 // *low and *high values are both set to 0 when no partitions
631 // are found, as well as when a single partition in the first
632 // position exists. Thus, the return value is the only way to
633 // tell when no partitions exist.
634 int BasicMBRData::GetPartRange(uint32_t *low, uint32_t *high) {
635    uint32_t i;
636    int numFound = 0;
637
638    *low = MAX_MBR_PARTS + 1; // code for "not found"
639    *high = 0;
640    for (i = 0; i < MAX_MBR_PARTS; i++) {
641       if (partitions[i].GetStartLBA() != UINT32_C(0)) { // it exists
642          *high = i; // since we're counting up, set the high value
643          // Set the low value only if it's not yet found...
644          if (*low == (MAX_MBR_PARTS + 1))
645             *low = i;
646          numFound++;
647       } // if
648    } // for
649
650    // Above will leave *low pointing to its "not found" value if no partitions
651    // are defined, so reset to 0 if this is the case....
652    if (*low == (MAX_MBR_PARTS + 1))
653       *low = 0;
654    return numFound;
655 } // GPTData::GetPartRange()
656
657 // Converts 64-bit LBA value to MBR-style CHS value. Returns 1 if conversion
658 // was within the range that can be expressed by CHS (including 0, for an
659 // empty partition), 0 if the value is outside that range, and -1 if chs is
660 // invalid.
661 int BasicMBRData::LBAtoCHS(uint64_t lba, uint8_t * chs) {
662    uint64_t cylinder, head, sector; // all numbered from 0
663    uint64_t remainder;
664    int retval = 1;
665    int done = 0;
666
667    if (chs != NULL) {
668       // Special case: In case of 0 LBA value, zero out CHS values....
669       if (lba == 0) {
670          chs[0] = chs[1] = chs[2] = UINT8_C(0);
671          done = 1;
672       } // if
673       // If LBA value is too large for CHS, max out CHS values....
674       if ((!done) && (lba >= (numHeads * numSecspTrack * MAX_CYLINDERS))) {
675          chs[0] = 254;
676          chs[1] = chs[2] = 255;
677          done = 1;
678          retval = 0;
679       } // if
680       // If neither of the above applies, compute CHS values....
681       if (!done) {
682          cylinder = lba / (uint64_t) (numHeads * numSecspTrack);
683          remainder = lba - (cylinder * numHeads * numSecspTrack);
684          head = remainder / numSecspTrack;
685          remainder -= head * numSecspTrack;
686          sector = remainder;
687          if (head < numHeads)
688             chs[0] = (uint8_t) head;
689          else
690             retval = 0;
691          if (sector < numSecspTrack) {
692             chs[1] = (uint8_t) ((sector + 1) + (cylinder >> 8) * 64);
693             chs[2] = (uint8_t) (cylinder & UINT64_C(0xFF));
694          } else {
695             retval = 0;
696          } // if/else
697       } // if value is expressible and non-0
698    } else { // Invalid (NULL) chs pointer
699       retval = -1;
700    } // if CHS pointer valid
701    return (retval);
702 } // BasicMBRData::LBAtoCHS()
703
704 // Look for overlapping partitions.
705 // Returns the number of problems found
706 int BasicMBRData::FindOverlaps(void) {
707    int i, j, numProbs = 0, numEE = 0;
708
709    for (i = 0; i < MAX_MBR_PARTS; i++) {
710       for (j = i + 1; j < MAX_MBR_PARTS; j++) {
711          if ((partitions[i].GetInclusion() != NONE) && (partitions[j].GetInclusion() != NONE) &&
712              (partitions[i].DoTheyOverlap(partitions[j]))) {
713             numProbs++;
714             cout << "\nProblem: MBR partitions " << i + 1 << " and " << j + 1
715                  << " overlap!\n";
716          } // if
717       } // for (j...)
718       if (partitions[i].GetType() == 0xEE) {
719          numEE++;
720          if (partitions[i].GetStartLBA() != 1)
721             cout << "\nWarning: 0xEE partition doesn't start on sector 1. This can cause "
722                  << "problems\nin some OSes.\n";
723       } // if
724    } // for (i...)
725    if (numEE > 1)
726       cout << "\nCaution: More than one 0xEE MBR partition found. This can cause problems\n"
727            << "in some OSes.\n";
728
729    return numProbs;
730 } // BasicMBRData::FindOverlaps()
731
732 // Returns the number of primary partitions, including the extended partition
733 // required to hold any logical partitions found.
734 int BasicMBRData::NumPrimaries(void) {
735    int i, numPrimaries = 0, logicalsFound = 0;
736
737    for (i = 0; i < MAX_MBR_PARTS; i++) {
738       if (partitions[i].GetLengthLBA() > 0) {
739          if (partitions[i].GetInclusion() == PRIMARY)
740             numPrimaries++;
741          if (partitions[i].GetInclusion() == LOGICAL)
742             logicalsFound = 1;
743       } // if
744    } // for
745    return (numPrimaries + logicalsFound);
746 } // BasicMBRData::NumPrimaries()
747
748 // Returns the number of logical partitions.
749 int BasicMBRData::NumLogicals(void) {
750    int i, numLogicals = 0;
751
752    for (i = 0; i < MAX_MBR_PARTS; i++) {
753       if (partitions[i].GetInclusion() == LOGICAL)
754          numLogicals++;
755    } // for
756    return numLogicals;
757 } // BasicMBRData::NumLogicals()
758
759 // Returns the number of partitions (primaries plus logicals), NOT including
760 // the extended partition required to house the logicals.
761 int BasicMBRData::CountParts(void) {
762    int i, num = 0;
763
764    for (i = 0; i < MAX_MBR_PARTS; i++) {
765       if ((partitions[i].GetInclusion() == LOGICAL) ||
766           (partitions[i].GetInclusion() == PRIMARY))
767          num++;
768    } // for
769    return num;
770 } // BasicMBRData::CountParts()
771
772 // Updates the canBeLogical and canBePrimary flags for all the partitions.
773 void BasicMBRData::UpdateCanBeLogical(void) {
774    int i, j, sectorBefore, numPrimaries, numLogicals, usedAsEBR;
775    uint64_t firstLogical, lastLogical, lStart, pStart;
776
777    numPrimaries = NumPrimaries();
778    numLogicals = NumLogicals();
779    firstLogical = FirstLogicalLBA() - 1;
780    lastLogical = LastLogicalLBA();
781    for (i = 0; i < MAX_MBR_PARTS; i++) {
782       usedAsEBR = (SectorUsedAs(partitions[i].GetLastLBA()) == EBR);
783       if (usedAsEBR) {
784          partitions[i].SetCanBeLogical(0);
785          partitions[i].SetCanBePrimary(0);
786       } else if (partitions[i].GetLengthLBA() > 0) {
787          // First determine if it can be logical....
788          sectorBefore = SectorUsedAs(partitions[i].GetStartLBA() - 1);
789          lStart = partitions[i].GetStartLBA(); // start of potential logical part.
790          if ((lastLogical > 0) &&
791              ((sectorBefore == EBR) || (sectorBefore == NONE))) {
792             // Assume it can be logical, then search for primaries that make it
793             // not work and, if found, flag appropriately.
794             partitions[i].SetCanBeLogical(1);
795             for (j = 0; j < MAX_MBR_PARTS; j++) {
796                if ((i != j) && (partitions[j].GetInclusion() == PRIMARY)) {
797                   pStart = partitions[j].GetStartLBA();
798                   if (((pStart < lStart) && (firstLogical < pStart)) ||
799                       ((pStart > lStart) && (firstLogical > pStart))) {
800                      partitions[i].SetCanBeLogical(0);
801                   } // if/else
802                } // if
803             } // for
804          } else {
805             if ((sectorBefore != EBR) && (sectorBefore != NONE))
806                partitions[i].SetCanBeLogical(0);
807             else
808                partitions[i].SetCanBeLogical(lastLogical == 0); // can be logical only if no logicals already
809          } // if/else
810          // Now determine if it can be primary. Start by assuming it can be...
811          partitions[i].SetCanBePrimary(1);
812          if ((numPrimaries >= 4) && (partitions[i].GetInclusion() != PRIMARY)) {
813             partitions[i].SetCanBePrimary(0);
814             if ((partitions[i].GetInclusion() == LOGICAL) && (numLogicals == 1) &&
815                 (numPrimaries == 4))
816                partitions[i].SetCanBePrimary(1);
817          } // if
818          if ((partitions[i].GetStartLBA() > (firstLogical + 1)) &&
819              (partitions[i].GetLastLBA() < lastLogical))
820             partitions[i].SetCanBePrimary(0);
821       } // else if
822    } // for
823 } // BasicMBRData::UpdateCanBeLogical()
824
825 // Returns the first sector occupied by any logical partition. Note that
826 // this does NOT include the logical partition's EBR! Returns UINT32_MAX
827 // if there are no logical partitions defined.
828 uint64_t BasicMBRData::FirstLogicalLBA(void) {
829    int i;
830    uint64_t firstFound = UINT32_MAX;
831
832    for (i = 0; i < MAX_MBR_PARTS; i++) {
833       if ((partitions[i].GetInclusion() == LOGICAL) &&
834           (partitions[i].GetStartLBA() < firstFound)) {
835          firstFound = partitions[i].GetStartLBA();
836       } // if
837    } // for
838    return firstFound;
839 } // BasicMBRData::FirstLogicalLBA()
840
841 // Returns the last sector occupied by any logical partition, or 0 if
842 // there are no logical partitions defined.
843 uint64_t BasicMBRData::LastLogicalLBA(void) {
844    int i;
845    uint64_t lastFound = 0;
846
847    for (i = 0; i < MAX_MBR_PARTS; i++) {
848       if ((partitions[i].GetInclusion() == LOGICAL) &&
849           (partitions[i].GetLastLBA() > lastFound))
850          lastFound = partitions[i].GetLastLBA();
851    } // for
852    return lastFound;
853 } // BasicMBRData::LastLogicalLBA()
854
855 // Returns 1 if logical partitions are contiguous (have no primaries
856 // in their midst), or 0 if one or more primaries exist between
857 // logicals.
858 int BasicMBRData::AreLogicalsContiguous(void) {
859    int allOK = 1, i = 0;
860    uint64_t firstLogical, lastLogical;
861
862    firstLogical = FirstLogicalLBA() - 1; // subtract 1 for EBR
863    lastLogical = LastLogicalLBA();
864    if (lastLogical > 0) {
865       do {
866          if ((partitions[i].GetInclusion() == PRIMARY) &&
867              (partitions[i].GetStartLBA() >= firstLogical) &&
868              (partitions[i].GetStartLBA() <= lastLogical)) {
869             allOK = 0;
870          } // if
871          i++;
872       } while ((i < MAX_MBR_PARTS) && allOK);
873    } // if
874    return allOK;
875 } // BasicMBRData::AreLogicalsContiguous()
876
877 // Returns 1 if all partitions fit on the disk, given its size; 0 if any
878 // partition is too big.
879 int BasicMBRData::DoTheyFit(void) {
880    int i, allOK = 1;
881
882    for (i = 0; i < MAX_MBR_PARTS; i++) {
883       if ((partitions[i].GetStartLBA() > diskSize) || (partitions[i].GetLastLBA() > diskSize)) {
884          allOK = 0;
885       } // if
886    } // for
887    return allOK;
888 } // BasicMBRData::DoTheyFit(void)
889
890 // Returns 1 if there's at least one free sector immediately preceding
891 // all partitions flagged as logical; 0 if any logical partition lacks
892 // this space.
893 int BasicMBRData::SpaceBeforeAllLogicals(void) {
894    int i = 0, allOK = 1;
895
896    do {
897       if ((partitions[i].GetStartLBA() > 0) && (partitions[i].GetInclusion() == LOGICAL)) {
898          allOK = allOK && (SectorUsedAs(partitions[i].GetStartLBA() - 1) == EBR);
899       } // if
900       i++;
901    } while (allOK && (i < MAX_MBR_PARTS));
902    return allOK;
903 } // BasicMBRData::SpaceBeforeAllLogicals()
904
905 // Returns 1 if the partitions describe a legal layout -- all logicals
906 // are contiguous and have at least one preceding empty partitions,
907 // the number of primaries is under 4 (or under 3 if there are any
908 // logicals), there are no overlapping partitions, etc.
909 // Does NOT assume that primaries are numbered 1-4; uses the
910 // IsItPrimary() function of the MBRPart class to determine
911 // primary status. Also does NOT consider partition order; there
912 // can be gaps and it will still be considered legal.
913 int BasicMBRData::IsLegal(void) {
914    int allOK = 1;
915
916    allOK = (FindOverlaps() == 0);
917    allOK = (allOK && (NumPrimaries() <= 4));
918    allOK = (allOK && AreLogicalsContiguous());
919    allOK = (allOK && DoTheyFit());
920    allOK = (allOK && SpaceBeforeAllLogicals());
921    return allOK;
922 } // BasicMBRData::IsLegal()
923
924 // Finds the next in-use partition, starting with start (will return start
925 // if it's in use). Returns -1 if no subsequent partition is in use.
926 int BasicMBRData::FindNextInUse(int start) {
927    if (start >= MAX_MBR_PARTS)
928       start = -1;
929    while ((start < MAX_MBR_PARTS) && (start >= 0) && (partitions[start].GetInclusion() == NONE))
930       start++;
931    if ((start < 0) || (start >= MAX_MBR_PARTS))
932       start = -1;
933    return start;
934 } // BasicMBRData::FindFirstLogical();
935
936 /*****************************************************
937  *                                                   *
938  * Functions to create, delete, or change partitions *
939  *                                                   *
940  *****************************************************/
941
942 // Empty all data. Meant mainly for calling by constructors, but it's also
943 // used by the hybrid MBR functions in the GPTData class.
944 void BasicMBRData::EmptyMBR(int clearBootloader) {
945    int i;
946
947    // Zero out the boot loader section, the disk signature, and the
948    // 2-byte nulls area only if requested to do so. (This is the
949    // default.)
950    if (clearBootloader == 1) {
951       EmptyBootloader();
952    } // if
953
954    // Blank out the partitions
955    for (i = 0; i < MAX_MBR_PARTS; i++) {
956       partitions[i].Empty();
957    } // for
958    MBRSignature = MBR_SIGNATURE;
959    state = mbr;
960 } // BasicMBRData::EmptyMBR()
961
962 // Blank out the boot loader area. Done with the initial MBR-to-GPT
963 // conversion, since MBR boot loaders don't understand GPT, and so
964 // need to be replaced....
965 void BasicMBRData::EmptyBootloader(void) {
966    int i;
967
968    for (i = 0; i < 440; i++)
969       code[i] = 0;
970    nulls = 0;
971 } // BasicMBRData::EmptyBootloader
972
973 // Create a partition of the specified number based on the passed
974 // partition. This function does *NO* error checking, so it's possible
975 // to seriously screw up a partition table using this function!
976 // Note: This function should NOT be used to create the 0xEE partition
977 // in a conventional GPT configuration, since that partition has
978 // specific size requirements that this function won't handle. It may
979 // be used for creating the 0xEE partition(s) in a hybrid MBR, though,
980 // since those toss the rulebook away anyhow....
981 void BasicMBRData::AddPart(int num, const MBRPart& newPart) {
982    partitions[num] = newPart;
983 } // BasicMBRData::AddPart()
984
985 // Create a partition of the specified number, starting LBA, and
986 // length. This function does almost no error checking, so it's possible
987 // to seriously screw up a partition table using this function!
988 // Note: This function should NOT be used to create the 0xEE partition
989 // in a conventional GPT configuration, since that partition has
990 // specific size requirements that this function won't handle. It may
991 // be used for creating the 0xEE partition(s) in a hybrid MBR, though,
992 // since those toss the rulebook away anyhow....
993 void BasicMBRData::MakePart(int num, uint64_t start, uint64_t length, int type, int bootable) {
994    if ((num >= 0) && (num < MAX_MBR_PARTS) && (start <= UINT32_MAX) && (length <= UINT32_MAX)) {
995       partitions[num].Empty();
996       partitions[num].SetType(type);
997       partitions[num].SetLocation(start, length);
998       if (num < 4)
999          partitions[num].SetInclusion(PRIMARY);
1000       else
1001          partitions[num].SetInclusion(LOGICAL);
1002       SetPartBootable(num, bootable);
1003    } // if valid partition number & size
1004 } // BasicMBRData::MakePart()
1005
1006 // Set the partition's type code.
1007 // Returns 1 if successful, 0 if not (invalid partition number)
1008 int BasicMBRData::SetPartType(int num, int type) {
1009    int allOK = 1;
1010
1011    if ((num >= 0) && (num < MAX_MBR_PARTS)) {
1012       if (partitions[num].GetLengthLBA() != UINT32_C(0)) {
1013          allOK = partitions[num].SetType(type);
1014       } else allOK = 0;
1015    } else allOK = 0;
1016    return allOK;
1017 } // BasicMBRData::SetPartType()
1018
1019 // Set (or remove) the partition's bootable flag. Setting it is the
1020 // default; pass 0 as bootable to remove the flag.
1021 // Returns 1 if successful, 0 if not (invalid partition number)
1022 int BasicMBRData::SetPartBootable(int num, int bootable) {
1023    int allOK = 1;
1024
1025    if ((num >= 0) && (num < MAX_MBR_PARTS)) {
1026       if (partitions[num].GetLengthLBA() != UINT32_C(0)) {
1027          if (bootable == 0)
1028             partitions[num].SetStatus(UINT8_C(0x00));
1029          else
1030             partitions[num].SetStatus(UINT8_C(0x80));
1031       } else allOK = 0;
1032    } else allOK = 0;
1033    return allOK;
1034 } // BasicMBRData::SetPartBootable()
1035
1036 // Create a partition that fills the most available space. Returns
1037 // 1 if partition was created, 0 otherwise. Intended for use in
1038 // creating hybrid MBRs.
1039 int BasicMBRData::MakeBiggestPart(int i, int type) {
1040    uint64_t start = UINT64_C(1); // starting point for each search
1041    uint64_t firstBlock; // first block in a segment
1042    uint64_t lastBlock; // last block in a segment
1043    uint64_t segmentSize; // size of segment in blocks
1044    uint64_t selectedSegment = UINT64_C(0); // location of largest segment
1045    uint64_t selectedSize = UINT64_C(0); // size of largest segment in blocks
1046    int found = 0;
1047
1048    do {
1049       firstBlock = FindFirstAvailable(start);
1050       if (firstBlock > UINT64_C(0)) { // something's free...
1051          lastBlock = FindLastInFree(firstBlock);
1052          segmentSize = lastBlock - firstBlock + UINT64_C(1);
1053          if (segmentSize > selectedSize) {
1054             selectedSize = segmentSize;
1055             selectedSegment = firstBlock;
1056          } // if
1057          start = lastBlock + 1;
1058       } // if
1059    } while (firstBlock != 0);
1060    if ((selectedSize > UINT64_C(0)) && (selectedSize < diskSize)) {
1061       found = 1;
1062       MakePart(i, selectedSegment, selectedSize, type, 0);
1063    } else {
1064       found = 0;
1065    } // if/else
1066    return found;
1067 } // BasicMBRData::MakeBiggestPart(int i)
1068
1069 // Delete partition #i
1070 void BasicMBRData::DeletePartition(int i) {
1071    partitions[i].Empty();
1072 } // BasicMBRData::DeletePartition()
1073
1074 // Set the inclusion status (PRIMARY, LOGICAL, or NONE) with some sanity
1075 // checks to ensure the table remains legal.
1076 // Returns 1 on success, 0 on failure.
1077 int BasicMBRData::SetInclusionwChecks(int num, int inclStatus) {
1078    int allOK = 1, origValue;
1079
1080    if (IsLegal()) {
1081       if ((inclStatus == PRIMARY) || (inclStatus == LOGICAL) || (inclStatus == NONE)) {
1082          origValue = partitions[num].GetInclusion();
1083          partitions[num].SetInclusion(inclStatus);
1084          if (!IsLegal()) {
1085             partitions[num].SetInclusion(origValue);
1086             cerr << "Specified change is not legal! Aborting change!\n";
1087          } // if
1088       } else {
1089          cerr << "Invalid partition inclusion code in BasicMBRData::SetInclusionwChecks()!\n";
1090       } // if/else
1091    } else {
1092       cerr << "Partition table is not currently in a valid state. Aborting change!\n";
1093       allOK = 0;
1094    } // if/else
1095    return allOK;
1096 } // BasicMBRData::SetInclusionwChecks()
1097
1098 // Recomputes the CHS values for the specified partition and adjusts the value.
1099 // Note that this will create a technically incorrect CHS value for EFI GPT (0xEE)
1100 // protective partitions, but this is required by some buggy BIOSes, so I'm
1101 // providing a function to do this deliberately at the user's command.
1102 // This function does nothing if the partition's length is 0.
1103 void BasicMBRData::RecomputeCHS(int partNum) {
1104    partitions[partNum].RecomputeCHS();
1105 } // BasicMBRData::RecomputeCHS()
1106
1107 // Sorts the partitions starting with partition #start. This function
1108 // does NOT pay attention to primary/logical assignment, which is
1109 // critical when writing the partitions.
1110 void BasicMBRData::SortMBR(int start) {
1111    if ((start < MAX_MBR_PARTS) && (start >= 0))
1112       sort(partitions + start, partitions + MAX_MBR_PARTS);
1113 } // BasicMBRData::SortMBR()
1114
1115 // Delete any partitions that are too big to fit on the disk
1116 // or that are too big for MBR (32-bit limits).
1117 // This deletes the partitions by setting values to 0, not just
1118 // by setting them as being omitted.
1119 // Returns the number of partitions deleted in this way.
1120 int BasicMBRData::DeleteOversizedParts() {
1121    int num = 0, i;
1122
1123    for (i = 0; i < MAX_MBR_PARTS; i++) {
1124       if ((partitions[i].GetStartLBA() > diskSize) || (partitions[i].GetLastLBA() > diskSize) ||
1125           (partitions[i].GetStartLBA() > UINT32_MAX) || (partitions[i].GetLengthLBA() > UINT32_MAX)) {
1126          cerr << "\aWarning: Deleting oversized partition #" << i + 1 << "! Start = "
1127               << partitions[i].GetStartLBA() << ", length = " << partitions[i].GetLengthLBA() << "\n";
1128          partitions[i].Empty();
1129          num++;
1130       } // if
1131    } // for
1132    return num;
1133 } // BasicMBRData::DeleteOversizedParts()
1134
1135 // Search for and delete extended partitions.
1136 // Returns the number of partitions deleted.
1137 int BasicMBRData::DeleteExtendedParts() {
1138    int i, numDeleted = 0;
1139    uint8_t type;
1140
1141    for (i = 0; i < MAX_MBR_PARTS; i++) {
1142       type = partitions[i].GetType();
1143       if (((type == 0x05) || (type == 0x0f) || (type == (0x85))) &&
1144           (partitions[i].GetLengthLBA() > 0)) {
1145          partitions[i].Empty();
1146          numDeleted++;
1147       } // if
1148    } // for
1149    return numDeleted;
1150 } // BasicMBRData::DeleteExtendedParts()
1151
1152 // Finds any overlapping partitions and omits the smaller of the two.
1153 void BasicMBRData::OmitOverlaps() {
1154    int i, j;
1155
1156    for (i = 0; i < MAX_MBR_PARTS; i++) {
1157       for (j = i + 1; j < MAX_MBR_PARTS; j++) {
1158          if ((partitions[i].GetInclusion() != NONE) &&
1159              partitions[i].DoTheyOverlap(partitions[j])) {
1160             if (partitions[i].GetLengthLBA() < partitions[j].GetLengthLBA())
1161                partitions[i].SetInclusion(NONE);
1162             else
1163                partitions[j].SetInclusion(NONE);
1164          } // if
1165       } // for (j...)
1166    } // for (i...)
1167 } // BasicMBRData::OmitOverlaps()
1168
1169 // Convert as many partitions into logicals as possible, except for
1170 // the first partition, if possible.
1171 void BasicMBRData::MaximizeLogicals() {
1172    int earliestPart = 0, earliestPartWas = NONE, i;
1173
1174    for (i = MAX_MBR_PARTS - 1; i >= 0; i--) {
1175       UpdateCanBeLogical();
1176       earliestPart = i;
1177       if (partitions[i].CanBeLogical()) {
1178          partitions[i].SetInclusion(LOGICAL);
1179       } else if (partitions[i].CanBePrimary()) {
1180          partitions[i].SetInclusion(PRIMARY);
1181       } else {
1182          partitions[i].SetInclusion(NONE);
1183       } // if/elseif/else
1184    } // for
1185    // If we have spare primaries, convert back the earliest partition to
1186    // its original state....
1187    if ((NumPrimaries() < 4) && (partitions[earliestPart].GetInclusion() == LOGICAL))
1188       partitions[earliestPart].SetInclusion(earliestPartWas);
1189 } // BasicMBRData::MaximizeLogicals()
1190
1191 // Add primaries up to the maximum allowed, from the omitted category.
1192 void BasicMBRData::MaximizePrimaries() {
1193    int num, i = 0;
1194
1195    num = NumPrimaries();
1196    while ((num < 4) && (i < MAX_MBR_PARTS)) {
1197       if ((partitions[i].GetInclusion() == NONE) && (partitions[i].CanBePrimary())) {
1198          partitions[i].SetInclusion(PRIMARY);
1199          num++;
1200          UpdateCanBeLogical();
1201       } // if
1202       i++;
1203    } // while
1204 } // BasicMBRData::MaximizePrimaries()
1205
1206 // Remove primary partitions in excess of 4, starting with the later ones,
1207 // in terms of the array location....
1208 void BasicMBRData::TrimPrimaries(void) {
1209    int numToDelete, i = MAX_MBR_PARTS;
1210
1211    numToDelete = NumPrimaries() - 4;
1212    while ((numToDelete > 0) && (i >= 0)) {
1213       if (partitions[i].GetInclusion() == PRIMARY) {
1214          partitions[i].SetInclusion(NONE);
1215          numToDelete--;
1216       } // if
1217       i--;
1218    } // while (numToDelete > 0)
1219 } // BasicMBRData::TrimPrimaries()
1220
1221 // Locates primary partitions located between logical partitions and
1222 // either converts the primaries into logicals (if possible) or omits
1223 // them.
1224 void BasicMBRData::MakeLogicalsContiguous(void) {
1225    uint64_t firstLogicalLBA, lastLogicalLBA;
1226    int i;
1227
1228    firstLogicalLBA = FirstLogicalLBA();
1229    lastLogicalLBA = LastLogicalLBA();
1230    for (i = 0; i < MAX_MBR_PARTS; i++) {
1231       if ((partitions[i].GetInclusion() == PRIMARY) &&
1232           (partitions[i].GetStartLBA() >= firstLogicalLBA) &&
1233           (partitions[i].GetLastLBA() <= lastLogicalLBA)) {
1234          if (SectorUsedAs(partitions[i].GetStartLBA() - 1) == NONE)
1235             partitions[i].SetInclusion(LOGICAL);
1236          else
1237             partitions[i].SetInclusion(NONE);
1238       } // if
1239    } // for
1240 } // BasicMBRData::MakeLogicalsContiguous()
1241
1242 // If MBR data aren't legal, adjust primary/logical assignments and,
1243 // if necessary, drop partitions, to make the data legal.
1244 void BasicMBRData::MakeItLegal(void) {
1245    if (!IsLegal()) {
1246       DeleteOversizedParts();
1247       MaximizeLogicals();
1248       MaximizePrimaries();
1249       if (!AreLogicalsContiguous())
1250          MakeLogicalsContiguous();
1251       if (NumPrimaries() > 4)
1252          TrimPrimaries();
1253       OmitOverlaps();
1254    } // if
1255 } // BasicMBRData::MakeItLegal()
1256
1257 // Removes logical partitions and deactivated partitions from first four
1258 // entries (primary space).
1259 // Returns the number of partitions moved.
1260 int BasicMBRData::RemoveLogicalsFromFirstFour(void) {
1261    int i, j = 4, numMoved = 0, swapped = 0;
1262    MBRPart temp;
1263
1264    for (i = 0; i < 4; i++) {
1265       if ((partitions[i].GetInclusion() != PRIMARY) && (partitions[i].GetLengthLBA() > 0)) {
1266          j = 4;
1267          swapped = 0;
1268          do {
1269             if ((partitions[j].GetInclusion() == NONE) && (partitions[j].GetLengthLBA() == 0)) {
1270                temp = partitions[j];
1271                partitions[j] = partitions[i];
1272                partitions[i] = temp;
1273                swapped = 1;
1274                numMoved++;
1275             } // if
1276             j++;
1277          } while ((j < MAX_MBR_PARTS) && !swapped);
1278          if (j >= MAX_MBR_PARTS)
1279             cerr << "Warning! Too many partitions in BasicMBRData::RemoveLogicalsFromFirstFour()!\n";
1280       } // if
1281    } // for i...
1282    return numMoved;
1283 } // BasicMBRData::RemoveLogicalsFromFirstFour()
1284
1285 // Move all primaries into the first four partition spaces
1286 // Returns the number of partitions moved.
1287 int BasicMBRData::MovePrimariesToFirstFour(void) {
1288    int i, j = 0, numMoved = 0, swapped = 0;
1289    MBRPart temp;
1290
1291    for (i = 4; i < MAX_MBR_PARTS; i++) {
1292       if (partitions[i].GetInclusion() == PRIMARY) {
1293          j = 0;
1294          swapped = 0;
1295          do {
1296             if (partitions[j].GetInclusion() != PRIMARY) {
1297                temp = partitions[j];
1298                partitions[j] = partitions[i];
1299                partitions[i] = temp;
1300                swapped = 1;
1301                numMoved++;
1302             } // if
1303             j++;
1304          } while ((j < 4) && !swapped);
1305       } // if
1306    } // for
1307    return numMoved;
1308 } // BasicMBRData::MovePrimariesToFirstFour()
1309
1310 // Create an extended partition, if necessary, to hold the logical partitions.
1311 // This function also sorts the primaries into the first four positions of
1312 // the table.
1313 // Returns 1 on success, 0 on failure.
1314 int BasicMBRData::CreateExtended(void) {
1315    int allOK = 1, i = 0, swapped = 0;
1316    MBRPart temp;
1317
1318    if (IsLegal()) {
1319       // Move logicals out of primary space...
1320       RemoveLogicalsFromFirstFour();
1321       // Move primaries out of logical space...
1322       MovePrimariesToFirstFour();
1323
1324       // Create the extended partition
1325       if (NumLogicals() > 0) {
1326          SortMBR(4); // sort starting from 4 -- that is, logicals only
1327          temp.Empty();
1328          temp.SetStartLBA(FirstLogicalLBA() - 1);
1329          temp.SetLengthLBA(LastLogicalLBA() - FirstLogicalLBA() + 2);
1330          temp.SetType(0x0f, 1);
1331          temp.SetInclusion(PRIMARY);
1332          do {
1333             if ((partitions[i].GetInclusion() == NONE) || (partitions[i].GetLengthLBA() == 0)) {
1334                partitions[i] = temp;
1335                swapped = 1;
1336             } // if
1337             i++;
1338          } while ((i < 4) && !swapped);
1339          if (!swapped) {
1340             cerr << "Could not create extended partition; no room in primary table!\n";
1341             allOK = 0;
1342          } // if
1343       } // if (NumLogicals() > 0)
1344    } else allOK = 0;
1345    // Do a final check for EFI GPT (0xEE) partitions & flag as a problem if found
1346    // along with an extended partition
1347    for (i = 0; i < MAX_MBR_PARTS; i++)
1348       if (swapped && partitions[i].GetType() == 0xEE)
1349          allOK = 0;
1350    return allOK;
1351 } // BasicMBRData::CreateExtended()
1352
1353 /****************************************
1354  *                                      *
1355  * Functions to find data on free space *
1356  *                                      *
1357  ****************************************/
1358
1359 // Finds the first free space on the disk from start onward; returns 0
1360 // if none available....
1361 uint64_t BasicMBRData::FindFirstAvailable(uint64_t start) {
1362    uint64_t first;
1363    uint64_t i;
1364    int firstMoved;
1365
1366    first = start;
1367
1368    // ...now search through all partitions; if first is within an
1369    // existing partition, move it to the next sector after that
1370    // partition and repeat. If first was moved, set firstMoved
1371    // flag; repeat until firstMoved is not set, so as to catch
1372    // cases where partitions are out of sequential order....
1373    do {
1374       firstMoved = 0;
1375       for (i = 0; i < 4; i++) {
1376          // Check if it's in the existing partition
1377          if ((first >= partitions[i].GetStartLBA()) &&
1378              (first < (partitions[i].GetStartLBA() + partitions[i].GetLengthLBA()))) {
1379             first = partitions[i].GetStartLBA() + partitions[i].GetLengthLBA();
1380             firstMoved = 1;
1381          } // if
1382       } // for
1383    } while (firstMoved == 1);
1384    if ((first >= diskSize) || (first > UINT32_MAX))
1385       first = 0;
1386    return (first);
1387 } // BasicMBRData::FindFirstAvailable()
1388
1389 // Finds the last free sector on the disk from start forward.
1390 uint64_t BasicMBRData::FindLastInFree(uint64_t start) {
1391    uint64_t nearestStart;
1392    uint64_t i;
1393
1394    if ((diskSize <= UINT32_MAX) && (diskSize > 0))
1395       nearestStart = diskSize - 1;
1396    else
1397       nearestStart = UINT32_MAX - 1;
1398
1399    for (i = 0; i < 4; i++) {
1400       if ((nearestStart > partitions[i].GetStartLBA()) &&
1401           (partitions[i].GetStartLBA() > start)) {
1402          nearestStart = partitions[i].GetStartLBA() - 1;
1403       } // if
1404    } // for
1405    return (nearestStart);
1406 } // BasicMBRData::FindLastInFree()
1407
1408 // Finds the first free sector on the disk from start backward.
1409 uint64_t BasicMBRData::FindFirstInFree(uint64_t start) {
1410    uint64_t bestLastLBA, thisLastLBA;
1411    int i;
1412
1413    bestLastLBA = 1;
1414    for (i = 0; i < 4; i++) {
1415       thisLastLBA = partitions[i].GetLastLBA() + 1;
1416       if (thisLastLBA > 0)
1417          thisLastLBA--;
1418       if ((thisLastLBA > bestLastLBA) && (thisLastLBA < start))
1419          bestLastLBA = thisLastLBA + 1;
1420    } // for
1421    return (bestLastLBA);
1422 } // BasicMBRData::FindFirstInFree()
1423
1424 // Returns NONE (unused), PRIMARY, LOGICAL, EBR (for EBR or MBR), or INVALID.
1425 // Note: If the sector immediately before a logical partition is in use by
1426 // another partition, this function returns PRIMARY or LOGICAL for that
1427 // sector, rather than EBR.
1428 int BasicMBRData::SectorUsedAs(uint64_t sector, int topPartNum) {
1429    int i = 0, usedAs = NONE;
1430
1431    do {
1432       if ((partitions[i].GetStartLBA() <= sector) && (partitions[i].GetLastLBA() >= sector))
1433          usedAs = partitions[i].GetInclusion();
1434       if ((partitions[i].GetStartLBA() == (sector + 1)) && (partitions[i].GetInclusion() == LOGICAL))
1435          usedAs = EBR;
1436       if (sector == 0)
1437          usedAs = EBR;
1438       if (sector >= diskSize)
1439          usedAs = INVALID;
1440       i++;
1441    } while ((i < topPartNum) && ((usedAs == NONE) || (usedAs == EBR)));
1442    return usedAs;
1443 } // BasicMBRData::SectorUsedAs()
1444
1445 /******************************************************
1446  *                                                    *
1447  * Functions that extract data on specific partitions *
1448  *                                                    *
1449  ******************************************************/
1450
1451 uint8_t BasicMBRData::GetStatus(int i) {
1452    MBRPart* thePart;
1453    uint8_t retval;
1454
1455    thePart = GetPartition(i);
1456    if (thePart != NULL)
1457       retval = thePart->GetStatus();
1458    else
1459       retval = UINT8_C(0);
1460    return retval;
1461 } // BasicMBRData::GetStatus()
1462
1463 uint8_t BasicMBRData::GetType(int i) {
1464    MBRPart* thePart;
1465    uint8_t retval;
1466
1467    thePart = GetPartition(i);
1468    if (thePart != NULL)
1469       retval = thePart->GetType();
1470    else
1471       retval = UINT8_C(0);
1472    return retval;
1473 } // BasicMBRData::GetType()
1474
1475 uint64_t BasicMBRData::GetFirstSector(int i) {
1476    MBRPart* thePart;
1477    uint64_t retval;
1478
1479    thePart = GetPartition(i);
1480    if (thePart != NULL) {
1481       retval = thePart->GetStartLBA();
1482    } else
1483       retval = UINT32_C(0);
1484       return retval;
1485 } // BasicMBRData::GetFirstSector()
1486
1487 uint64_t BasicMBRData::GetLength(int i) {
1488    MBRPart* thePart;
1489    uint64_t retval;
1490
1491    thePart = GetPartition(i);
1492    if (thePart != NULL) {
1493       retval = thePart->GetLengthLBA();
1494    } else
1495       retval = UINT64_C(0);
1496       return retval;
1497 } // BasicMBRData::GetLength()
1498
1499 /***********************
1500  *                     *
1501  * Protected functions *
1502  *                     *
1503  ***********************/
1504
1505 // Return a pointer to a primary or logical partition, or NULL if
1506 // the partition is out of range....
1507 MBRPart* BasicMBRData::GetPartition(int i) {
1508    MBRPart* thePart = NULL;
1509
1510    if ((i >= 0) && (i < MAX_MBR_PARTS))
1511       thePart = &partitions[i];
1512    return thePart;
1513 } // GetPartition()
1514
1515 /*******************************************
1516  *                                         *
1517  * Functions that involve user interaction *
1518  *                                         *
1519  *******************************************/
1520
1521 // Present the MBR operations menu. Note that the 'w' option does not
1522 // immediately write data; that's handled by the calling function.
1523 // Returns the number of partitions defined on exit, or -1 if the
1524 // user selected the 'q' option. (Thus, the caller should save data
1525 // if the return value is >0, or possibly >=0 depending on intentions.)
1526 int BasicMBRData::DoMenu(const string& prompt) {
1527    int goOn = 1, quitting = 0, retval, num, haveShownInfo = 0;
1528    unsigned int hexCode;
1529    string tempStr;
1530
1531    do {
1532       cout << prompt;
1533       switch (ReadString()[0]) {
1534          case '\0':
1535             goOn = cin.good();
1536             break;
1537          case 'a': case 'A':
1538             num = GetNumber(1, MAX_MBR_PARTS, 1, "Toggle active flag for partition: ") - 1;
1539             if (partitions[num].GetInclusion() != NONE)
1540                partitions[num].SetStatus(partitions[num].GetStatus() ^ 0x80);
1541             break;
1542          case 'c': case 'C':
1543             for (num = 0; num < MAX_MBR_PARTS; num++)
1544                RecomputeCHS(num);
1545             break;
1546          case 'l': case 'L':
1547             num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to set as logical: ") - 1;
1548             SetInclusionwChecks(num, LOGICAL);
1549             break;
1550          case 'o': case 'O':
1551             num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to omit: ") - 1;
1552             SetInclusionwChecks(num, NONE);
1553             break;
1554          case 'p': case 'P':
1555             if (!haveShownInfo) {
1556                cout << "\n** NOTE: Partition numbers do NOT indicate final primary/logical "
1557                     << "status,\n** unlike in most MBR partitioning tools!\n\a";
1558                cout << "\n** Extended partitions are not displayed, but will be generated "
1559                     << "as required.\n";
1560                haveShownInfo = 1;
1561             } // if
1562             DisplayMBRData();
1563             break;
1564          case 'q': case 'Q':
1565             cout << "This will abandon your changes. Are you sure? ";
1566             if (GetYN() == 'Y') {
1567                goOn = 0;
1568                quitting = 1;
1569             } // if
1570             break;
1571          case 'r': case 'R':
1572             num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to set as primary: ") - 1;
1573             SetInclusionwChecks(num, PRIMARY);
1574             break;
1575          case 's': case 'S':
1576             SortMBR();
1577             break;
1578          case 't': case 'T':
1579             num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to change type code: ") - 1;
1580             hexCode = 0x00;
1581             if (partitions[num].GetLengthLBA() > 0) {
1582                while ((hexCode <= 0) || (hexCode > 255)) {
1583                   cout << "Enter an MBR hex code: ";
1584                   tempStr = ReadString();
1585                   if (IsHex(tempStr))
1586                      sscanf(tempStr.c_str(), "%x", &hexCode);
1587                } // while
1588                partitions[num].SetType(hexCode);
1589             } // if
1590             break;
1591          case 'w': case 'W':
1592             goOn = 0;
1593             break;
1594          default:
1595             ShowCommands();
1596             break;
1597       } // switch
1598    } while (goOn);
1599    if (quitting)
1600       retval = -1;
1601    else
1602       retval = CountParts();
1603    return (retval);
1604 } // BasicMBRData::DoMenu()
1605
1606 void BasicMBRData::ShowCommands(void) {
1607    cout << "a\ttoggle the active/boot flag\n";
1608    cout << "c\trecompute all CHS values\n";
1609    cout << "l\tset partition as logical\n";
1610    cout << "o\tomit partition\n";
1611    cout << "p\tprint the MBR partition table\n";
1612    cout << "q\tquit without saving changes\n";
1613    cout << "r\tset partition as primary\n";
1614    cout << "s\tsort MBR partitions\n";
1615    cout << "t\tchange partition type code\n";
1616    cout << "w\twrite the MBR partition table to disk and exit\n";
1617 } // BasicMBRData::ShowCommands()