-
Notifications
You must be signed in to change notification settings - Fork 2
/
basicmbr.cc
1637 lines (1475 loc) · 57.8 KB
/
basicmbr.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* basicmbr.cc -- Functions for loading, saving, and manipulating legacy MBR partition
data. */
/* Initial coding by Rod Smith, January to February, 2009 */
/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <errno.h>
#include <iostream>
#include <algorithm>
#include "mbr.h"
#include "support.h"
using namespace std;
/****************************************
* *
* MBRData class and related structures *
* *
****************************************/
BasicMBRData::BasicMBRData(void) {
blockSize = SECTOR_SIZE;
diskSize = 0;
device = "";
state = invalid;
numHeads = MAX_HEADS;
numSecspTrack = MAX_SECSPERTRACK;
myDisk = NULL;
canDeleteMyDisk = 0;
// memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
EmptyMBR();
} // BasicMBRData default constructor
BasicMBRData::BasicMBRData(string filename) {
blockSize = SECTOR_SIZE;
diskSize = 0;
device = filename;
state = invalid;
numHeads = MAX_HEADS;
numSecspTrack = MAX_SECSPERTRACK;
myDisk = NULL;
canDeleteMyDisk = 0;
// memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint32_t));
// Try to read the specified partition table, but if it fails....
if (!ReadMBRData(filename)) {
EmptyMBR();
device = "";
} // if
} // BasicMBRData(string filename) constructor
// Free space used by myDisk only if that's OK -- sometimes it will be
// copied from an outside source, in which case that source should handle
// it!
BasicMBRData::~BasicMBRData(void) {
if (canDeleteMyDisk)
delete myDisk;
} // BasicMBRData destructor
// Assignment operator -- copy entire set of MBR data.
BasicMBRData & BasicMBRData::operator=(const BasicMBRData & orig) {
int i;
memcpy(code, orig.code, 440);
diskSignature = orig.diskSignature;
nulls = orig.nulls;
MBRSignature = orig.MBRSignature;
blockSize = orig.blockSize;
diskSize = orig.diskSize;
numHeads = orig.numHeads;
numSecspTrack = orig.numSecspTrack;
canDeleteMyDisk = orig.canDeleteMyDisk;
device = orig.device;
state = orig.state;
myDisk = new DiskIO;
if (myDisk == NULL) {
cerr << "Unable to allocate memory in BasicMBRData::operator=()! Terminating!\n";
exit(1);
} // if
if (orig.myDisk != NULL)
myDisk->OpenForRead(orig.myDisk->GetName());
for (i = 0; i < MAX_MBR_PARTS; i++) {
partitions[i] = orig.partitions[i];
} // for
return *this;
} // BasicMBRData::operator=()
/**********************
* *
* Disk I/O functions *
* *
**********************/
// Read data from MBR. Returns 1 if read was successful (even if the
// data isn't a valid MBR), 0 if the read failed.
int BasicMBRData::ReadMBRData(const string & deviceFilename) {
int allOK = 1;
if (myDisk == NULL) {
myDisk = new DiskIO;
if (myDisk == NULL) {
cerr << "Unable to allocate memory in BasicMBRData::ReadMBRData()! Terminating!\n";
exit(1);
} // if
canDeleteMyDisk = 1;
} // if
if (myDisk->OpenForRead(deviceFilename)) {
allOK = ReadMBRData(myDisk);
} else {
allOK = 0;
} // if
if (allOK)
device = deviceFilename;
return allOK;
} // BasicMBRData::ReadMBRData(const string & deviceFilename)
// Read data from MBR. If checkBlockSize == 1 (the default), the block
// size is checked; otherwise it's set to the default (512 bytes).
// Note that any extended partition(s) present will be omitted from
// in the partitions[] array; these partitions must be re-created when
// the partition table is saved in MBR format.
int BasicMBRData::ReadMBRData(DiskIO * theDisk, int checkBlockSize) {
int allOK = 1, i, logicalNum = 3;
int err = 1;
TempMBR tempMBR;
if ((myDisk != NULL) && (myDisk != theDisk) && (canDeleteMyDisk)) {
delete myDisk;
canDeleteMyDisk = 0;
} // if
myDisk = theDisk;
// Empty existing MBR data, including the logical partitions...
EmptyMBR(0);
if (myDisk->Seek(0))
if (myDisk->Read(&tempMBR, 512))
err = 0;
if (err) {
cerr << "Problem reading disk in BasicMBRData::ReadMBRData()!\n";
} else {
for (i = 0; i < 440; i++)
code[i] = tempMBR.code[i];
diskSignature = tempMBR.diskSignature;
nulls = tempMBR.nulls;
for (i = 0; i < 4; i++) {
partitions[i] = tempMBR.partitions[i];
if (partitions[i].GetLengthLBA() > 0)
partitions[i].SetInclusion(PRIMARY);
} // for i... (reading all four partitions)
MBRSignature = tempMBR.MBRSignature;
ReadCHSGeom();
// Reverse the byte order, if necessary
if (IsLittleEndian() == 0) {
ReverseBytes(&diskSignature, 4);
ReverseBytes(&nulls, 2);
ReverseBytes(&MBRSignature, 2);
for (i = 0; i < 4; i++) {
partitions[i].ReverseByteOrder();
} // for
} // if
if (MBRSignature != MBR_SIGNATURE) {
allOK = 0;
state = invalid;
} // if
// Find disk size
diskSize = myDisk->DiskSize(&err);
// Find block size
if (checkBlockSize) {
blockSize = myDisk->GetBlockSize();
} // if (checkBlockSize)
// Load logical partition data, if any is found....
if (allOK) {
for (i = 0; i < 4; i++) {
if ((partitions[i].GetType() == 0x05) || (partitions[i].GetType() == 0x0f)
|| (partitions[i].GetType() == 0x85)) {
// Found it, so call a function to load everything from them....
logicalNum = ReadLogicalParts(partitions[i].GetStartLBA(), abs(logicalNum) + 1);
if (logicalNum < 0) {
cerr << "Error reading logical partitions! List may be truncated!\n";
} // if maxLogicals valid
DeletePartition(i);
} // if primary partition is extended
} // for primary partition loop
if (allOK) { // Loaded logicals OK
state = mbr;
} else {
state = invalid;
} // if
} // if
// Check to see if it's in GPT format....
if (allOK) {
for (i = 0; i < 4; i++) {
if (partitions[i].GetType() == UINT8_C(0xEE)) {
state = gpt;
} // if
} // for
} // if
// If there's an EFI GPT partition, look for other partition types,
// to flag as hybrid
if (state == gpt) {
for (i = 0 ; i < 4; i++) {
if ((partitions[i].GetType() != UINT8_C(0xEE)) &&
(partitions[i].GetType() != UINT8_C(0x00)))
state = hybrid;
if (logicalNum != 3)
cerr << "Warning! MBR Logical partitions found on a hybrid MBR disk! This is an\n"
<< "EXTREMELY dangerous configuration!\n\a";
} // for
} // if (hybrid detection code)
} // no initial error
return allOK;
} // BasicMBRData::ReadMBRData(DiskIO * theDisk, int checkBlockSize)
// This is a function to read all the logical partitions, following the
// logical partition linked list from the disk and storing the basic data in the
// partitions[] array. Returns last index to partitions[] used, or -1 times the
// that index if there was a problem. (Some problems can leave valid logical
// partition data.)
// Parameters:
// extendedStart = LBA of the start of the extended partition
// partNum = number of first partition in extended partition (normally 4).
int BasicMBRData::ReadLogicalParts(uint64_t extendedStart, int partNum) {
struct TempMBR ebr;
int i, another = 1, allOK = 1;
uint8_t ebrType;
uint64_t offset;
uint64_t EbrLocations[MAX_MBR_PARTS];
offset = extendedStart;
memset(&EbrLocations, 0, MAX_MBR_PARTS * sizeof(uint64_t));
while (another && (partNum < MAX_MBR_PARTS) && (partNum >= 0) && (allOK > 0)) {
for (i = 0; i < MAX_MBR_PARTS; i++) {
if (EbrLocations[i] == offset) { // already read this one; infinite logical partition loop!
cerr << "Logical partition infinite loop detected! This is being corrected.\n";
allOK = -1;
partNum -= 1;
} // if
} // for
EbrLocations[partNum] = offset;
if (myDisk->Seek(offset) == 0) { // seek to EBR record
cerr << "Unable to seek to " << offset << "! Aborting!\n";
allOK = -1;
}
if (myDisk->Read(&ebr, 512) != 512) { // Load the data....
cerr << "Error seeking to or reading logical partition data from " << offset
<< "!\nSome logical partitions may be missing!\n";
allOK = -1;
} else if (IsLittleEndian() != 1) { // Reverse byte ordering of some data....
ReverseBytes(&ebr.MBRSignature, 2);
ReverseBytes(&ebr.partitions[0].firstLBA, 4);
ReverseBytes(&ebr.partitions[0].lengthLBA, 4);
ReverseBytes(&ebr.partitions[1].firstLBA, 4);
ReverseBytes(&ebr.partitions[1].lengthLBA, 4);
} // if/else/if
if (ebr.MBRSignature != MBR_SIGNATURE) {
allOK = -1;
cerr << "EBR signature for logical partition invalid; read 0x";
cerr.fill('0');
cerr.width(4);
cerr.setf(ios::uppercase);
cerr << hex << ebr.MBRSignature << ", but should be 0x";
cerr.width(4);
cerr << MBR_SIGNATURE << dec << "\n";
cerr.fill(' ');
} // if
if ((partNum >= 0) && (partNum < MAX_MBR_PARTS) && (allOK > 0)) {
// Sometimes an EBR points directly to another EBR, rather than defining
// a logical partition and then pointing to another EBR. Thus, we skip
// the logical partition when this is the case....
ebrType = ebr.partitions[0].partitionType;
if ((ebrType == 0x05) || (ebrType == 0x0f) || (ebrType == 0x85)) {
cout << "EBR describes a logical partition!\n";
offset = extendedStart + ebr.partitions[0].firstLBA;
} else {
// Copy over the basic data....
partitions[partNum] = ebr.partitions[0];
// Adjust the start LBA, since it's encoded strangely....
partitions[partNum].SetStartLBA(ebr.partitions[0].firstLBA + offset);
partitions[partNum].SetInclusion(LOGICAL);
// Find the next partition (if there is one)
if ((ebr.partitions[1].firstLBA != UINT32_C(0)) && (partNum < (MAX_MBR_PARTS - 1))) {
offset = extendedStart + ebr.partitions[1].firstLBA;
partNum++;
} else {
another = 0;
} // if another partition
} // if/else
} // if
} // while()
return (partNum * allOK);
} // BasicMBRData::ReadLogicalPart()
// Write the MBR data to the default defined device. This writes both the
// MBR itself and any defined logical partitions, provided there's an
// MBR extended partition.
int BasicMBRData::WriteMBRData(void) {
int allOK = 1;
if (myDisk != NULL) {
if (myDisk->OpenForWrite() != 0) {
allOK = WriteMBRData(myDisk);
cout << "Done writing data!\n";
} else {
allOK = 0;
} // if/else
myDisk->Close();
} else allOK = 0;
return allOK;
} // BasicMBRData::WriteMBRData(void)
// Save the MBR data to a file. This writes both the
// MBR itself and any defined logical partitions.
int BasicMBRData::WriteMBRData(DiskIO *theDisk) {
int i, j, partNum, next, allOK = 1, moreLogicals = 0;
uint64_t extFirstLBA = 0;
uint64_t writeEbrTo; // 64-bit because we support extended in 2-4TiB range
TempMBR tempMBR;
allOK = CreateExtended();
if (allOK) {
// First write the main MBR data structure....
memcpy(tempMBR.code, code, 440);
tempMBR.diskSignature = diskSignature;
tempMBR.nulls = nulls;
tempMBR.MBRSignature = MBRSignature;
for (i = 0; i < 4; i++) {
partitions[i].StoreInStruct(&tempMBR.partitions[i]);
if (partitions[i].GetType() == 0x0f) {
extFirstLBA = partitions[i].GetStartLBA();
moreLogicals = 1;
} // if
} // for i...
} // if
allOK = allOK && WriteMBRData(tempMBR, theDisk, 0);
// Set up tempMBR with some constant data for logical partitions...
tempMBR.diskSignature = 0;
for (i = 2; i < 4; i++) {
tempMBR.partitions[i].firstLBA = tempMBR.partitions[i].lengthLBA = 0;
tempMBR.partitions[i].partitionType = 0x00;
for (j = 0; j < 3; j++) {
tempMBR.partitions[i].firstSector[j] = 0;
tempMBR.partitions[i].lastSector[j] = 0;
} // for j
} // for i
partNum = FindNextInUse(4);
writeEbrTo = (uint64_t) extFirstLBA;
// Write logicals...
while (allOK && moreLogicals && (partNum < MAX_MBR_PARTS) && (partNum >= 0)) {
partitions[partNum].StoreInStruct(&tempMBR.partitions[0]);
tempMBR.partitions[0].firstLBA = 1;
// tempMBR.partitions[1] points to next EBR or terminates EBR linked list...
next = FindNextInUse(partNum + 1);
if ((next < MAX_MBR_PARTS) && (next > 0) && (partitions[next].GetStartLBA() > 0)) {
tempMBR.partitions[1].partitionType = 0x0f;
tempMBR.partitions[1].firstLBA = (uint32_t) (partitions[next].GetStartLBA() - extFirstLBA - 1);
tempMBR.partitions[1].lengthLBA = (uint32_t) (partitions[next].GetLengthLBA() + 1);
LBAtoCHS((uint64_t) tempMBR.partitions[1].firstLBA,
(uint8_t *) &tempMBR.partitions[1].firstSector);
LBAtoCHS(tempMBR.partitions[1].lengthLBA - extFirstLBA,
(uint8_t *) &tempMBR.partitions[1].lastSector);
} else {
tempMBR.partitions[1].partitionType = 0x00;
tempMBR.partitions[1].firstLBA = 0;
tempMBR.partitions[1].lengthLBA = 0;
moreLogicals = 0;
} // if/else
allOK = WriteMBRData(tempMBR, theDisk, writeEbrTo);
writeEbrTo = (uint64_t) tempMBR.partitions[1].firstLBA + (uint64_t) extFirstLBA;
partNum = next;
} // while
DeleteExtendedParts();
return allOK;
} // BasicMBRData::WriteMBRData(DiskIO *theDisk)
int BasicMBRData::WriteMBRData(const string & deviceFilename) {
device = deviceFilename;
return WriteMBRData();
} // BasicMBRData::WriteMBRData(const string & deviceFilename)
// Write a single MBR record to the specified sector. Used by the like-named
// function to write both the MBR and multiple EBR (for logical partition)
// records.
// Returns 1 on success, 0 on failure
int BasicMBRData::WriteMBRData(struct TempMBR & mbr, DiskIO *theDisk, uint64_t sector) {
int i, allOK;
// Reverse the byte order, if necessary
if (IsLittleEndian() == 0) {
ReverseBytes(&mbr.diskSignature, 4);
ReverseBytes(&mbr.nulls, 2);
ReverseBytes(&mbr.MBRSignature, 2);
for (i = 0; i < 4; i++) {
ReverseBytes(&mbr.partitions[i].firstLBA, 4);
ReverseBytes(&mbr.partitions[i].lengthLBA, 4);
} // for
} // if
// Now write the data structure...
allOK = theDisk->OpenForWrite();
if (allOK && theDisk->Seek(sector)) {
if (theDisk->Write(&mbr, 512) != 512) {
allOK = 0;
cerr << "Error " << errno << " when saving MBR!\n";
} // if
} else {
allOK = 0;
cerr << "Error " << errno << " when seeking to MBR to write it!\n";
} // if/else
theDisk->Close();
// Reverse the byte order back, if necessary
if (IsLittleEndian() == 0) {
ReverseBytes(&mbr.diskSignature, 4);
ReverseBytes(&mbr.nulls, 2);
ReverseBytes(&mbr.MBRSignature, 2);
for (i = 0; i < 4; i++) {
ReverseBytes(&mbr.partitions[i].firstLBA, 4);
ReverseBytes(&mbr.partitions[i].lengthLBA, 4);
} // for
}// if
return allOK;
} // BasicMBRData::WriteMBRData(uint64_t sector)
// Set a new disk device; used in copying one disk's partition
// table to another disk.
void BasicMBRData::SetDisk(DiskIO *theDisk) {
int err;
myDisk = theDisk;
diskSize = theDisk->DiskSize(&err);
canDeleteMyDisk = 0;
ReadCHSGeom();
} // BasicMBRData::SetDisk()
/********************************************
* *
* Functions that display data for the user *
* *
********************************************/
// Show the MBR data to the user, up to the specified maximum number
// of partitions....
void BasicMBRData::DisplayMBRData(void) {
int i;
cout << "\nDisk size is " << diskSize << " sectors ("
<< BytesToIeee(diskSize, blockSize) << ")\n";
cout << "MBR disk identifier: 0x";
cout.width(8);
cout.fill('0');
cout.setf(ios::uppercase);
cout << hex << diskSignature << dec << "\n";
cout << "MBR partitions:\n\n";
if ((state == gpt) || (state == hybrid)) {
cout << "Number Boot Start Sector End Sector Status Code\n";
} else {
cout << " Can Be Can Be\n";
cout << "Number Boot Start Sector End Sector Status Logical Primary Code\n";
UpdateCanBeLogical();
} //
for (i = 0; i < MAX_MBR_PARTS; i++) {
if (partitions[i].GetLengthLBA() != 0) {
cout.fill(' ');
cout.width(4);
cout << i + 1 << " ";
partitions[i].ShowData((state == gpt) || (state == hybrid));
} // if
cout.fill(' ');
} // for
} // BasicMBRData::DisplayMBRData()
// Displays the state, as a word, on stdout. Used for debugging & to
// tell the user about the MBR state when the program launches....
void BasicMBRData::ShowState(void) {
switch (state) {
case invalid:
cout << " MBR: not present\n";
break;
case gpt:
cout << " MBR: protective\n";
break;
case hybrid:
cout << " MBR: hybrid\n";
break;
case mbr:
cout << " MBR: MBR only\n";
break;
default:
cout << "\a MBR: unknown -- bug!\n";
break;
} // switch
} // BasicMBRData::ShowState()
/************************
* *
* GPT Checks and fixes *
* *
************************/
// Perform a very rudimentary check for GPT data on the disk; searches for
// the GPT signature in the main and backup metadata areas.
// Returns 0 if GPT data not found, 1 if main data only is found, 2 if
// backup only is found, 3 if both main and backup data are found, and
// -1 if a disk error occurred.
int BasicMBRData::CheckForGPT(void) {
int retval = 0, err;
char signature1[9], signature2[9];
if (myDisk != NULL) {
if (myDisk->OpenForRead() != 0) {
if (myDisk->Seek(1)) {
myDisk->Read(signature1, 8);
signature1[8] = '\0';
} else retval = -1;
if (myDisk->Seek(myDisk->DiskSize(&err) - 1)) {
myDisk->Read(signature2, 8);
signature2[8] = '\0';
} else retval = -1;
if ((retval >= 0) && (strcmp(signature1, "EFI PART") == 0))
retval += 1;
if ((retval >= 0) && (strcmp(signature2, "EFI PART") == 0))
retval += 2;
} else {
retval = -1;
} // if/else
myDisk->Close();
} else retval = -1;
return retval;
} // BasicMBRData::CheckForGPT()
// Blanks the 2nd (sector #1, numbered from 0) and last sectors of the disk,
// but only if GPT data are verified on the disk, and only for the sector(s)
// with GPT signatures.
// Returns 1 if operation completes successfully, 0 if not (returns 1 if
// no GPT data are found on the disk).
int BasicMBRData::BlankGPTData(void) {
int allOK = 1, err;
uint8_t blank[512];
memset(blank, 0, 512);
switch (CheckForGPT()) {
case -1:
allOK = 0;
break;
case 0:
break;
case 1:
if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
allOK = 0;
myDisk->Close();
} else allOK = 0;
break;
case 2:
if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
(myDisk->Write(blank, 512) == 512)))
allOK = 0;
myDisk->Close();
} else allOK = 0;
break;
case 3:
if ((myDisk != NULL) && (myDisk->OpenForWrite())) {
if (!((myDisk->Seek(1)) && (myDisk->Write(blank, 512) == 512)))
allOK = 0;
if (!((myDisk->Seek(myDisk->DiskSize(&err) - 1)) &&
(myDisk->Write(blank, 512) == 512)))
allOK = 0;
myDisk->Close();
} else allOK = 0;
break;
default:
break;
} // switch()
return allOK;
} // BasicMBRData::BlankGPTData
/*********************************************************************
* *
* Functions that set or get disk metadata (CHS geometry, disk size, *
* etc.) *
* *
*********************************************************************/
// Read the CHS geometry using OS calls, or if that fails, set to
// the most common value for big disks (255 heads, 63 sectors per
// track, & however many cylinders that computes to).
void BasicMBRData::ReadCHSGeom(void) {
int err;
numHeads = myDisk->GetNumHeads();
numSecspTrack = myDisk->GetNumSecsPerTrack();
diskSize = myDisk->DiskSize(&err);
blockSize = myDisk->GetBlockSize();
partitions[0].SetGeometry(numHeads, numSecspTrack, diskSize, blockSize);
} // BasicMBRData::ReadCHSGeom()
// Find the low and high used partition numbers (numbered from 0).
// Return value is the number of partitions found. Note that the
// *low and *high values are both set to 0 when no partitions
// are found, as well as when a single partition in the first
// position exists. Thus, the return value is the only way to
// tell when no partitions exist.
int BasicMBRData::GetPartRange(uint32_t *low, uint32_t *high) {
uint32_t i;
int numFound = 0;
*low = MAX_MBR_PARTS + 1; // code for "not found"
*high = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if (partitions[i].GetStartLBA() != UINT32_C(0)) { // it exists
*high = i; // since we're counting up, set the high value
// Set the low value only if it's not yet found...
if (*low == (MAX_MBR_PARTS + 1))
*low = i;
numFound++;
} // if
} // for
// Above will leave *low pointing to its "not found" value if no partitions
// are defined, so reset to 0 if this is the case....
if (*low == (MAX_MBR_PARTS + 1))
*low = 0;
return numFound;
} // GPTData::GetPartRange()
// Converts 64-bit LBA value to MBR-style CHS value. Returns 1 if conversion
// was within the range that can be expressed by CHS (including 0, for an
// empty partition), 0 if the value is outside that range, and -1 if chs is
// invalid.
int BasicMBRData::LBAtoCHS(uint64_t lba, uint8_t * chs) {
uint64_t cylinder, head, sector; // all numbered from 0
uint64_t remainder;
int retval = 1;
int done = 0;
if (chs != NULL) {
// Special case: In case of 0 LBA value, zero out CHS values....
if (lba == 0) {
chs[0] = chs[1] = chs[2] = UINT8_C(0);
done = 1;
} // if
// If LBA value is too large for CHS, max out CHS values....
if ((!done) && (lba >= ((uint64_t) numHeads * numSecspTrack * MAX_CYLINDERS))) {
chs[0] = 254;
chs[1] = chs[2] = 255;
done = 1;
retval = 0;
} // if
// If neither of the above applies, compute CHS values....
if (!done) {
cylinder = lba / (uint64_t) (numHeads * numSecspTrack);
remainder = lba - (cylinder * numHeads * numSecspTrack);
head = remainder / numSecspTrack;
remainder -= head * numSecspTrack;
sector = remainder;
if (head < numHeads)
chs[0] = (uint8_t) head;
else
retval = 0;
if (sector < numSecspTrack) {
chs[1] = (uint8_t) ((sector + 1) + (cylinder >> 8) * 64);
chs[2] = (uint8_t) (cylinder & UINT64_C(0xFF));
} else {
retval = 0;
} // if/else
} // if value is expressible and non-0
} else { // Invalid (NULL) chs pointer
retval = -1;
} // if CHS pointer valid
return (retval);
} // BasicMBRData::LBAtoCHS()
// Look for overlapping partitions. Also looks for a couple of non-error
// conditions that the user should be told about.
// Returns the number of problems found
int BasicMBRData::FindOverlaps(void) {
int i, j, numProbs = 0, numEE = 0, ProtectiveOnOne = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
for (j = i + 1; j < MAX_MBR_PARTS; j++) {
if ((partitions[i].GetInclusion() != NONE) && (partitions[j].GetInclusion() != NONE) &&
(partitions[i].DoTheyOverlap(partitions[j]))) {
numProbs++;
cout << "\nProblem: MBR partitions " << i + 1 << " and " << j + 1
<< " overlap!\n";
} // if
} // for (j...)
if (partitions[i].GetType() == 0xEE) {
numEE++;
if (partitions[i].GetStartLBA() == 1)
ProtectiveOnOne = 1;
} // if
} // for (i...)
if (numEE > 1)
cout << "\nCaution: More than one 0xEE MBR partition found. This can cause problems\n"
<< "in some OSes.\n";
if (!ProtectiveOnOne && (numEE > 0))
cout << "\nWarning: 0xEE partition doesn't start on sector 1. This can cause "
<< "problems\nin some OSes.\n";
return numProbs;
} // BasicMBRData::FindOverlaps()
// Returns the number of primary partitions, including the extended partition
// required to hold any logical partitions found.
int BasicMBRData::NumPrimaries(void) {
int i, numPrimaries = 0, logicalsFound = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if (partitions[i].GetLengthLBA() > 0) {
if (partitions[i].GetInclusion() == PRIMARY)
numPrimaries++;
if (partitions[i].GetInclusion() == LOGICAL)
logicalsFound = 1;
} // if
} // for
return (numPrimaries + logicalsFound);
} // BasicMBRData::NumPrimaries()
// Returns the number of logical partitions.
int BasicMBRData::NumLogicals(void) {
int i, numLogicals = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if (partitions[i].GetInclusion() == LOGICAL)
numLogicals++;
} // for
return numLogicals;
} // BasicMBRData::NumLogicals()
// Returns the number of partitions (primaries plus logicals), NOT including
// the extended partition required to house the logicals.
int BasicMBRData::CountParts(void) {
int i, num = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if ((partitions[i].GetInclusion() == LOGICAL) ||
(partitions[i].GetInclusion() == PRIMARY))
num++;
} // for
return num;
} // BasicMBRData::CountParts()
// Updates the canBeLogical and canBePrimary flags for all the partitions.
void BasicMBRData::UpdateCanBeLogical(void) {
int i, j, sectorBefore, numPrimaries, numLogicals, usedAsEBR;
uint64_t firstLogical, lastLogical, lStart, pStart;
numPrimaries = NumPrimaries();
numLogicals = NumLogicals();
firstLogical = FirstLogicalLBA() - 1;
lastLogical = LastLogicalLBA();
for (i = 0; i < MAX_MBR_PARTS; i++) {
usedAsEBR = (SectorUsedAs(partitions[i].GetLastLBA()) == EBR);
if (usedAsEBR) {
partitions[i].SetCanBeLogical(0);
partitions[i].SetCanBePrimary(0);
} else if (partitions[i].GetLengthLBA() > 0) {
// First determine if it can be logical....
sectorBefore = SectorUsedAs(partitions[i].GetStartLBA() - 1);
lStart = partitions[i].GetStartLBA(); // start of potential logical part.
if ((lastLogical > 0) &&
((sectorBefore == EBR) || (sectorBefore == NONE))) {
// Assume it can be logical, then search for primaries that make it
// not work and, if found, flag appropriately.
partitions[i].SetCanBeLogical(1);
for (j = 0; j < MAX_MBR_PARTS; j++) {
if ((i != j) && (partitions[j].GetInclusion() == PRIMARY)) {
pStart = partitions[j].GetStartLBA();
if (((pStart < lStart) && (firstLogical < pStart)) ||
((pStart > lStart) && (firstLogical > pStart))) {
partitions[i].SetCanBeLogical(0);
} // if/else
} // if
} // for
} else {
if ((sectorBefore != EBR) && (sectorBefore != NONE))
partitions[i].SetCanBeLogical(0);
else
partitions[i].SetCanBeLogical(lastLogical == 0); // can be logical only if no logicals already
} // if/else
// Now determine if it can be primary. Start by assuming it can be...
partitions[i].SetCanBePrimary(1);
if ((numPrimaries >= 4) && (partitions[i].GetInclusion() != PRIMARY)) {
partitions[i].SetCanBePrimary(0);
if ((partitions[i].GetInclusion() == LOGICAL) && (numLogicals == 1) &&
(numPrimaries == 4))
partitions[i].SetCanBePrimary(1);
} // if
if ((partitions[i].GetStartLBA() > (firstLogical + 1)) &&
(partitions[i].GetLastLBA() < lastLogical))
partitions[i].SetCanBePrimary(0);
} // else if
} // for
} // BasicMBRData::UpdateCanBeLogical()
// Returns the first sector occupied by any logical partition. Note that
// this does NOT include the logical partition's EBR! Returns UINT32_MAX
// if there are no logical partitions defined.
uint64_t BasicMBRData::FirstLogicalLBA(void) {
int i;
uint64_t firstFound = UINT32_MAX;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if ((partitions[i].GetInclusion() == LOGICAL) &&
(partitions[i].GetStartLBA() < firstFound)) {
firstFound = partitions[i].GetStartLBA();
} // if
} // for
return firstFound;
} // BasicMBRData::FirstLogicalLBA()
// Returns the last sector occupied by any logical partition, or 0 if
// there are no logical partitions defined.
uint64_t BasicMBRData::LastLogicalLBA(void) {
int i;
uint64_t lastFound = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if ((partitions[i].GetInclusion() == LOGICAL) &&
(partitions[i].GetLastLBA() > lastFound))
lastFound = partitions[i].GetLastLBA();
} // for
return lastFound;
} // BasicMBRData::LastLogicalLBA()
// Returns 1 if logical partitions are contiguous (have no primaries
// in their midst), or 0 if one or more primaries exist between
// logicals.
int BasicMBRData::AreLogicalsContiguous(void) {
int allOK = 1, i = 0;
uint64_t firstLogical, lastLogical;
firstLogical = FirstLogicalLBA() - 1; // subtract 1 for EBR
lastLogical = LastLogicalLBA();
if (lastLogical > 0) {
do {
if ((partitions[i].GetInclusion() == PRIMARY) &&
(partitions[i].GetStartLBA() >= firstLogical) &&
(partitions[i].GetStartLBA() <= lastLogical)) {
allOK = 0;
} // if
i++;
} while ((i < MAX_MBR_PARTS) && allOK);
} // if
return allOK;
} // BasicMBRData::AreLogicalsContiguous()
// Returns 1 if all partitions fit on the disk, given its size; 0 if any
// partition is too big.
int BasicMBRData::DoTheyFit(void) {
int i, allOK = 1;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if ((partitions[i].GetStartLBA() > diskSize) || (partitions[i].GetLastLBA() > diskSize)) {
allOK = 0;
} // if
} // for
return allOK;
} // BasicMBRData::DoTheyFit(void)
// Returns 1 if there's at least one free sector immediately preceding
// all partitions flagged as logical; 0 if any logical partition lacks
// this space.
int BasicMBRData::SpaceBeforeAllLogicals(void) {
int i = 0, allOK = 1;
do {
if ((partitions[i].GetStartLBA() > 0) && (partitions[i].GetInclusion() == LOGICAL)) {
allOK = allOK && (SectorUsedAs(partitions[i].GetStartLBA() - 1) == EBR);
} // if
i++;
} while (allOK && (i < MAX_MBR_PARTS));
return allOK;
} // BasicMBRData::SpaceBeforeAllLogicals()
// Returns 1 if the partitions describe a legal layout -- all logicals
// are contiguous and have at least one preceding empty sector,
// the number of primaries is under 4 (or under 3 if there are any
// logicals), there are no overlapping partitions, etc.
// Does NOT assume that primaries are numbered 1-4; uses the
// IsItPrimary() function of the MBRPart class to determine
// primary status. Also does NOT consider partition order; there
// can be gaps and it will still be considered legal.
int BasicMBRData::IsLegal(void) {
int allOK = 1;
allOK = (FindOverlaps() == 0);
allOK = (allOK && (NumPrimaries() <= 4));
allOK = (allOK && AreLogicalsContiguous());
allOK = (allOK && DoTheyFit());
allOK = (allOK && SpaceBeforeAllLogicals());
return allOK;
} // BasicMBRData::IsLegal()
// Returns 1 if the 0xEE partition in the protective/hybrid MBR is marked as
// active/bootable.
int BasicMBRData::IsEEActive(void) {
int i, IsActive = 0;
for (i = 0; i < MAX_MBR_PARTS; i++) {
if ((partitions[i].GetStatus() & 0x80) && (partitions[i].GetType() == 0xEE))
IsActive = 1;
}
return IsActive;
} // BasicMBRData::IsEEActive()
// Finds the next in-use partition, starting with start (will return start
// if it's in use). Returns -1 if no subsequent partition is in use.
int BasicMBRData::FindNextInUse(int start) {
if (start >= MAX_MBR_PARTS)
start = -1;
while ((start < MAX_MBR_PARTS) && (start >= 0) && (partitions[start].GetInclusion() == NONE))
start++;
if ((start < 0) || (start >= MAX_MBR_PARTS))
start = -1;
return start;
} // BasicMBRData::FindFirstLogical();
/*****************************************************
* *
* Functions to create, delete, or change partitions *
* *
*****************************************************/
// Empty all data. Meant mainly for calling by constructors, but it's also
// used by the hybrid MBR functions in the GPTData class.
void BasicMBRData::EmptyMBR(int clearBootloader) {
int i;
// Zero out the boot loader section, the disk signature, and the
// 2-byte nulls area only if requested to do so. (This is the
// default.)
if (clearBootloader == 1) {
EmptyBootloader();
} // if
// Blank out the partitions
for (i = 0; i < MAX_MBR_PARTS; i++) {
partitions[i].Empty();
} // for
MBRSignature = MBR_SIGNATURE;
state = mbr;
} // BasicMBRData::EmptyMBR()
// Blank out the boot loader area. Done with the initial MBR-to-GPT
// conversion, since MBR boot loaders don't understand GPT, and so
// need to be replaced....
void BasicMBRData::EmptyBootloader(void) {
int i;
for (i = 0; i < 440; i++)
code[i] = 0;
nulls = 0;
} // BasicMBRData::EmptyBootloader
// Create a partition of the specified number based on the passed
// partition. This function does *NO* error checking, so it's possible
// to seriously screw up a partition table using this function!
// Note: This function should NOT be used to create the 0xEE partition
// in a conventional GPT configuration, since that partition has
// specific size requirements that this function won't handle. It may
// be used for creating the 0xEE partition(s) in a hybrid MBR, though,
// since those toss the rulebook away anyhow....
void BasicMBRData::AddPart(int num, const MBRPart& newPart) {
partitions[num] = newPart;
} // BasicMBRData::AddPart()