forked from kubiko/partitioning_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptool.py
2506 lines (1925 loc) · 119 KB
/
ptool.py
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
#!/usr/bin/python
#===========================================================================
#Copyright (c) 2019, The Linux Foundation. All rights reserved.
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of The Linux Foundation nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
#WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
#BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
#OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
#IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ===========================================================================*/
import sys,os,getopt
import random,math
import re
import struct
from types import *
from time import sleep
if sys.version_info < (3,8):
sys.stdout.write("\n\nERROR: This script needs Python version 3.8 or greater, detected as ")
print(sys.version_info)
sys.exit() # error
from xml.etree import ElementTree as ET
#from elementtree.ElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
OutputFolder = ""
LastPartitionBeginsAt = 0
HashInstructions = {}
tempVar = 5
NumPhyPartitions = 0
PartitionCollection = [] # An array of Partition objects. Partition is a hash of information about partition
PhyPartition = {} # An array of PartitionCollection objects
MinSectorsNeeded = 0
# Ex. PhyPartition[0] holds the PartitionCollection that holds all the info for partitions in PHY partition 0
AvailablePartitions = {}
XMLFile = "module_common.py"
ExtendedPartitionBegins= 0
instructions = []
HashStruct = {}
StructPartitions = []
StructAdditionalFields = []
AllPartitions = {}
PARTITION_SYSTEM_GUID = 0x3BC93EC9A0004BBA11D2F81FC12A7328
PARTITION_MSFT_RESERVED_GUID= 0xAE1502F02DF97D814DB80B5CE3C9E316
PARTITION_BASIC_DATA_GUID = 0xC79926B7B668C0874433B9E5EBD0A0A2
SECTOR_SIZE_IN_BYTES = 512 # This can be over ridden in the partition.xml file
PrimaryGPT = [0]*17408 # This gets redefined later based on SECTOR_SIZE_IN_BYTES This is LBA 0 to 33 (34 sectors total) (start of disk)
BackupGPT = [0]*16896 # This gets redefined later based on SECTOR_SIZE_IN_BYTES This is LBA-33 to -1 (33 sectors total) (end of disk)
EmptyGPT = [0]*17408 # This gets redefined later based on SECTOR_SIZE_IN_BYTES This is LBA 0 to 33 (34 sectors total) (start of disk)
PrimaryGPTNumLBAs=len(PrimaryGPT)/SECTOR_SIZE_IN_BYTES
BackupGPTNumLBAs =len(BackupGPT)/SECTOR_SIZE_IN_BYTES
## Note that these HashInstructions are updated by the XML file
HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB'] = 64*1024
HashInstructions['GROW_LAST_PARTITION_TO_FILL_DISK'] = True
HashInstructions['DISK_SIGNATURE'] = 0x0
MBR = [0]*SECTOR_SIZE_IN_BYTES
EBR = [0]*SECTOR_SIZE_IN_BYTES
hash_w = [{'start_sector':0,'num_sectors':(HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB']*1024/SECTOR_SIZE_IN_BYTES),
'end_sector':(HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB']*1024/SECTOR_SIZE_IN_BYTES)-1,'physical_partition_number':0,'boundary_num':0,'num_boundaries_covered':1}]
NumWPregions = 0
def ShowPartitionExample():
print("Your \"partition.xml\" file needs to look like something like this below")
print("\t(i.e. notice the *multiple* physical_partition tags)\n")
print("<!-- This is physical partition 0 -->")
print("<physical_partition>")
print(" <partition label=\"SBL1\" size_in_kb=\"100\" type=\"DEA0BA2C-CBDD-4805-B4F9-F428251C3E98\" filename=\"sbl1.mbn\"/>")
print("</physical_partition>")
print(" ")
print("<!-- This is physical partition 1 -->")
print("<physical_partition>")
print(" <partition label=\"SBL2\" size_in_kb=\"200\" type=\"8C6B52AD-8A9E-4398-AD09-AE916E53AE2D\" filename=\"sbl2.mbn\"/>")
print("</physical_partition>")
def ConvertKBtoSectors(x):
## 1KB / SECTOR_SIZE_IN_BYTES normally means return 2 (i.e. with SECTOR_SIZE_IN_BYTES=512)
## 2KB / SECTOR_SIZE_IN_BYTES normally means return 4 (i.e. with SECTOR_SIZE_IN_BYTES=512)
return int((x*1024)/SECTOR_SIZE_IN_BYTES)
def UpdatePatch(StartSector,ByteOffset,PHYPartition,size_in_bytes,szvalue,szfilename,szwhat):
global PatchesXML
SubElement(PatchesXML, 'patch', {'start_sector':StartSector, 'byte_offset':ByteOffset,
'physical_partition_number':str(PHYPartition), 'size_in_bytes':str(size_in_bytes),
'value':szvalue, 'filename':szfilename, 'SECTOR_SIZE_IN_BYTES':str(SECTOR_SIZE_IN_BYTES), 'what':szwhat })
def UpdateRawProgram(RawProgramXML, StartSector, size_in_KB, PHYPartition, file_sector_offset, num_partition_sectors, filename, sparse, label,readbackverify='false', partofsingleimage='false'):
if StartSector<0:
szStartSector = "NUM_DISK_SECTORS%d." % StartSector ## as in NUM_DISK_SECTORS-33 since %d=-33
szStartByte = "(%d*NUM_DISK_SECTORS)%d." % (SECTOR_SIZE_IN_BYTES,StartSector*SECTOR_SIZE_IN_BYTES)
else:
#print "\nTo be here means StartSector>0"
#print "UpdateRawProgram StartSector=",StartSector
#print "StartSector=",type(StartSector)
#print "-----------------------------------------"
szStartByte = str(hex(StartSector*SECTOR_SIZE_IN_BYTES))
szStartSector = str(StartSector)
#import pdb; pdb.set_trace()
if num_partition_sectors<=0:
#print "*"*78
#print "WARNING: num_partition_sectors is %d for '%s' PHYPartition=%d, setting it to 0" % (num_partition_sectors,label,PHYPartition)
#print "\tThis can happen if you only have 1 partition and thus it is the grow partition"
num_partition_sectors = 0
size_in_KB = 0
if erasefirst:
if label!="cdt":
SubElement(RawProgramXML, 'erase', {'start_sector':szStartSector, 'physical_partition_number':str(PHYPartition),
'num_partition_sectors':str(num_partition_sectors), 'filename':filename,
'SECTOR_SIZE_IN_BYTES':str(SECTOR_SIZE_IN_BYTES) })
SubElement(RawProgramXML, 'program', {'start_sector':szStartSector, 'size_in_KB':str(size_in_KB), 'physical_partition_number':str(PHYPartition), 'partofsingleimage':partofsingleimage,
'file_sector_offset':str(file_sector_offset), 'num_partition_sectors':str(num_partition_sectors), 'readbackverify':readbackverify,
'filename':filename, 'sparse':sparse, 'start_byte_hex':szStartByte, 'SECTOR_SIZE_IN_BYTES':str(SECTOR_SIZE_IN_BYTES), 'label':label })
#iter = RawProgramXML.getiterator()
#for element in iter:
# print "\nElement:" , element.tag, " : ", element.text # thins like image,primary,extended etc
# if element.keys():
# print "\tAttributes:"
# for name, value in element.items():
# print "\t\tName: '%s'=>'%s' " % (name,value)
#import pdb; pdb.set_trace()
def PrintBigWarning(sz):
print("\t _ ")
print("\t (_) ")
print("\t__ ____ _ _ __ _ __ _ _ __ __ _ ")
print("\t\\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` |")
print("\t \\ V V / (_| | | | | | | | | | | (_| |")
print("\t \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, |")
print("\t __/ |")
print("\t |___/ \n")
if len(sz)>0:
print(sz)
def ValidGUIDForm(GUID):
if type(GUID) is not str:
GUID = str(GUID)
print("Testing if GUID=",GUID)
m = re.search("0x([a-fA-F\d]{32})$", GUID) #0xC79926B7B668C0874433B9E5EBD0A0A2
if type(m) is not type(None):
return True
m = re.search("([a-fA-F\d]{8})-([a-fA-F\d]{4})-([a-fA-F\d]{4})-([a-fA-F\d]{2})([a-fA-F\d]{2})-([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})", GUID)
if type(m) is not type(None):
return True
print("GUID does not match regular expression")
return False
def ValidateTYPE(Type):
# for type I must support the original "4C" and if they put "0x4C"
if type(Type) is int:
if Type>=0 and Type<=255:
return Type
if type(Type) is not str:
Type = str(Type)
m = re.search("^(0x)?([a-fA-F\d][a-fA-F\d]?)$", Type)
if type(m) is type(None):
print("\tWARNING: Type \"%s\" is not in the form 0x4C" % Type)
sys.exit(1)
else:
#print m.group(2)
#print "---------"
#print "\tType is \"0x%X\"" % Type
return int(m.group(2),16)
def ValidateGUID(GUID):
if type(GUID) is not str:
GUID = str(GUID)
print("Looking to validate GUID=",GUID)
m = re.search("0x([a-fA-F\d]{32})$", GUID) #0xC79926B7B668C0874433B9E5EBD0A0A2
if type(m) is not type(None):
tempGUID = int(m.group(1),16)
print("\tGUID \"%s\"" % GUID)
if tempGUID == PARTITION_SYSTEM_GUID:
print("\tPARTITION_SYSTEM_GUID detected\n")
elif tempGUID == PARTITION_MSFT_RESERVED_GUID:
print("\tPARTITION_MSFT_RESERVED_GUID detected\n")
elif tempGUID == PARTITION_BASIC_DATA_GUID:
print("\tPARTITION_BASIC_DATA_GUID detected\n")
else:
print("\tUNKNOWN PARTITION_GUID detected\n")
return tempGUID
else:
#ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 --> #0x C7 99 26 B7 B6 68 C087 4433 B9E5 EBD0A0A2
m = re.search("([a-fA-F\d]{8})-([a-fA-F\d]{4})-([a-fA-F\d]{4})-([a-fA-F\d]{2})([a-fA-F\d]{2})-([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})([a-fA-F\d]{2})", GUID)
if type(m) is not type(None):
print("Found more advanced type")
tempGUID = (int(m.group(4),16)<<64) | (int(m.group(3),16)<<48) | (int(m.group(2),16)<<32) | int(m.group(1),16)
tempGUID|= (int(m.group(8),16)<<96) | (int(m.group(7),16)<<88) | (int(m.group(6),16)<<80) | (int(m.group(5),16)<<72)
tempGUID|= (int(m.group(11),16)<<120)| (int(m.group(10),16)<<112)| (int(m.group(9),16)<<104)
print("** CONVERTED GUID \"%s\" is FOUND --> 0x%X" % (GUID,tempGUID))
return tempGUID
else:
print("\nWARNING: "+"-"*78)
print("*"*78)
print("WARNING: GUID \"%s\" is not in the form ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" % GUID)
print("*"*78)
print("WARNING"+"-"*78+"\n")
print("Converted to PARTITION_BASIC_DATA_GUID (0xC79926B7B668C0874433B9E5EBD0A0A2)\n")
return PARTITION_BASIC_DATA_GUID
def EnsureDirectoryExists(filename):
dir = os.path.dirname(filename)
try:
os.stat(dir)
except:
os.makedirs(dir)
def WriteGPT(GPTMAIN, GPTBACKUP, GPTEMPTY):
global opfile,PrimaryGPT,BackupGPT,GPTBOTH
#for b in PrimaryGPT:
# opfile.write(struct.pack("B", b))
#for b in BackupGPT:
# opfile.write(struct.pack("B", b))
ofile = open(GPTMAIN, "wb")
for b in PrimaryGPT:
ofile.write(struct.pack("B", b))
ofile.close()
print("\nCreated \"%s\"\t\t\t<-- Primary GPT partition tables + protective MBR" % GPTMAIN)
ofile = open(GPTBACKUP, "wb")
for b in BackupGPT:
ofile.write(struct.pack("B", b))
ofile.close()
print("Created \"%s\"\t\t<-- Backup GPT partition tables" % GPTBACKUP)
ofile = open(GPTBOTH, "wb")
for b in PrimaryGPT:
ofile.write(struct.pack("B", b))
for b in BackupGPT:
ofile.write(struct.pack("B", b))
ofile.close()
print("Created \"%s\" \t\t<-- you can run 'perl parseGPT.pl %s'" % (GPTBOTH,GPTBOTH))
## EmptyGPT is just all 0's, let's fill in the correct data
FillInEmptyGPT()
ofile = open(GPTEMPTY, "wb")
for b in EmptyGPT:
ofile.write(struct.pack("B", b))
ofile.close()
print("Created \"%s\"\t\t<-- Empty GPT partition table, use to force EDL mode (very useful)" % GPTEMPTY)
def FillInEmptyGPT():
global EmptyGPT
i=SECTOR_SIZE_IN_BYTES+16
EmptyGPT[0:i] = PrimaryGPT[0:i] ## this copies up to EFI PART, REVISION and HEADER SIZE
EmptyGPT[i:i+4] = [0xD6, 0x51, 0x5B, 0x44] # CRC32
i+=8
EmptyGPT[i:i+1] = [0x01] # Current LBA
i+=16
EmptyGPT[i:i+1] = [0x22] # First useable LBA
i+=16
EmptyGPT[i:i+16] = [0x32, 0x1B, 0x10, 0x98, 0xE2, 0xBB, 0xF2, 0x4B, 0xA0, 0x6E, 0x2B, 0xB3, 0x3D, 0x00, 0x0C, 0x20] # DISK GUID
i+=16
EmptyGPT[i:i+1] = [0x02] # Starting LBA
i+=8
EmptyGPT[i:i+16] = [0x04, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x87, 0x5D, 0x3C, 0x00, 0x00, 0x00, 0x00] # Num Entries, Size of Array, CRC
i=2*SECTOR_SIZE_IN_BYTES+16
EmptyGPT[i:i+16] = [0x6B, 0xCA, 0x1F, 0xEF, 0x31, 0x26, 0xC9, 0x95, 0x5C, 0x13, 0x61, 0xEB, 0x3F, 0xCF, 0x87, 0xF9] # unique GUID
i+=16
EmptyGPT[i:i+1] = [0x22] # first LBA
i+=8
EmptyGPT[i:i+2] = [0x21, 0x02] # last LBA
i+=16
EmptyGPT[i:i+9] = [0x65, 0x00, 0x6D, 0x00, 0x70, 0x00, 0x74, 0x00, 0x79] # unicode "empty" partition name
def UpdatePrimaryGPT(value,length,i):
global PrimaryGPT
for b in range(length):
PrimaryGPT[i] = ((int(value)>>(b*8)) & 0xFF) ; i+=1
return i
def UpdateBackupGPT(value,length,i):
global BackupGPT
for b in range(length):
BackupGPT[int(i)] = ((int(value)>>(b*8)) & 0xFF) ; i+=1
return i
def ShowBackupGPT(sector):
global BackupGPT
print("Sector: %d" % sector)
for j in range(32):
for i in range(16):
sys.stdout.write("%.2X " % BackupGPT[i+j*16+sector*SECTOR_SIZE_IN_BYTES])
print(" ")
print(" ")
def CreateFileOfZeros(filename,num_sectors):
try:
opfile = open(filename, "w+b")
except Exception as x:
print("ERROR: Could not create '%s', cwd=%s" % (filename,os.getcwd() ))
print("REASON: %s" % (x))
sys.exit(1)
temp = [0]*(int(SECTOR_SIZE_IN_BYTES*num_sectors))
zeros = struct.pack("%iB"%(SECTOR_SIZE_IN_BYTES*num_sectors),*temp)
try:
opfile.write(zeros)
except Exception as x:
print("ERROR: Could not write zeros to '%s'\nREASON: %s" % (filename,x))
sys.exit(1)
try:
opfile.close()
except Exception as x:
print("\tWARNING: Could not close %s" % filename)
print("REASON: %s" % (x))
print("Created \"%s\"\t\t<-- full of binary zeros - used by \"wipe\" rawprogram files" % filename)
def CreateErasingRawProgramFiles():
CreateFileOfZeros("zeros_1sector.bin",1)
CreateFileOfZeros("zeros_%dsectors.bin" % BackupGPTNumLBAs,BackupGPTNumLBAs)
##import pdb; pdb.set_trace()
for i in range(8): # PHY partitions 0 to 7 exist (with 4,5,6,7 as GPPs)
if i==3:
continue # no such PHY partition as of Feb 23, 2012
temp = Element('data')
temp.append(Comment('NOTE: This is an ** Autogenerated file **'))
temp.append(Comment('NOTE: Sector size is %ibytes'%SECTOR_SIZE_IN_BYTES))
UpdateRawProgram(temp,0, 0.5, i, 0, 1, "zeros_33sectors.bin", "false", "Overwrite MBR sector")
UpdateRawProgram(temp,1, BackupGPTNumLBAs*SECTOR_SIZE_IN_BYTES/1024.0, i, 0, BackupGPTNumLBAs, "zeros_%dsectors.bin" % BackupGPTNumLBAs, "false", "Overwrite Primary GPT Sectors")
UpdateRawProgram(temp,-BackupGPTNumLBAs, BackupGPTNumLBAs*SECTOR_SIZE_IN_BYTES/1024.0, i, 0, BackupGPTNumLBAs, "zeros_%dsectors.bin" % BackupGPTNumLBAs, "false", "Overwrite Backup GPT Sectors")
RAW_PROGRAM = '%swipe_rawprogram_PHY%d.xml' % (OutputFolder,i)
opfile = open(RAW_PROGRAM, "w")
opfile.write( prettify(temp) )
opfile.close()
print("Created \"%s\"\t<-- Used to *wipe/erase* partition information" % RAW_PROGRAM)
NumPartitions = 0
SizeOfPartitionArray= 0
def CreateGPTPartitionTable(PhysicalPartitionNumber,UserProvided=False):
global opfile,PhyPartition,PrimaryGPT,BackupGPT,EmptyGPT,RawProgramXML, GPTMAIN, GPTBACKUP, GPTBOTH, RAW_PROGRAM, PATCHES, PrimaryGPTNumLBAs, BackupGPTNumLBAs
print("\n\nMaking GUID Partitioning Table (GPT)")
#PrintBanner("instructions")
#print "\nGoing through partitions listed in XML file"
## Step 2. Move through partitions resizing as needed based on WRITE_PROTECT_BOUNDARY_IN_KB
#print "\n\n--------------------------------------------------------"
#print "This is the order of the partitions"
# I most likely need to resize at least one partition below to the WRITE_PROTECT_BOUNDARY_IN_KB boundary
#for k in range(len(PhyPartition)):
k = PhysicalPartitionNumber
GPTMAIN = '%sgpt_main%d.bin' % (OutputFolder,k)
GPTEMPTY = '%sgpt_empty%d.bin' % (OutputFolder,k)
GPTBACKUP = '%sgpt_backup%d.bin' % (OutputFolder,k)
GPTBOTH = '%sgpt_both%d.bin' % (OutputFolder,k)
RAW_PROGRAM = '%srawprogram%d.xml' % (OutputFolder,k)
RAW_PROGRAM_WIPE_PARTITIONS = '%srawprogram%d_WIPE_PARTITIONS.xml'% (OutputFolder,k)
RAW_PROGRAM_BLANK_GPT = '%srawprogram%d_BLANK_GPT.xml'% (OutputFolder,k)
PATCHES = '%spatch%i.xml' % (OutputFolder,k)
#for k in range(1):
#PrimaryGPT = [0]*(34*SECTOR_SIZE_IN_BYTES) # This is LBA 0 to 33 (34 sectors total) (start of disk)
#BackupGPT = [0]*(33*SECTOR_SIZE_IN_BYTES) # This is LBA-33 to -1 (33 sectors total) (end of disk)
if SECTOR_SIZE_IN_BYTES==4096:
PrimaryGPT = [0]*(1*SECTOR_SIZE_IN_BYTES+1*SECTOR_SIZE_IN_BYTES+4*SECTOR_SIZE_IN_BYTES)
BackupGPT = [0]*(1*SECTOR_SIZE_IN_BYTES+4*SECTOR_SIZE_IN_BYTES)
EmptyGPT = [0]*(1*SECTOR_SIZE_IN_BYTES+1*SECTOR_SIZE_IN_BYTES+4*SECTOR_SIZE_IN_BYTES)
else:
PrimaryGPT = [0]*(34*SECTOR_SIZE_IN_BYTES) # This is LBA 0 to 33 (34 sectors total) (start of disk)
BackupGPT = [0]*(33*SECTOR_SIZE_IN_BYTES) # This is LBA-33 to -1 (33 sectors total) (end of disk)
EmptyGPT = [0]*(34*SECTOR_SIZE_IN_BYTES) # This is LBA 0 to 33 (34 sectors total) (start of disk)
## ---------------------------------------------------------------------------------
## Step 2. Move through xml definition and figure out partitions sizes
## ---------------------------------------------------------------------------------
PrimaryGPTNumLBAs=len(PrimaryGPT)/SECTOR_SIZE_IN_BYTES
BackupGPTNumLBAs =len(BackupGPT)/SECTOR_SIZE_IN_BYTES
i = 2*SECTOR_SIZE_IN_BYTES ## partition arrays begin here
FirstLBA = HashInstructions['FIRST_SECTOR_OF_FIRST_PARTITION'] # PrimaryGPTNumLBAs
LastLBA = FirstLBA ## Make these equal at first
if HashInstructions['WRITE_PROTECT_GPT_PARTITION_TABLE'] is True:
UpdateWPhash(FirstLBA, 0) # make sure 1st write protect boundary is setup correctly
#print "len(PhyPartition)=%d and k=%d" % (len(PhyPartition),k)
if(k>=len(PhyPartition)):
if UserProvided==True:
print("\nERROR: PHY Partition %i of %i not found" % (k,len(PhyPartition)))
print("\nERROR: PHY Partition %i of %i not found\n\n" % (k,len(PhyPartition)))
ShowPartitionExample()
sys.exit()
else:
print("\nERROR: PHY Partition %i of %i not found\n\n" % (k,len(PhyPartition)))
return ## Automatically trying to do 0 to 7, and some don't exist, which is to be expected
SectorsTillNextBoundary = 0
print("\n\nOn PHY Partition %d that has %d partitions" % (k,len(PhyPartition[k])))
for j in range(len(PhyPartition[k])):
#print "\nPartition name='%s' (readonly=%s)" % (PhyPartition[k][j]['label'], PhyPartition[k][j]['readonly'])
#print "\tat sector location %d (%d KB or %.2f MB) and LastLBA=%d" % (FirstLBA,FirstLBA/2,FirstLBA/2048,LastLBA)
#print "%d of %d with label %s" %(j,len(PhyPartition[k]),PhyPartition[k][j]['label'])
print("\n"+"="*78)
print(" _ (\"-._ (\"-._ (\"-._ (\"-._ (\"-._ (\"-._ (\"-._ (\"-._ (\"-.")
print(" ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )")
print(" (_,-\" (_,-\" (_,-\" (_,-\" (_,-\" (_,-\" (_,-\" (_,-\" (_,-\"")
print("="*78)
PhyPartition[k][j]['size_in_kb'] = int(PhyPartition[k][j]['size_in_kb'])
print("\n\n%d of %d \"%s\" (readonly=%s) and size=%dKB (%dMB) (%i sectors with %i bytes/sector)" %(j+1,len(PhyPartition[k]),PhyPartition[k][j]['label'],PhyPartition[k][j]['readonly'],PhyPartition[k][j]['size_in_kb'],PhyPartition[k][j]['size_in_kb']/1024,ConvertKBtoSectors(PhyPartition[k][j]['size_in_kb']),SECTOR_SIZE_IN_BYTES))
if (PhyPartition[k][j]['size_in_kb']*1024)%SECTOR_SIZE_IN_BYTES>0:
## Have a remainder, need to round up to next full sector
TempResult = (PhyPartition[k][j]['size_in_kb']*1024)/SECTOR_SIZE_IN_BYTES
TempResult +=1
PhyPartition[k][j]['size_in_kb'] = (TempResult * SECTOR_SIZE_IN_BYTES)/1024
##import pdb; pdb.set_trace() ## verifying sizes
if HashInstructions['PERFORMANCE_BOUNDARY_IN_KB']>0 and HashInstructions['ALIGN_PARTITIONS_TO_PERFORMANCE_BOUNDARY'] is False:
PrintBigWarning("WARNING: HashInstructions['PERFORMANCE_BOUNDARY_IN_KB'] is %i KB\n\tbut HashInstructions['ALIGN_PARTITIONS_TO_PERFORMANCE_BOUNDARY'] is FALSE!!\n\n" % HashInstructions['PERFORMANCE_BOUNDARY_IN_KB'])
PrintBigWarning("WARNING: This means partitions will *NOT* be aligned to a HashInstructions['PERFORMANCE_BOUNDARY_IN_KB'] of %i KB !!\n\n" % HashInstructions['PERFORMANCE_BOUNDARY_IN_KB'])
print("To correct this, partition.xml should look like this\n")
print("\t<parser_instructions>")
print("\t\tPERFORMANCE_BOUNDARY_IN_KB = %i" % Partition['PERFORMANCE_BOUNDARY_IN_KB'])
print("\t\tALIGN_PARTITIONS_TO_PERFORMANCE_BOUNDARY=true")
print("\t</parser_instructions>\n\n")
if HashInstructions['ALIGN_PARTITIONS_TO_PERFORMANCE_BOUNDARY'] is True:
## to be here means this partition *must* be on an ALIGN boundary
print("\tAlignment is to %iKB" % PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB'])
SectorsTillNextBoundary = ReturnNumSectorsTillBoundary(FirstLBA,PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']) ## hi
if SectorsTillNextBoundary>0:
print("\tSectorsTillNextBoundary=%d, FirstLBA=%d it needs to be moved to be aligned to %d" % (SectorsTillNextBoundary,FirstLBA,FirstLBA + SectorsTillNextBoundary))
##print "\tPhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']=",PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']
FirstLBA += SectorsTillNextBoundary
else:
if PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']>0:
print("\tThis partition is *NOT* aligned to a performance boundary\n")
if HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB']>0:
SectorsTillNextBoundary = ReturnNumSectorsTillBoundary(FirstLBA,HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB'])
if PhyPartition[k][j]['readonly']=="true":
## to be here means this partition is read-only, so see if we need to move the start
if FirstLBA <= hash_w[NumWPregions]["end_sector"]:
print("\tWe *don't* need to move FirstLBA (%d) since it's covered by the end of the current WP region (%d)" % (FirstLBA,hash_w[NumWPregions]["end_sector"]))
pass
else:
print("\tFirstLBA (%d) is *not* covered by the end of the WP region (%d),\n\tit needs to be moved to be aligned to %d" % (FirstLBA,hash_w[NumWPregions]["end_sector"],FirstLBA + SectorsTillNextBoundary))
FirstLBA += SectorsTillNextBoundary
else:
print("\n\tThis partition is *NOT* readonly")
## to be here means this partition is writeable, so see if we need to move the start
if FirstLBA <= hash_w[NumWPregions]["end_sector"]:
print("\tWe *need* to move FirstLBA (%d) since it's covered by the end of the current WP region (%d)" % (FirstLBA,hash_w[NumWPregions]["end_sector"]))
print("\nhash_w[NumWPregions]['end_sector']=%i" % hash_w[NumWPregions]["end_sector"]);
print("FirstLBA=%i\n" %FirstLBA);
FirstLBA += SectorsTillNextBoundary
print("\tFirstLBA is now %d" % (FirstLBA))
else:
#print "Great, We *don't* need to move FirstLBA (%d) since it's *not* covered by the end of the current WP region (%d)" % (FirstLBA,hash_w[NumWPregions]["end_sector"])
pass
if (j+1) == len(PhyPartition[k]):
print("\nTHIS IS THE *LAST* PARTITION")
if HashInstructions['GROW_LAST_PARTITION_TO_FILL_DISK']==True:
print("\nMeans patching instructions go here")
PhyPartition[k][j]['size_in_kb'] = 0 # infinite huge
print("PhyPartition[k][j]['size_in_kb'] set to 0")
SectorsRemaining = BackupGPTNumLBAs
print("LastLBA=",LastLBA)
print("FirstLBA=",FirstLBA)
# gpt patch - size of last partition ################################################
#StartSector = 2*512+40+j*128 ## i.e. skip sector 0 and 1, then it's offset
#ByteOffset = str(StartSector%512)
#StartSector = str(int(StartSector / 512))
StartSector = 40+j*128 ## i.e. skip sector 0 and 1, then it's offset
ByteOffset = str(StartSector%SECTOR_SIZE_IN_BYTES)
StartSector = str(2+int(StartSector / SECTOR_SIZE_IN_BYTES))
BackupStartSector = 40+j*128
ByteOffset = str(BackupStartSector%SECTOR_SIZE_IN_BYTES)
BackupStartSector = int(BackupStartSector / SECTOR_SIZE_IN_BYTES)
## gpt patch - main gpt partition array
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,os.path.basename(GPTMAIN),"Update last partition %d '%s' with actual size in Primary Header." % ((j+1),PhyPartition[k][j]['label']))
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,"DISK", "Update last partition %d '%s' with actual size in Primary Header." % ((j+1),PhyPartition[k][j]['label']))
## gpt patch - backup gpt partition array
UpdatePatch(str(BackupStartSector), ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,os.path.basename(GPTBACKUP),"Update last partition %d '%s' with actual size in Backup Header." % ((j+1),PhyPartition[k][j]['label']))
UpdatePatch("NUM_DISK_SECTORS-%d." % (BackupGPTNumLBAs-BackupStartSector),ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,"DISK", "Update last partition %d '%s' with actual size in Backup Header." % ((j+1),PhyPartition[k][j]['label']))
LastLBA = FirstLBA + ConvertKBtoSectors( PhyPartition[k][j]['size_in_kb'] ) ## increase by num sectors, LastLBA inclusive, so add 1 for size
LastLBA -= 1 # inclusive, meaning 0 to 3 is 4 sectors
#import pdb; pdb.set_trace()
print("\n\tAt sector location %d with size %.2f MB (%d sectors) and LastLBA=%d (0x%X)" % (FirstLBA,PhyPartition[k][j]['size_in_kb']/1024.0,ConvertKBtoSectors(PhyPartition[k][j]['size_in_kb']),LastLBA,LastLBA))
if HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB']>0:
AlignedRemainder = FirstLBA % HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB'];
if AlignedRemainder==0:
print("\tWPB: This partition is ** ALIGNED ** to a %i KB boundary at sector %i (boundary %i)" % (HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB'],FirstLBA,FirstLBA/(ConvertKBtoSectors(HashInstructions['WRITE_PROTECT_BOUNDARY_IN_KB']))))
if PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']>0:
AlignedRemainder = FirstLBA % PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB'];
if AlignedRemainder==0:
print("\t"+"-"*78)
print("\tPERF: This partition is ** ALIGNED ** to a %i KB boundary at sector %i (boundary %i)" % (PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB'],FirstLBA,FirstLBA/(ConvertKBtoSectors(PhyPartition[k][j]['PERFORMANCE_BOUNDARY_IN_KB']))))
print("\t"+"-"*78)
if PhyPartition[k][j]['readonly']=="true":
UpdateWPhash(FirstLBA, ConvertKBtoSectors(PhyPartition[k][j]['size_in_kb']))
#print Partition.keys()
#print Partition.has_key("label")
#print "\tsize %i kB (%.2f MB)" % (PhyPartition[k][j]['size_in_kb'], PhyPartition[k][j]['size_in_kb']/1024)
PartitionTypeGUID = PhyPartition[k][j]['type']
print("\nPartitionTypeGUID\t0x%X" % PartitionTypeGUID)
# If the partition is a multiple of 4, it must start on an LBA boundary of size SECTOR_SIZE_IN_BYTES
# if j%4==0 :
# # To be here means the partition number is a multiple of 4, so it must start on
# # an LBA boundary, i.e. LBA2, LBA3 etc.
# if i%SECTOR_SIZE_IN_BYTES > 0:
# print "\tWARNING: Location is %i, need to add %i to offset" % (i, SECTOR_SIZE_IN_BYTES-(i%SECTOR_SIZE_IN_BYTES))
# i += (SECTOR_SIZE_IN_BYTES-(i%SECTOR_SIZE_IN_BYTES))
#
# print "\n==============================================================================="
# print "This partition array entry (%i) is a multiple of 4 and must begin on a boundary of size %i bytes" % (j,SECTOR_SIZE_IN_BYTES)
# print "This partition array entry is at LBA%i, absolute byte address %i (0x%X)" % (i/SECTOR_SIZE_IN_BYTES,i,i)
# print "NOTE: LBA0 is protective MBR, LBA1 is Primary GPT Header, LBA2 beginning of Partition Array"
# print "===============================================================================\n"
for b in range(16):
PrimaryGPT[i] = ((PartitionTypeGUID>>(b*8)) & 0xFF) ; i+=1
# Unique Partition GUID
if sequentialguid == 1:
UniquePartitionGUID = j+1
else:
if PhyPartition[k][j]['uguid'] != "false":
UniquePartitionGUID = PhyPartition[k][j]['uguid']
else:
UniquePartitionGUID = random.randint(0,2**(128))
print("UniquePartitionGUID\t0x%X" % UniquePartitionGUID)
# This HACK section is for verifying with GPARTED, allowing me to put in
# whatever uniqueGUID that program came up with
#if j==0:
# UniquePartitionGUID = 0x373C17CF53BC7FB149B85A927ED24483
#elif j==1:
# UniquePartitionGUID = 0x1D3C4663FC172F904EC7E0C7A8CF84EC
#elif j==2:
# UniquePartitionGUID = 0x04A9B2AAEF96DAAE465F429D0EF5C6E2
#else:
# UniquePartitionGUID = 0x4D82D027725FD3AE46AF1C5A28944977
for b in range(16):
PrimaryGPT[i] = ((UniquePartitionGUID>>(b*8)) & 0xFF) ; i+=1
# First LBA
for b in range(8):
PrimaryGPT[i] = ((FirstLBA>>(b*8)) & 0xFF) ; i+=1
# Last LBA
for b in range(8):
PrimaryGPT[i] = ((LastLBA>>(b*8)) & 0xFF) ; i+=1
print("**** FirstLBA=%d and LastLBA=%d and size is %i sectors" % (FirstLBA,LastLBA,LastLBA-FirstLBA+1))
# Attributes
Attributes = 0x0
#import pdb; pdb.set_trace()
if PhyPartition[k][j]['readonly']=="true":
Attributes |= 1<<60 ## Bit 60 is read only
if PhyPartition[k][j]['hidden']=="true":
Attributes |= 1<<62
if PhyPartition[k][j]['dontautomount']=="true":
Attributes |= 1<<63
if PhyPartition[k][j]['uc20_install_created']=="true":
Attributes |= 1<<59
if PhyPartition[k][j]['system']=="true":
Attributes |= 1<<0
if PhyPartition[k][j]['tries_remaining']>0:
Attributes |= PhyPartition[k][j]['tries_remaining']<<52
if PhyPartition[k][j]['priority']>0:
Attributes |= PhyPartition[k][j]['priority']<<48
print("Attributes\t\t0x%X" % Attributes)
##import pdb; pdb.set_trace()
for b in range(8):
PrimaryGPT[i] = ((Attributes>>(b*8)) & 0xFF) ; i+=1
if len(PhyPartition[k][j]['label'])>36:
print("Label %s is more than 36 characters, therefore it's truncated" % PhyPartition[k][j]['label'])
PhyPartition[k][j]['label'] = PhyPartition[k][j]['label'][0:36]
#print "LABEL %s and i=%i" % (PhyPartition[k][j]['label'],i)
# Partition Name
for b in PhyPartition[k][j]['label']:
PrimaryGPT[i] = ord(b) ; i+=1
PrimaryGPT[i] = 0x00 ; i+=1
for b in range(36-len(PhyPartition[k][j]['label'])):
PrimaryGPT[i] = 0x00 ; i+=1
PrimaryGPT[i] = 0x00 ; i+=1
#for b in range(2):
# PrimaryGPT[i] = 0x00 ; i+=1
#for b in range(70):
# PrimaryGPT[i] = 0x00 ; i+=1
##FileToProgram = ""
##FileOffset = 0
PartitionLabel = ""
## Default for each partition is no file
FileToProgram = [""]
FileOffset = [0]
FilePartitionOffset = [0]
FileAppsbin = ["false"]
FileSparse = ["false"]
if 'filename' in PhyPartition[k][j]:
##print "filename exists"
#print PhyPartition[k][j]['filename']
#print FileToProgram[0]
# These are all the default values that should be there, including an empty string possibly for filename
FileToProgram[0] = PhyPartition[k][j]['filename'][0]
FileOffset[0] = PhyPartition[k][j]['fileoffset'][0]
FilePartitionOffset[0] = PhyPartition[k][j]['filepartitionoffset'][0]
FileAppsbin[0] = PhyPartition[k][j]['appsbin'][0]
FileSparse[0] = PhyPartition[k][j]['sparse'][0]
for z in range(1,len(PhyPartition[k][j]['filename'])):
FileToProgram.append( PhyPartition[k][j]['filename'][z] )
FileOffset.append( PhyPartition[k][j]['fileoffset'][z] )
FilePartitionOffset.append( PhyPartition[k][j]['filepartitionoffset'][z] )
FileAppsbin.append( PhyPartition[k][j]['appsbin'][z] )
FileSparse.append( PhyPartition[k][j]['sparse'][z] )
#print PhyPartition[k][j]['fileoffset']
#for z in range(len(FileToProgram)):
# print "FileToProgram[",z,"]=",FileToProgram[z]
# print "FileOffset[",z,"]=",FileOffset[z]
# print " "
if 'label' in PhyPartition[k][j]:
PartitionLabel = PhyPartition[k][j]['label']
for z in range(len(FileToProgram)):
#print "===============================%i of %i===========================================" % (z,len(FileToProgram))
#print "File: ",FileToProgram[z]
#print "Label: ",FileToProgram[z]
#print "FilePartitionOffset[z]=",FilePartitionOffset[z]
#print "UpdateRawProgram(RawProgramXML,",(FirstLBA+FilePartitionOffset[z]),",",((LastLBA-FirstLBA)*SECTOR_SIZE_IN_BYTES/1024.0),",",PhysicalPartitionNumber,",",FileOffset[z],",",(LastLBA-FirstLBA-FilePartitionOffset[z]),",",(FileToProgram[z]),",", PartitionLabel,")"
#print "LastLBA=",LastLBA
#print "FirstLBA=",FirstLBA
#print "FilePartitionOffset[z]=",FilePartitionOffset[z]
UpdateRawProgram(RawProgramXML,
FirstLBA+FilePartitionOffset[z], # Start sector
((LastLBA-FirstLBA+1))*SECTOR_SIZE_IN_BYTES/1024.0, # Size in KB
PhysicalPartitionNumber,
FileOffset[z],
LastLBA-FirstLBA+1 - FilePartitionOffset[z], # num_partition_sectors
FileToProgram[z],
FileSparse[z],
PartitionLabel,
PhyPartition[k][j]['readbackverify'],
PhyPartition[k][j]['partofsingleimage'])
if (j+1) == len(PhyPartition[k]):
## last partition, and if GROW was set to True, it will only have a size of 0
UpdateRawProgram(RawProgramXML_Wipe,
FirstLBA+FilePartitionOffset[z], #Start Sector
(ConvertKBtoSectors(PhyPartition[k][j]['original_size_in_kb'])+(LastLBA-FirstLBA)+1)*SECTOR_SIZE_IN_BYTES/1024.0, # Size in KB
PhysicalPartitionNumber,
FileOffset[z],
ConvertKBtoSectors(PhyPartition[k][j]['original_size_in_kb'])+LastLBA-FirstLBA+1-FilePartitionOffset[z],
"zeros_33sectors.bin",
"false",
PartitionLabel,
PhyPartition[k][j]['readbackverify'],
PhyPartition[k][j]['partofsingleimage'])
else:
UpdateRawProgram(RawProgramXML_Wipe,
FirstLBA+FilePartitionOffset[z], # Start Sector
((LastLBA-FirstLBA)+1)*SECTOR_SIZE_IN_BYTES/1024.0, # Size in KB
PhysicalPartitionNumber,
FileOffset[z],
LastLBA-FirstLBA+1-FilePartitionOffset[z], # num_partition_sectors
"zeros_33sectorS.bin",
"false",
PartitionLabel,
PhyPartition[k][j]['readbackverify'],
PhyPartition[k][j]['partofsingleimage'])
if j==0:
UpdateRawProgram(RawProgramXML_Blank,0, 33*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, FileOffset[z], 33, "gpt_empty%d.bin" % k, "false", "PrimaryGPT", "false", "false")
LastLBA += 1 ## move to the next free sector, also, 0 to 9 inclusive means it's 10
## so below (LastLBA-FirstLBA) must = 10
FirstLBA = LastLBA # getting ready for next partition, FirstLBA is now where we left off
## Still working on *this* PHY partition
## making protective MBR, all zeros in buffer up until 0x1BE
i = 0x1BE
PrimaryGPT[i+0] = 0x00 # not bootable
PrimaryGPT[i+1] = 0x00 # head
PrimaryGPT[i+2] = 0x01 # sector
PrimaryGPT[i+3] = 0x00 # cylinder
PrimaryGPT[i+4] = 0xEE # type
PrimaryGPT[i+5] = 0xFF # head
PrimaryGPT[i+6] = 0xFF # sector
PrimaryGPT[i+7] = 0xFF # cylinder
PrimaryGPT[i+8:i+8+4] = [0x01,0x00,0x00,0x00] # starting sector
PrimaryGPT[i+12:i+12+4] = [0xFF,0xFF,0xFF,0xFF] # starting sector
PrimaryGPT[440] = (HashInstructions['DISK_SIGNATURE']>>24)&0xFF
PrimaryGPT[441] = (HashInstructions['DISK_SIGNATURE']>>16)&0xFF
PrimaryGPT[442] = (HashInstructions['DISK_SIGNATURE']>>8)&0xFF
PrimaryGPT[443] = (HashInstructions['DISK_SIGNATURE'])&0xFF
PrimaryGPT[510:512] = [0x55,0xAA] # magic byte for MBR partitioning - always at this location regardless of SECTOR_SIZE_IN_BYTES
i = SECTOR_SIZE_IN_BYTES
## Signature and Revision and HeaderSize i.e. "EFI PART" and 00 00 01 00 and 5C 00 00 00
PrimaryGPT[i:i+16] = [0x45, 0x46, 0x49, 0x20, 0x50, 0x41, 0x52, 0x54, 0x00, 0x00, 0x01, 0x00, 0x5C, 0x00, 0x00, 0x00] ; i+=16
PrimaryGPT[i:i+4] = [0x00, 0x00, 0x00, 0x00] ; i+=4 ## CRC is zeroed out till calculated later
PrimaryGPT[i:i+4] = [0x00, 0x00, 0x00, 0x00] ; i+=4 ## Reserved, set to 0
CurrentLBA= 1 ; i = UpdatePrimaryGPT(CurrentLBA,8,i)
BackupLBA = 0 ; i = UpdatePrimaryGPT(BackupLBA,8,i)
FirstLBA = len(PrimaryGPT)/SECTOR_SIZE_IN_BYTES ; i = UpdatePrimaryGPT(FirstLBA,8,i)
LastLBA = 0 ; i = UpdatePrimaryGPT(LastLBA,8,i)
##print "\n\nBackup GPT is at sector %i" % BackupLBA
##print "Last Usable LBA is at sector %i" % (LastLBA)
DiskGUID = random.randint(0,2**(128))
i = UpdatePrimaryGPT(DiskGUID,16,i)
PartitionsLBA = 2 ; i = UpdatePrimaryGPT(PartitionsLBA,8,i)
NumPartitions = (SECTOR_SIZE_IN_BYTES/128)*int(len(PhyPartition[k])/(SECTOR_SIZE_IN_BYTES/128)) # Want a multiple of (SECTOR_SIZE_IN_BYTES) to fill the sector (avoids gdisk warning)
if (len(PhyPartition[k])%(SECTOR_SIZE_IN_BYTES/128))>0:
NumPartitions+=(SECTOR_SIZE_IN_BYTES/128)
if force128partitions == 1:
print("\n\nGPT table will list 128 partitions instead of ",NumPartitions)
print("This makes the output compatible with some older test utilities")
NumPartitions = 128
i = UpdatePrimaryGPT(NumPartitions,4,i) ## (offset 80) Number of partition entries
##NumPartitions = 8 ; i = UpdatePrimaryGPT(NumPartitions,4,i) ## (offset 80) Number of partition entries
SizeOfPartitionArray = 128 ; i = UpdatePrimaryGPT(SizeOfPartitionArray,4,i) ## (offset 84) Size of partition entries
## Now I can calculate the partitions CRC
print("\n\nCalculating CRC with NumPartitions=%i, SizeOfPartitionArray=%i (bytes each) TOTAL LENGTH %d" % (NumPartitions,SizeOfPartitionArray,NumPartitions*SizeOfPartitionArray));
##PartitionsCRC = CalcCRC32(PrimaryGPT[1024:],NumPartitions*SizeOfPartitionArray) ## Each partition entry is 128 bytes
PartitionsPerSector = SECTOR_SIZE_IN_BYTES/128 ## 128 bytes per partition
if NumPartitions>PartitionsPerSector:
SectorsToCalculateCRCOver = NumPartitions/PartitionsPerSector
if NumPartitions%PartitionsPerSector:
SectorsToCalculateCRCOver+=1
else:
SectorsToCalculateCRCOver = 1
PartitionsCRC = CalcCRC32(PrimaryGPT[(2*SECTOR_SIZE_IN_BYTES):],SectorsToCalculateCRCOver * SECTOR_SIZE_IN_BYTES) ## NAND HACK
i = UpdatePrimaryGPT(PartitionsCRC,4,i)
print("\n\nCalculated PARTITION CRC is 0x%.8X" % PartitionsCRC)
## gpt patch - main gpt header - last useable lba
ByteOffset = str(48)
StartSector = str(1)
BackupStartSector = str(BackupGPTNumLBAs-1) ## Want last sector ##str(32)
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,os.path.basename(GPTMAIN), "Update Primary Header with LastUseableLBA.")
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,"DISK", "Update Primary Header with LastUseableLBA.")
UpdatePatch(BackupStartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,os.path.basename(GPTBACKUP), "Update Backup Header with LastUseableLBA.")
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % PrimaryGPTNumLBAs,"DISK", "Update Backup Header with LastUseableLBA.")
# gpt patch - location of backup gpt header ##########################################
ByteOffset = str(32)
StartSector = str(1)
## gpt patch - main gpt header
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-1.",os.path.basename(GPTMAIN), "Update Primary Header with BackupGPT Header Location.")
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-1.","DISK", "Update Primary Header with BackupGPT Header Location.")
# gpt patch - currentLBA backup header ##########################################
ByteOffset = str(24)
BackupStartSector = str(BackupGPTNumLBAs-1) ## Want last sector ##str(32)
## gpt patch - main gpt header
UpdatePatch(BackupStartSector, ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-1.",os.path.basename(GPTBACKUP), "Update Backup Header with CurrentLBA.")
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-1.","DISK", "Update Backup Header with CurrentLBA.")
# gpt patch - location of backup gpt header ##########################################
ByteOffset = str(72)
BackupStartSector = str(BackupGPTNumLBAs-1) ## Want last sector ##str(32)
## gpt patch - main gpt header
UpdatePatch(BackupStartSector, ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % BackupGPTNumLBAs,os.path.basename(GPTBACKUP), "Update Backup Header with Partition Array Location.")
UpdatePatch("NUM_DISK_SECTORS-1",ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-%d." % BackupGPTNumLBAs,"DISK", "Update Backup Header with Partition Array Location.")
# gpt patch - Partition Array CRC ################################################
ByteOffset = str(88)
StartSector = str(1)
BackupStartSector = str(BackupGPTNumLBAs-1) ## Want last sector ##str(32)
## gpt patch - main gpt header
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"CRC32(2,%d)" % (NumPartitions*SizeOfPartitionArray),os.path.basename(GPTMAIN), "Update Primary Header with CRC of Partition Array.") # CRC32(start_sector:num_bytes)
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"CRC32(2,%d)" % (NumPartitions*SizeOfPartitionArray),"DISK", "Update Primary Header with CRC of Partition Array.") # CRC32(start_sector:num_bytes)
## gpt patch - backup gpt header
UpdatePatch(BackupStartSector, ByteOffset,PhysicalPartitionNumber,4,"CRC32(0,%d)" % (NumPartitions*SizeOfPartitionArray),os.path.basename(GPTBACKUP), "Update Backup Header with CRC of Partition Array.") # CRC32(start_sector:num_bytes)
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,4,"CRC32(NUM_DISK_SECTORS-%d.,%d)" % (BackupGPTNumLBAs,NumPartitions*SizeOfPartitionArray),"DISK", "Update Backup Header with CRC of Partition Array.") # CRC32(start_sector:num_bytes)
#print "\nNeed to patch PARTITION ARRAY, @ sector 1, byte offset 88, size=4 bytes, CRC32(2,33)"
#print "\nNeed to patch PARTITION ARRAY, @ sector -1, byte offset 88, size=4 bytes, CRC32(2,33)"
## Now I can calculate the Header CRC
##print "\nCalculating CRC for Primary Header"
CalcHeaderCRC = CalcCRC32(PrimaryGPT[SECTOR_SIZE_IN_BYTES:],92)
UpdatePrimaryGPT(CalcHeaderCRC,4,SECTOR_SIZE_IN_BYTES+16)
#print "\n\nCalculated HEADER CRC is 0x%.8X" % CalcHeaderCRC
#print "\nNeed to patch GPT HEADERS in 2 places"
#print "\nNeed to patch CRC HEADER, @ sector 1, byte offset 16, size=4 bytes, CRC32(1,1)"
#print "\nNeed to patch CRC HEADER, @ sector -1, byte offset 16, size=4 bytes, CRC32(1,1)"
# gpt patch - Header CRC ################################################
ByteOffset = str(16)
StartSector = str(1)
BackupStartSector = str(BackupGPTNumLBAs-1) ## Want last sector ##str(32)
## gpt patch - main gpt header
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"0",os.path.basename(GPTMAIN), "Zero Out Header CRC in Primary Header.") # zero out old CRC first
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"CRC32(1,92)",os.path.basename(GPTMAIN), "Update Primary Header with CRC of Primary Header.") # CRC32(start_sector:num_bytes)
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"0", "DISK", "Zero Out Header CRC in Primary Header.") # zero out old CRC first
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,4,"CRC32(1,92)","DISK", "Update Primary Header with CRC of Primary Header.") # CRC32(start_sector:num_bytes)
## gpt patch - backup gpt header
#import pdb; pdb.set_trace()
UpdatePatch(BackupStartSector,ByteOffset,PhysicalPartitionNumber,4,"0",os.path.basename(GPTBACKUP), "Zero Out Header CRC in Backup Header.") # zero out old CRC first
UpdatePatch(BackupStartSector,ByteOffset,PhysicalPartitionNumber,4,"CRC32(%s,92)" % BackupStartSector,os.path.basename(GPTBACKUP), "Update Backup Header with CRC of Backup Header.") # CRC32(start_sector:num_bytes)
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,4,"0", "DISK", "Zero Out Header CRC in Backup Header.") # zero out old CRC first
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,4,"CRC32(NUM_DISK_SECTORS-1.,92)","DISK", "Update Backup Header with CRC of Backup Header.") # CRC32(start_sector:num_bytes)
## now create the backup GPT partitions
BackupGPT = [0xFF]*int(BackupGPTNumLBAs*SECTOR_SIZE_IN_BYTES)
BackupGPT[0:] = PrimaryGPT[2*SECTOR_SIZE_IN_BYTES:]
## now create the backup GPT header
BackupGPT[int((BackupGPTNumLBAs-1)*SECTOR_SIZE_IN_BYTES):int(BackupGPTNumLBAs*SECTOR_SIZE_IN_BYTES)]= PrimaryGPT[1*SECTOR_SIZE_IN_BYTES:2*SECTOR_SIZE_IN_BYTES] ##BackupGPTNumLBAs=33
#ShowBackupGPT(32)
## Need to update CurrentLBA, BackupLBA and then recalc CRC for this header
i = (BackupGPTNumLBAs-1)*SECTOR_SIZE_IN_BYTES+8+4+4
CalcHeaderCRC = 0 ; i = UpdateBackupGPT(CalcHeaderCRC,4,i) ## zero out CRC
CalcHeaderCRC = 0 ; i = UpdateBackupGPT(CalcHeaderCRC,4,i) ## reserved 4 zeros
CurrentLBA = 0 ; i = UpdateBackupGPT(CurrentLBA,8,i)
BackupLBA = 1 ; i = UpdateBackupGPT(BackupLBA,8,i)
#print "\n\nBackup GPT is at sector %i" % CurrentLBA
#print "Last Usable LBA is at sector %i" % (CurrentLBA-33)
i += 8+8+16
PartitionsLBA = 0 ; i = UpdateBackupGPT(PartitionsLBA,8,i)
#print "PartitionsLBA = %d (0x%X)" % (PartitionsLBA,PartitionsLBA)
##print "\nCalculating CRC for Backup Header"
CalcHeaderCRC = CalcCRC32(BackupGPT[int((BackupGPTNumLBAs-1)*SECTOR_SIZE_IN_BYTES):],92)
#print "\nCalcHeaderCRC of BackupGPT is 0x%.8X" % CalcHeaderCRC
i = (BackupGPTNumLBAs-1)*SECTOR_SIZE_IN_BYTES+8+4+4
i = UpdateBackupGPT(CalcHeaderCRC,4,i) ## zero out CRC