-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathptool.py
2227 lines (1710 loc) · 107 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
#===========================================================================
# This script parses "partition.xml" and creates numerous output files
# specifically, partition.bin, rawprogram.xml
# REFERENCES
# $Header: //source/qcom/qct/core/pkg/bootloaders/rel/1.0/boot_images/core/storage/tools/jsdcc/partition_load_pt/ptool.py#18 $
# $DateTime: 2012/08/23 12:22:11 $
# $Author: coresvc $
# when who what, where, why
# -------- --- -------------------------------------------------------
# 2012-08-20 ah Added uniquegugid for partition.xml
# 2012-08-16 ah Fixed bug if PERFORMANCE_BOUNDARY_IN_KB wasn't specified
# 2012-08-14 ah PERFORMANCE_BOUNDARY_IN_KB can now be an individual partition tag
# 2012-07-06 ah More user friendly with ShowPartitionExample()
# 2012-04-30 ah GPT Attributes bits corrected
# 2012-02-24 ah Much cleaner code - fixes for configurable sector sizes
# 2012-02-15 ah Minor fix when 'SECTOR_SIZE_IN_BYTES' is not defined
# 2012-01-13 ah Fixed bug where rawprogram.xml was reporting numsectors off by 1
# 2011-11-22 ah Added SECTOR_SIZE_IN_BYTES option (defaults to 512)
# 2011-11-17 ah Added force128 partitions, option -k
# 2011-11-14 ah Enabled zeroout tag for GPT
# 2011-10-19 ah Not allowing empty <physical_partition> tags in partition.xml - makes multiple PHY partitions work
# 2011-09-23 ah GPT num partitions in table not fixed to 128, respecting partition table attributes now
# 2011-08-12 ah Added ALIGN_PARTITIONS_TO_PERFORMANCE_BOUNDARY, WRITE_PROTECT_GPT_PARTITION_TABLE
# 2011-08-11 ah Added Unique GUID option or Sequential -g (default is unique)
# 2011-08-09 ah Fix alignment issue for WPG<64MB - Fixed GPT off by 1 sector issue
# 2011-08-04 ah Now allowing -t option to specify output directory for files
# 2011-07-26 ah Much better error message if GUID invalid, fixed 'grow' partition size (patch)
# 2011-07-21 ah Major revision, using getopt(), auto-discovering GPT or MBR
# 2011-07-13 ah Corrected sparse support
# 2011-06-01 ah Added sparse support for GPT - corrected size of last partition
# 2011-05-26 ah Adds "zeroout" tag (wiping GPT) and "sparse" file support
# 2011-05-21 ab Undoing hack for boot to wipe out sector 1
# 2011-05-17 ah removing GPT sectors is simpler now, compatible with 8960 tz.mbn issue
# 2011-05-06 ah MBR partition tables now nuke any trace of GPT (request from boot team)
# 2011-04-26 ah temporarily removed 'start_byte_hex':szStartByte for QPST compatibility
# 2011-03-23 ah ensured last partition is size 0 for rawprogram.xml
# 2011-03-22 ah rawprogram for GPT for 'grow' partition, since mjsdload.cmm couldn't handle big number
# 2011-03-22 ah Corrected final disk size patch (off by 1 sector), corrected GPT labels (uni-code)
# 2011-03-18 ah Fixed default bug for DISK_SIGNATURE, align_wpb -> align
# 2011-03-16 ah New DISK_SIGNATURE tag added for MBR partitions, Split partition0.bin into
# MBR0.bin and EBR0.bin, Corrected bug in backup GPT DISK patching
# 2011-03-10 ah Removes loadpt.cmm, splits partition0.bin to MBR0.bin, EBR0.bin
# 2011-03-09 ah Much more error checking, cleaner, adds "align_wpb" tag
# 2011-02-14 ah Added patching of DISK for GPT
# 2011-02-02 ah Allow MBR Type to be specified as "4C" or "0x4C"
# 2011-25-01 ah Outputs "patch.xml" as well, allows more optimal partition alignment
# 2010-12-01 ah Matching QPST, all EXT partitions 64MB aligned (configurable actually)
# More error checking, Removed CHS option, GPT output is 2 files (primary and backup)
# 2010-10-26 ah better error checking, corrected typo on physical_partition for > 0
# 2010-10-25 ah adds GPT, CFILE output, various other features
# 2010-10-08 ah released to remove compile errors of missing PERL script modules
# Copyright (c) 2007-2010
# Qualcomm Technologies Incorporated.
# All Rights Reserved.
# Qualcomm Confidential and Proprietary
# ===========================================================================*/
import sys,os,getopt
import random,math
import re
import struct
from types import *
from time import sleep
if sys.version_info < (2,5):
sys.stdout.write("\n\nERROR: This script needs Python version 2.5 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)
## 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):
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
SubElement(RawProgramXML, 'program', {'start_sector':szStartSector, 'size_in_KB':str(size_in_KB), 'physical_partition_number':str(PHYPartition),
'file_sector_offset':str(file_sector_offset), 'num_partition_sectors':str(num_partition_sectors),
'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 NoneType:
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 NoneType:
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 NoneType:
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 NoneType:
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 NoneType:
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):
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)
def UpdatePrimaryGPT(value,length,i):
global PrimaryGPT
for b in range(length):
PrimaryGPT[i] = ((value>>(b*8)) & 0xFF) ; i+=1
return i
def UpdateBackupGPT(value,length,i):
global BackupGPT
for b in range(length):
BackupGPT[i] = ((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, x:
print "ERROR: Could not create '%s', cwd=%s" % (filename,os.getcwd() )
print "REASON: %s" % (x)
sys.exit(1)
temp = [0]*(SECTOR_SIZE_IN_BYTES*num_sectors)
zeros = struct.pack("%iB"%(SECTOR_SIZE_IN_BYTES*num_sectors),*temp)
try:
opfile.write(zeros)
except Exception, x:
print "ERROR: Could not write zeros to '%s'\nREASON: %s" % (filename,x)
sys.exit(1)
try:
opfile.close()
except Exception, 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_33sectors.bin",33)
##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_1sector.bin", "false", "Overwrite MBR sector")
UpdateRawProgram(temp,1, 33*SECTOR_SIZE_IN_BYTES/1024.0, i, 0, 33, "zeros_33sectors.bin", "false", "Overwrite Primary GPT Sectors")
UpdateRawProgram(temp,-33, 33*SECTOR_SIZE_IN_BYTES/1024.0, i, 0, 33, "zeros_33sectors.bin", "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):
global opfile,PhyPartition,PrimaryGPT,BackupGPT,RawProgramXML, GPTMAIN, GPTBACKUP, GPTBOTH, RAW_PROGRAM, PATCHES
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)
GPTBACKUP = '%sgpt_backup%d.bin' % (OutputFolder,k)
GPTBOTH = '%sgpt_both%d.bin' % (OutputFolder,k)
RAW_PROGRAM = '%srawprogram%d.xml' % (OutputFolder,k)
RAW_PROGRAM_BLANK = '%srawprogram%d_BLANK.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)
## ---------------------------------------------------------------------------------
## Step 2. Move through xml definition and figure out partitions sizes
## ---------------------------------------------------------------------------------
i = 2*SECTOR_SIZE_IN_BYTES ## partition arrays begin here
FirstLBA = 34
LastLBA = 34 ## 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)):
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()
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)
##import pdb; pdb.set_trace() # timmy
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 = 33
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-34.",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-34.","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-34.",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." % (33-BackupStartSector),ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-34.","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, OR another way, LastLBA must be odd
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
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]['system']=="true":
Attributes |= 1<<0
##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], ((LastLBA-FirstLBA)+1)*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, FileOffset[z], LastLBA-FirstLBA-FilePartitionOffset[z]+1, FileToProgram[z], FileSparse[z], PartitionLabel)
UpdateRawProgram(RawProgramXML_Blank,FirstLBA+FilePartitionOffset[z], ((LastLBA-FirstLBA)+1)*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, FileOffset[z], LastLBA-FirstLBA-FilePartitionOffset[z]+1, "zeros_1sector.bin", "false", PartitionLabel)
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 = 34 ; 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 = 0x4BFA5EA0886429854DAC4B1C1ED28A1F
DiskGUID = 0x200C003DB32B6EA04BF2BBE298101B32
i = UpdatePrimaryGPT(DiskGUID,16,i)
PartitionsLBA = 2 ; i = UpdatePrimaryGPT(PartitionsLBA,8,i)
NumPartitions = 4*int(len(PhyPartition[k])/4) # Want a multiple of 4 to fill the sector (avoids gdisk warning)
if (len(PhyPartition[k])%4)>0:
NumPartitions+=4
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
##PartitionsCRC = CalcCRC32(PrimaryGPT[1024:],32*512)
##print "\n\nCalculating CRC with NumPartitions=%i, SizeOfPartitionArray=%i TOTAL LENGTH %d" % (NumPartitions,SizeOfPartitionArray,NumPartitions*SizeOfPartitionArray);
PartitionsCRC = CalcCRC32(PrimaryGPT[1024:],NumPartitions*SizeOfPartitionArray) ## Each partition entry is 128 bytes
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(32)
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-34.",os.path.basename(GPTMAIN), "Update Primary Header with LastUseableLBA.")
UpdatePatch(StartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-34.","DISK", "Update Primary Header with LastUseableLBA.")
UpdatePatch(BackupStartSector,ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-34.",os.path.basename(GPTBACKUP), "Update Backup Header with LastUseableLBA.")
UpdatePatch("NUM_DISK_SECTORS-1.",ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-34.","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(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(32)
## gpt patch - main gpt header
UpdatePatch(BackupStartSector, ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-33.",os.path.basename(GPTBACKUP), "Update Backup Header with Partition Array Location.")
UpdatePatch("NUM_DISK_SECTORS-1",ByteOffset,PhysicalPartitionNumber,8,"NUM_DISK_SECTORS-33.","DISK", "Update Backup Header with Partition Array Location.")
# gpt patch - Partition Array CRC ################################################
ByteOffset = str(88)
StartSector = str(1)
BackupStartSector = 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-33.,%d)" % (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(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
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(32,92)",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]*(33*SECTOR_SIZE_IN_BYTES)
BackupGPT[0:] = PrimaryGPT[2*SECTOR_SIZE_IN_BYTES:]
## now create the backup GPT header
BackupGPT[32*SECTOR_SIZE_IN_BYTES:33*SECTOR_SIZE_IN_BYTES]= PrimaryGPT[1*SECTOR_SIZE_IN_BYTES:2*SECTOR_SIZE_IN_BYTES]
#ShowBackupGPT(32)
## Need to update CurrentLBA, BackupLBA and then recalc CRC for this header
i = 32*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[32*SECTOR_SIZE_IN_BYTES:],92)
#print "\nCalcHeaderCRC of BackupGPT is 0x%.8X" % CalcHeaderCRC
i = 32*SECTOR_SIZE_IN_BYTES+8+4+4
i = UpdateBackupGPT(CalcHeaderCRC,4,i) ## zero out CRC
#ShowBackupGPT(32)
UpdateRawProgram(RawProgramXML,0, 34*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, 0, 34, os.path.basename(GPTMAIN), 'false', 'PrimaryGPT')
UpdateRawProgram(RawProgramXML_Blank,0, 1*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, 0, 1, "zeros_1sector.bin", 'false', 'PrimaryGPT')
UpdateRawProgram(RawProgramXML_Blank,1, 33*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, 0, 33, "zeros_33sectors.bin", 'false', 'PrimaryGPT')
#print "szStartSector=%s" % szStartSector
UpdateRawProgram(RawProgramXML,-33, 33*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, 0, 33, os.path.basename(GPTBACKUP), 'false', 'BackupGPT')
UpdateRawProgram(RawProgramXML_Blank,-33, 33*SECTOR_SIZE_IN_BYTES/1024.0, PhysicalPartitionNumber, 0, 33, "zeros_33sectors.bin", 'false', 'BackupGPT')
##print "szStartSector=%s" % szStartSector
WriteGPT(GPTMAIN, GPTBACKUP)
opfile = open(RAW_PROGRAM, "w")
opfile.write( prettify(RawProgramXML) )
opfile.close()
print "\nCreated \"%s\"\t<-- YOUR partition information is HERE" % RAW_PROGRAM
opfile = open(RAW_PROGRAM_BLANK, "w")
opfile.write( prettify(RawProgramXML_Blank) )
opfile.close()
print "Created \"%s\"\t<-- Wipe out your images with this file (if needed for testing)" % RAW_PROGRAM_BLANK
opfile = open(PATCHES, "w") # gpt
opfile.write( prettify(PatchesXML) )
opfile.close()
print "Created \"%s\"\t\t<-- Tailor your partition tables to YOUR device with this file\n" % PATCHES
def AlignVariablesToEqualSigns(sz):
temp = re.sub(r"(\t| )+=","=",sz)
temp = re.sub(r"=(\t| )+","=",temp)
return temp
def ReturnArrayFromSpaceSeparatedList(sz):
temp = re.sub(r"\s+|\n"," ",sz)
temp = re.sub(r"^\s+","",temp)
temp = re.sub(r"\s+$","",temp)
return temp.split(' ')
def ParseXML(XMLFile):
global OutputToCreate,NumPhyPartitions, PartitionCollection, PhyPartition,MinSectorsNeeded,SECTOR_SIZE_IN_BYTES
root = ET.parse( XMLFile )
#Create an iterator
iter = root.getiterator()
for element in iter:
#print "\nElement:" , element.tag # thins like image,primary,extended etc
if element.tag=="parser_instructions":
instructions = ReturnArrayFromSpaceSeparatedList(AlignVariablesToEqualSigns(element.text))
for element in instructions:
temp = element.split('=')
if len(temp) > 1:
HashInstructions[temp[0].strip()] = temp[1].strip()
#print "HashInstructions['%s'] = %s" % (temp[0].strip(),temp[1].strip())
elif element.tag=="physical_partition":
# We can have this scenario meaning NumPhyPartitions++ but len(PhyPartition) doesn't increase
# <physical_partition>
# </physical_partition>
# Thus if NumPhyPartitions > len(PhyPartition) by 2, then we need to increase it
NumPhyPartitions += 1
PartitionCollection = [] # Reset, we've found a new physical partition
if NumPhyPartitions-len(PhyPartition)>=2:
print "\n\n"
print "*"*78
print "ERROR: Empty <physical_partition></physical_partition> tags detected\n"
print "Please replace with"
print "<physical_partition>"
print "<partition label='placeholder' size_in_kb='0' type='00000000-0000-0000-0000-000000000001' bootable='false' readonly='false' filename='' />"
print "</physical_partition>\n"
sys.exit()
print "\nFound a physical_partition, NumPhyPartitions=%d" % NumPhyPartitions
print "\nlen(PhyPartition)=%d" % len(PhyPartition)
elif element.tag=="partition" or element.tag=="primary" or element.tag=="extended":
if element.keys():
#print "\tAttributes:"
# Reset all variables to defaults
Partition = {}
# This partition could have more than 1 file, so these are arrays
# However, as I loop through the elements, *if* there is more than 1 file
# it will have it's own <file> tag
Partition['filename'] = [""]