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