1 /* basicmbr.cc -- Functions for loading, saving, and manipulating legacy MBR partition
4 /* Initial coding by Rod Smith, January to February, 2009 */
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. */
9 #define __STDC_LIMIT_MACROS
10 #define __STDC_CONSTANT_MACROS
27 /****************************************
29 * MBRData class and related structures *
31 ****************************************/
33 BasicMBRData::BasicMBRData(void) {
34 blockSize = SECTOR_SIZE;
39 numSecspTrack = MAX_SECSPERTRACK;
42 // memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
44 } // BasicMBRData default constructor
46 BasicMBRData::BasicMBRData(string filename) {
47 blockSize = SECTOR_SIZE;
52 numSecspTrack = MAX_SECSPERTRACK;
55 // memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
57 // Try to read the specified partition table, but if it fails....
58 if (!ReadMBRData(filename)) {
62 } // BasicMBRData(string filename) constructor
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
67 BasicMBRData::~BasicMBRData(void) {
70 } // BasicMBRData destructor
72 // Assignment operator -- copy entire set of MBR data.
73 BasicMBRData & BasicMBRData::operator=(const BasicMBRData & orig) {
76 memcpy(code, orig.code, 440);
77 diskSignature = orig.diskSignature;
79 MBRSignature = orig.MBRSignature;
80 blockSize = orig.blockSize;
81 diskSize = orig.diskSize;
82 numHeads = orig.numHeads;
83 numSecspTrack = orig.numSecspTrack;
84 canDeleteMyDisk = orig.canDeleteMyDisk;
90 cerr << "Unable to allocate memory in BasicMBRData::operator=()! Terminating!\n";
93 if (orig.myDisk != NULL)
94 myDisk->OpenForRead(orig.myDisk->GetName());
96 for (i = 0; i < MAX_MBR_PARTS; i++) {
97 partitions[i] = orig.partitions[i];
100 } // BasicMBRData::operator=()
102 /**********************
104 * Disk I/O functions *
106 **********************/
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) {
113 if (myDisk == NULL) {
115 if (myDisk == NULL) {
116 cerr << "Unable to allocate memory in BasicMBRData::ReadMBRData()! Terminating!\n";
121 if (myDisk->OpenForRead(deviceFilename)) {
122 allOK = ReadMBRData(myDisk);
128 device = deviceFilename;
131 } // BasicMBRData::ReadMBRData(const string & deviceFilename)
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;
143 if ((myDisk != NULL) && (myDisk != theDisk) && (canDeleteMyDisk)) {
150 // Empty existing MBR data, including the logical partitions...
154 if (myDisk->Read(&tempMBR, 512))
157 cerr << "Problem reading disk in BasicMBRData::ReadMBRData()!\n";
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;
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();
181 if (MBRSignature != MBR_SIGNATURE) {
187 diskSize = myDisk->DiskSize(&err);
190 if (checkBlockSize) {
191 blockSize = myDisk->GetBlockSize();
192 } // if (checkBlockSize)
194 // Load logical partition data, if any is found....
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
205 } // if primary partition is extended
206 } // for primary partition loop
207 if (allOK) { // Loaded logicals OK
214 // Check to see if it's in GPT format....
216 for (i = 0; i < 4; i++) {
217 if (partitions[i].GetType() == UINT8_C(0xEE)) {
223 // If there's an EFI GPT partition, look for other partition types,
226 for (i = 0 ; i < 4; i++) {
227 if ((partitions[i].GetType() != UINT8_C(0xEE)) &&
228 (partitions[i].GetType() != UINT8_C(0x00)))
231 cerr << "Warning! MBR Logical partitions found on a hybrid MBR disk! This is an\n"
232 << "EXTREMELY dangerous configuration!\n\a";
234 } // if (hybrid detection code)
235 } // no initial error
237 } // BasicMBRData::ReadMBRData(DiskIO * theDisk, int checkBlockSize)
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
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) {
249 int i, another = 1, allOK = 1;
252 uint64_t EbrLocations[MAX_MBR_PARTS];
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";
264 EbrLocations[partNum] = offset;
265 if (myDisk->Seek(offset) == 0) { // seek to EBR record
266 cerr << "Unable to seek to " << offset << "! Aborting!\n";
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";
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);
281 if (ebr.MBRSignature != MBR_SIGNATURE) {
283 cerr << "EBR signature for logical partition invalid; read 0x";
286 cerr.setf(ios::uppercase);
287 cerr << hex << ebr.MBRSignature << ", but should be 0x";
289 cerr << MBR_SIGNATURE << dec << "\n";
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;
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);
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;
314 } // if another partition
318 return (partNum * allOK);
319 } // BasicMBRData::ReadLogicalPart()
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) {
327 if (myDisk != NULL) {
328 if (myDisk->OpenForWrite() != 0) {
329 allOK = WriteMBRData(myDisk);
330 cout << "Done writing data!\n";
337 } // BasicMBRData::WriteMBRData(void)
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
347 allOK = CreateExtended();
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();
362 allOK = allOK && WriteMBRData(tempMBR, theDisk, 0);
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;
375 partNum = FindNextInUse(4);
376 writeEbrTo = (uint64_t) extFirstLBA;
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);
392 tempMBR.partitions[1].partitionType = 0x00;
393 tempMBR.partitions[1].firstLBA = 0;
394 tempMBR.partitions[1].lengthLBA = 0;
397 allOK = WriteMBRData(tempMBR, theDisk, writeEbrTo);
398 writeEbrTo = (uint64_t) tempMBR.partitions[1].firstLBA + (uint64_t) extFirstLBA;
401 DeleteExtendedParts();
403 } // BasicMBRData::WriteMBRData(DiskIO *theDisk)
405 int BasicMBRData::WriteMBRData(const string & deviceFilename) {
406 device = deviceFilename;
407 return WriteMBRData();
408 } // BasicMBRData::WriteMBRData(const string & deviceFilename)
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)
413 // Returns 1 on success, 0 on failure
414 int BasicMBRData::WriteMBRData(struct TempMBR & mbr, DiskIO *theDisk, uint64_t sector) {
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);
428 // Now write the data structure...
429 allOK = theDisk->OpenForWrite();
430 if (allOK && theDisk->Seek(sector)) {
431 if (theDisk->Write(&mbr, 512) != 512) {
433 cerr << "Error " << errno << " when saving MBR!\n";
437 cerr << "Error " << errno << " when seeking to MBR to write it!\n";
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);
452 } // BasicMBRData::WriteMBRData(uint64_t sector)
454 // Set a new disk device; used in copying one disk's partition
455 // table to another disk.
456 void BasicMBRData::SetDisk(DiskIO *theDisk) {
460 diskSize = theDisk->DiskSize(&err);
463 } // BasicMBRData::SetDisk()
465 /********************************************
467 * Functions that display data for the user *
469 ********************************************/
471 // Show the MBR data to the user, up to the specified maximum number
473 void BasicMBRData::DisplayMBRData(void) {
476 cout << "\nDisk size is " << diskSize << " sectors ("
477 << BytesToIeee(diskSize, blockSize) << ")\n";
478 cout << "MBR disk identifier: 0x";
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";
487 cout << " Can Be Can Be\n";
488 cout << "Number Boot Start Sector End Sector Status Logical Primary Code\n";
489 UpdateCanBeLogical();
491 for (i = 0; i < MAX_MBR_PARTS; i++) {
492 if (partitions[i].GetLengthLBA() != 0) {
495 cout << i + 1 << " ";
496 partitions[i].ShowData((state == gpt) || (state == hybrid));
500 } // BasicMBRData::DisplayMBRData()
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) {
507 cout << " MBR: not present\n";
510 cout << " MBR: protective\n";
513 cout << " MBR: hybrid\n";
516 cout << " MBR: MBR only\n";
519 cout << "\a MBR: unknown -- bug!\n";
522 } // BasicMBRData::ShowState()
524 /************************
526 * GPT Checks and fixes *
528 ************************/
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) {
537 char signature1[9], signature2[9];
539 if (myDisk != NULL) {
540 if (myDisk->OpenForRead() != 0) {
541 if (myDisk->Seek(1)) {
542 myDisk->Read(signature1, 8);
543 signature1[8] = '\0';
545 if (myDisk->Seek(myDisk->DiskSize(&err) - 1)) {
546 myDisk->Read(signature2, 8);
547 signature2[8] = '\0';
549 if ((retval >= 0) && (strcmp(signature1, "EFI PART") == 0))
551 if ((retval >= 0) && (strcmp(signature2, "EFI PART") == 0))
559 } // BasicMBRData::CheckForGPT()
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) {
570 memset(blank, 0, 512);
571 switch (CheckForGPT()) {
578 if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
579 if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
585 if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
586 if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
587 (myDisk->Write(blank, 512) == 512)))
593 if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
594 if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
596 if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
597 (myDisk->Write(blank, 512) == 512)))
606 } // BasicMBRData::BlankGPTData
608 /*********************************************************************
610 * Functions that set or get disk metadata (CHS geometry, disk size, *
613 *********************************************************************/
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) {
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()
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) {
638 *low = MAX_MBR_PARTS + 1; // code for "not found"
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))
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))
655 } // GPTData::GetPartRange()
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
661 int BasicMBRData::LBAtoCHS(uint64_t lba, uint8_t * chs) {
662 uint64_t cylinder, head, sector; // all numbered from 0
668 // Special case: In case of 0 LBA value, zero out CHS values....
670 chs[0] = chs[1] = chs[2] = UINT8_C(0);
673 // If LBA value is too large for CHS, max out CHS values....
674 if ((!done) && (lba >= (numHeads * numSecspTrack * MAX_CYLINDERS))) {
676 chs[1] = chs[2] = 255;
680 // If neither of the above applies, compute CHS values....
682 cylinder = lba / (uint64_t) (numHeads * numSecspTrack);
683 remainder = lba - (cylinder * numHeads * numSecspTrack);
684 head = remainder / numSecspTrack;
685 remainder -= head * numSecspTrack;
688 chs[0] = (uint8_t) head;
691 if (sector < numSecspTrack) {
692 chs[1] = (uint8_t) ((sector + 1) + (cylinder >> 8) * 64);
693 chs[2] = (uint8_t) (cylinder & UINT64_C(0xFF));
697 } // if value is expressible and non-0
698 } else { // Invalid (NULL) chs pointer
700 } // if CHS pointer valid
702 } // BasicMBRData::LBAtoCHS()
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;
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]))) {
714 cout << "\nProblem: MBR partitions " << i + 1 << " and " << j + 1
718 if (partitions[i].GetType() == 0xEE) {
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";
726 cout << "\nCaution: More than one 0xEE MBR partition found. This can cause problems\n"
727 << "in some OSes.\n";
730 } // BasicMBRData::FindOverlaps()
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;
737 for (i = 0; i < MAX_MBR_PARTS; i++) {
738 if (partitions[i].GetLengthLBA() > 0) {
739 if (partitions[i].GetInclusion() == PRIMARY)
741 if (partitions[i].GetInclusion() == LOGICAL)
745 return (numPrimaries + logicalsFound);
746 } // BasicMBRData::NumPrimaries()
748 // Returns the number of logical partitions.
749 int BasicMBRData::NumLogicals(void) {
750 int i, numLogicals = 0;
752 for (i = 0; i < MAX_MBR_PARTS; i++) {
753 if (partitions[i].GetInclusion() == LOGICAL)
757 } // BasicMBRData::NumLogicals()
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) {
764 for (i = 0; i < MAX_MBR_PARTS; i++) {
765 if ((partitions[i].GetInclusion() == LOGICAL) ||
766 (partitions[i].GetInclusion() == PRIMARY))
770 } // BasicMBRData::CountParts()
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;
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);
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);
805 if ((sectorBefore != EBR) && (sectorBefore != NONE))
806 partitions[i].SetCanBeLogical(0);
808 partitions[i].SetCanBeLogical(lastLogical == 0); // can be logical only if no logicals already
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) &&
816 partitions[i].SetCanBePrimary(1);
818 if ((partitions[i].GetStartLBA() > (firstLogical + 1)) &&
819 (partitions[i].GetLastLBA() < lastLogical))
820 partitions[i].SetCanBePrimary(0);
823 } // BasicMBRData::UpdateCanBeLogical()
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) {
830 uint64_t firstFound = UINT32_MAX;
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();
839 } // BasicMBRData::FirstLogicalLBA()
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) {
845 uint64_t lastFound = 0;
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();
853 } // BasicMBRData::LastLogicalLBA()
855 // Returns 1 if logical partitions are contiguous (have no primaries
856 // in their midst), or 0 if one or more primaries exist between
858 int BasicMBRData::AreLogicalsContiguous(void) {
859 int allOK = 1, i = 0;
860 uint64_t firstLogical, lastLogical;
862 firstLogical = FirstLogicalLBA() - 1; // subtract 1 for EBR
863 lastLogical = LastLogicalLBA();
864 if (lastLogical > 0) {
866 if ((partitions[i].GetInclusion() == PRIMARY) &&
867 (partitions[i].GetStartLBA() >= firstLogical) &&
868 (partitions[i].GetStartLBA() <= lastLogical)) {
872 } while ((i < MAX_MBR_PARTS) && allOK);
875 } // BasicMBRData::AreLogicalsContiguous()
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) {
882 for (i = 0; i < MAX_MBR_PARTS; i++) {
883 if ((partitions[i].GetStartLBA() > diskSize) || (partitions[i].GetLastLBA() > diskSize)) {
888 } // BasicMBRData::DoTheyFit(void)
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
893 int BasicMBRData::SpaceBeforeAllLogicals(void) {
894 int i = 0, allOK = 1;
897 if ((partitions[i].GetStartLBA() > 0) && (partitions[i].GetInclusion() == LOGICAL)) {
898 allOK = allOK && (SectorUsedAs(partitions[i].GetStartLBA() - 1) == EBR);
901 } while (allOK && (i < MAX_MBR_PARTS));
903 } // BasicMBRData::SpaceBeforeAllLogicals()
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) {
916 allOK = (FindOverlaps() == 0);
917 allOK = (allOK && (NumPrimaries() <= 4));
918 allOK = (allOK && AreLogicalsContiguous());
919 allOK = (allOK && DoTheyFit());
920 allOK = (allOK && SpaceBeforeAllLogicals());
922 } // BasicMBRData::IsLegal()
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)
929 while ((start < MAX_MBR_PARTS) && (start >= 0) && (partitions[start].GetInclusion() == NONE))
931 if ((start < 0) || (start >= MAX_MBR_PARTS))
934 } // BasicMBRData::FindFirstLogical();
936 /*****************************************************
938 * Functions to create, delete, or change partitions *
940 *****************************************************/
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) {
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
950 if (clearBootloader == 1) {
954 // Blank out the partitions
955 for (i = 0; i < MAX_MBR_PARTS; i++) {
956 partitions[i].Empty();
958 MBRSignature = MBR_SIGNATURE;
960 } // BasicMBRData::EmptyMBR()
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) {
968 for (i = 0; i < 440; i++)
971 } // BasicMBRData::EmptyBootloader
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()
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);
999 partitions[num].SetInclusion(PRIMARY);
1001 partitions[num].SetInclusion(LOGICAL);
1002 SetPartBootable(num, bootable);
1003 } // if valid partition number & size
1004 } // BasicMBRData::MakePart()
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) {
1011 if ((num >= 0) && (num < MAX_MBR_PARTS)) {
1012 if (partitions[num].GetLengthLBA() != UINT32_C(0)) {
1013 allOK = partitions[num].SetType(type);
1017 } // BasicMBRData::SetPartType()
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) {
1025 if ((num >= 0) && (num < MAX_MBR_PARTS)) {
1026 if (partitions[num].GetLengthLBA() != UINT32_C(0)) {
1028 partitions[num].SetStatus(UINT8_C(0x00));
1030 partitions[num].SetStatus(UINT8_C(0x80));
1034 } // BasicMBRData::SetPartBootable()
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
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;
1057 start = lastBlock + 1;
1059 } while (firstBlock != 0);
1060 if ((selectedSize > UINT64_C(0)) && (selectedSize < diskSize)) {
1062 MakePart(i, selectedSegment, selectedSize, type, 0);
1067 } // BasicMBRData::MakeBiggestPart(int i)
1069 // Delete partition #i
1070 void BasicMBRData::DeletePartition(int i) {
1071 partitions[i].Empty();
1072 } // BasicMBRData::DeletePartition()
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;
1081 if ((inclStatus == PRIMARY) || (inclStatus == LOGICAL) || (inclStatus == NONE)) {
1082 origValue = partitions[num].GetInclusion();
1083 partitions[num].SetInclusion(inclStatus);
1085 partitions[num].SetInclusion(origValue);
1086 cerr << "Specified change is not legal! Aborting change!\n";
1089 cerr << "Invalid partition inclusion code in BasicMBRData::SetInclusionwChecks()!\n";
1092 cerr << "Partition table is not currently in a valid state. Aborting change!\n";
1096 } // BasicMBRData::SetInclusionwChecks()
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()
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()
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() {
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();
1133 } // BasicMBRData::DeleteOversizedParts()
1135 // Search for and delete extended partitions.
1136 // Returns the number of partitions deleted.
1137 int BasicMBRData::DeleteExtendedParts() {
1138 int i, numDeleted = 0;
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();
1150 } // BasicMBRData::DeleteExtendedParts()
1152 // Finds any overlapping partitions and omits the smaller of the two.
1153 void BasicMBRData::OmitOverlaps() {
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);
1163 partitions[j].SetInclusion(NONE);
1167 } // BasicMBRData::OmitOverlaps()
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;
1174 for (i = MAX_MBR_PARTS - 1; i >= 0; i--) {
1175 UpdateCanBeLogical();
1177 if (partitions[i].CanBeLogical()) {
1178 partitions[i].SetInclusion(LOGICAL);
1179 } else if (partitions[i].CanBePrimary()) {
1180 partitions[i].SetInclusion(PRIMARY);
1182 partitions[i].SetInclusion(NONE);
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()
1191 // Add primaries up to the maximum allowed, from the omitted category.
1192 void BasicMBRData::MaximizePrimaries() {
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);
1200 UpdateCanBeLogical();
1204 } // BasicMBRData::MaximizePrimaries()
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;
1211 numToDelete = NumPrimaries() - 4;
1212 while ((numToDelete > 0) && (i >= 0)) {
1213 if (partitions[i].GetInclusion() == PRIMARY) {
1214 partitions[i].SetInclusion(NONE);
1218 } // while (numToDelete > 0)
1219 } // BasicMBRData::TrimPrimaries()
1221 // Locates primary partitions located between logical partitions and
1222 // either converts the primaries into logicals (if possible) or omits
1224 void BasicMBRData::MakeLogicalsContiguous(void) {
1225 uint64_t firstLogicalLBA, lastLogicalLBA;
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);
1237 partitions[i].SetInclusion(NONE);
1240 } // BasicMBRData::MakeLogicalsContiguous()
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) {
1246 DeleteOversizedParts();
1248 MaximizePrimaries();
1249 if (!AreLogicalsContiguous())
1250 MakeLogicalsContiguous();
1251 if (NumPrimaries() > 4)
1255 } // BasicMBRData::MakeItLegal()
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;
1264 for (i = 0; i < 4; i++) {
1265 if ((partitions[i].GetInclusion() != PRIMARY) && (partitions[i].GetLengthLBA() > 0)) {
1269 if ((partitions[j].GetInclusion() == NONE) && (partitions[j].GetLengthLBA() == 0)) {
1270 temp = partitions[j];
1271 partitions[j] = partitions[i];
1272 partitions[i] = temp;
1277 } while ((j < MAX_MBR_PARTS) && !swapped);
1278 if (j >= MAX_MBR_PARTS)
1279 cerr << "Warning! Too many partitions in BasicMBRData::RemoveLogicalsFromFirstFour()!\n";
1283 } // BasicMBRData::RemoveLogicalsFromFirstFour()
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;
1291 for (i = 4; i < MAX_MBR_PARTS; i++) {
1292 if (partitions[i].GetInclusion() == PRIMARY) {
1296 if (partitions[j].GetInclusion() != PRIMARY) {
1297 temp = partitions[j];
1298 partitions[j] = partitions[i];
1299 partitions[i] = temp;
1304 } while ((j < 4) && !swapped);
1308 } // BasicMBRData::MovePrimariesToFirstFour()
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
1313 // Returns 1 on success, 0 on failure.
1314 int BasicMBRData::CreateExtended(void) {
1315 int allOK = 1, i = 0, swapped = 0;
1319 // Move logicals out of primary space...
1320 RemoveLogicalsFromFirstFour();
1321 // Move primaries out of logical space...
1322 MovePrimariesToFirstFour();
1324 // Create the extended partition
1325 if (NumLogicals() > 0) {
1326 SortMBR(4); // sort starting from 4 -- that is, logicals only
1328 temp.SetStartLBA(FirstLogicalLBA() - 1);
1329 temp.SetLengthLBA(LastLogicalLBA() - FirstLogicalLBA() + 2);
1330 temp.SetType(0x0f, 1);
1331 temp.SetInclusion(PRIMARY);
1333 if ((partitions[i].GetInclusion() == NONE) || (partitions[i].GetLengthLBA() == 0)) {
1334 partitions[i] = temp;
1338 } while ((i < 4) && !swapped);
1340 cerr << "Could not create extended partition; no room in primary table!\n";
1343 } // if (NumLogicals() > 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)
1351 } // BasicMBRData::CreateExtended()
1353 /****************************************
1355 * Functions to find data on free space *
1357 ****************************************/
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) {
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....
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();
1383 } while (firstMoved == 1);
1384 if ((first >= diskSize) || (first > UINT32_MAX))
1387 } // BasicMBRData::FindFirstAvailable()
1389 // Finds the last free sector on the disk from start forward.
1390 uint64_t BasicMBRData::FindLastInFree(uint64_t start) {
1391 uint64_t nearestStart;
1394 if ((diskSize <= UINT32_MAX) && (diskSize > 0))
1395 nearestStart = diskSize - 1;
1397 nearestStart = UINT32_MAX - 1;
1399 for (i = 0; i < 4; i++) {
1400 if ((nearestStart > partitions[i].GetStartLBA()) &&
1401 (partitions[i].GetStartLBA() > start)) {
1402 nearestStart = partitions[i].GetStartLBA() - 1;
1405 return (nearestStart);
1406 } // BasicMBRData::FindLastInFree()
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;
1414 for (i = 0; i < 4; i++) {
1415 thisLastLBA = partitions[i].GetLastLBA() + 1;
1416 if (thisLastLBA > 0)
1418 if ((thisLastLBA > bestLastLBA) && (thisLastLBA < start))
1419 bestLastLBA = thisLastLBA + 1;
1421 return (bestLastLBA);
1422 } // BasicMBRData::FindFirstInFree()
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;
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))
1438 if (sector >= diskSize)
1441 } while ((i < topPartNum) && ((usedAs == NONE) || (usedAs == EBR)));
1443 } // BasicMBRData::SectorUsedAs()
1445 /******************************************************
1447 * Functions that extract data on specific partitions *
1449 ******************************************************/
1451 uint8_t BasicMBRData::GetStatus(int i) {
1455 thePart = GetPartition(i);
1456 if (thePart != NULL)
1457 retval = thePart->GetStatus();
1459 retval = UINT8_C(0);
1461 } // BasicMBRData::GetStatus()
1463 uint8_t BasicMBRData::GetType(int i) {
1467 thePart = GetPartition(i);
1468 if (thePart != NULL)
1469 retval = thePart->GetType();
1471 retval = UINT8_C(0);
1473 } // BasicMBRData::GetType()
1475 uint64_t BasicMBRData::GetFirstSector(int i) {
1479 thePart = GetPartition(i);
1480 if (thePart != NULL) {
1481 retval = thePart->GetStartLBA();
1483 retval = UINT32_C(0);
1485 } // BasicMBRData::GetFirstSector()
1487 uint64_t BasicMBRData::GetLength(int i) {
1491 thePart = GetPartition(i);
1492 if (thePart != NULL) {
1493 retval = thePart->GetLengthLBA();
1495 retval = UINT64_C(0);
1497 } // BasicMBRData::GetLength()
1499 /***********************
1501 * Protected functions *
1503 ***********************/
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;
1510 if ((i >= 0) && (i < MAX_MBR_PARTS))
1511 thePart = &partitions[i];
1515 /*******************************************
1517 * Functions that involve user interaction *
1519 *******************************************/
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;
1533 switch (ReadString()[0]) {
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);
1543 for (num = 0; num < MAX_MBR_PARTS; num++)
1547 num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to set as logical: ") - 1;
1548 SetInclusionwChecks(num, LOGICAL);
1551 num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to omit: ") - 1;
1552 SetInclusionwChecks(num, NONE);
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";
1565 cout << "This will abandon your changes. Are you sure? ";
1566 if (GetYN() == 'Y') {
1572 num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to set as primary: ") - 1;
1573 SetInclusionwChecks(num, PRIMARY);
1579 num = GetNumber(1, MAX_MBR_PARTS, 1, "Partition to change type code: ") - 1;
1581 if (partitions[num].GetLengthLBA() > 0) {
1582 while ((hexCode <= 0) || (hexCode > 255)) {
1583 cout << "Enter an MBR hex code: ";
1584 tempStr = ReadString();
1586 sscanf(tempStr.c_str(), "%x", &hexCode);
1588 partitions[num].SetType(hexCode);
1602 retval = CountParts();
1604 } // BasicMBRData::DoMenu()
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()