forked from kubiko/partitioning_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsp.py
1846 lines (1463 loc) · 79.2 KB
/
msp.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) 2015, 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 struct, os, sys, getopt
import math,traceback
import re
import codecs
from types import *
import time
from time import sleep
import subprocess as sub
from time import strftime, localtime
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
DiskSectors = 0
BLOCK_SIZE = 0x200
TABLE_ENTRY_0 = 0x1BE
TABLE_ENTRY_1 = 0x1CE
TABLE_ENTRY_2 = 0x1DE
TABLE_ENTRY_3 = 0x1EE
EMMCBLD_MAX_DISK_SIZE_IN_BYTES = (64*1024*1024*1024*1024) # 64TB - Terabytes
MAX_FILE_SIZE_BEFORE_SPLIT = (10*1024*1024)
#MAX_FILE_SIZE_BEFORE_SPLIT = (2048) # testing purposes
ExtendedPartitionBegins = 0
bytes_read = 0
FileNotFoundShowWarning = 0
SECTOR_SIZE = 512
disk_size = None
def reset_device_log():
try:
log_fp = open('log_msp.txt', 'w')
except Exception, x:
print "\nERROR: Can't create the file log_msp.txt"
print "REASON: %s" % x
print "This might be because the file is open and locked"
print "Or because you are running this from a read-only location\n"
sys.exit()
print "\nCREATED log_msp.txt\n"
log_fp.close()
def device_log(message, display=1):
try:
log_fp = open('log_msp.txt', 'a')
except Exception, x:
print "ERROR: could not open 'log_msp.txt'"
print "REASON: %s" % x
return
try:
log_fp.write("%s %s\n" % (strftime("%H:%M:%S", localtime()),message))
except Exception, x:
print "ERROR: could not write to 'log_msp.txt'"
print "REASON: %s" % x
return
if display==1:
print message
log_fp.close()
def ReadSectors(opfile,NumSectors):
try:
return opfile.read(NumSectors*SECTOR_SIZE)
except Exception, x:
PrintBigError("Could not complete the read")
device_log("REASON: %s" % (x))
reset_device_log()
device_log("\nmsp.py is running from CWD: %s\n" % os.getcwd())
def EnsureDirectoryExists(filename):
dir = os.path.dirname(filename)
try:
os.stat(dir)
except Exception, x:
os.makedirs(dir)
def PrintBigWarning(sz):
device_log("\t _ ")
device_log("\t (_) ")
device_log("\t__ ____ _ _ __ _ __ _ _ __ __ _ ")
device_log("\t\\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` |")
device_log("\t \\ V V / (_| | | | | | | | | | | (_| |")
device_log("\t \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, |")
device_log("\t __/ |")
device_log("\t |___/ \n")
if len(sz)>0:
device_log(sz)
def PrintBigError(sz):
device_log("\t _________________ ___________ ")
device_log("\t| ___| ___ \\ ___ \\ _ | ___ \\")
device_log("\t| |__ | |_/ / |_/ / | | | |_/ /")
device_log("\t| __|| /| /| | | | / ")
device_log("\t| |___| |\\ \\| |\\ \\\\ \\_/ / |\\ \\ ")
device_log("\t\\____/\\_| \\_\\_| \\_|\\___/\\_| \\_|\n")
device_log("\nERROR - ERROR - ERROR - ERROR - ERROR\n")
if len(sz)>0:
device_log(sz)
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit(1)
def PrettyPrintArray(bytes_read):
Bytes = struct.unpack("%dB" % len(bytes_read),bytes_read)
for k in range(len(Bytes)/SECTOR_SIZE):
print "-"*78
for j in range(32):
for i in range(16):
sys.stdout.write("%.2X " % Bytes[i+j*16])
sys.stdout.write("\t")
for i in range(16):
sys.stdout.write("%c" % Bytes[i+j*16])
print " "
print " "
def external_call(command, capture_output=True):
errors = None
output = None
try:
if capture_output:
if sys.platform.startswith("linux"):
p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
else:
p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = p.communicate()
else:
os.system(command)
except Exception, e:
print output
device_log("Error executing command '%s' (%s)" % (str(command), e))
#clean_up()
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit(1)
finally:
#if not output is None:
# device_log("Result: %s" % output)
if (not errors is None) and (not errors == ""):
device_log("Process stderr: %s" % errors)
return output
def HandleNUM_DISK_SECTORS(field):
if type(field) is not str:
#print "returning since this is not a string"
return field
m = re.search("NUM_DISK_SECTORS-(\d+)", field)
if type(m) is not NoneType:
if DiskSizeInBytes > 0 :
field = int((DiskSizeInBytes/SECTOR_SIZE)-int(m.group(1))) # here I know DiskSizeInBytes
else:
field = int((EMMCBLD_MAX_DISK_SIZE_IN_BYTES/SECTOR_SIZE)+int(m.group(1))) # I make this a gigantic number for sorting (PLUS not MINUS here)
if type(field) is not str:
return field
m = re.search("NUM_DISK_SECTORS", field)
if type(m) is not NoneType:
if DiskSizeInBytes > 0 :
field = int((DiskSizeInBytes/SECTOR_SIZE))
else:
field = int((EMMCBLD_MAX_DISK_SIZE_IN_BYTES/SECTOR_SIZE))
if type(field) is not str:
return field
field = int(field)
return field
def ReturnParsedValues(element):
global SECTOR_SIZE
MyDict = { 'filename':'','file_sector_offset':'0','label':'','num_partition_sectors':'0',
'physical_partition_number':'0','size_in_KB':'0','sparse':'false','start_byte_hex':'0x0','start_sector':'0',
'function':'none','arg0':'0','arg1':'0','value':'0','byte_offset':'0','size_in_bytes':'4','SECTOR_SIZE_IN_BYTES':'512' }
for name, value in element.items():
##device_log("\t\tName: '%s'=>'%s' " % (name,value))
MyDict[name]=value
if 'SECTOR_SIZE_IN_BYTES' in MyDict:
SECTOR_SIZE = int(MyDict['SECTOR_SIZE_IN_BYTES'])
if 'num_sectors' in MyDict: ## Legacy name used in original partition.xml
MyDict['num_partition_sectors'] = MyDict['num_sectors']
if 'offset' in MyDict: ## Legacy name used in original partition.xml
MyDict['file_sector_offset'] = MyDict['offset']
MyDict['num_partition_sectors'] = HandleNUM_DISK_SECTORS(MyDict['num_partition_sectors']) # Means field can have 'NUM_DISK_SECTORS-5.' type of contents
MyDict['start_sector'] = HandleNUM_DISK_SECTORS(MyDict['start_sector']) # Means field can have 'NUM_DISK_SECTORS-5.' type of contents
MyDict['file_sector_offset'] = HandleNUM_DISK_SECTORS(MyDict['file_sector_offset']) # Means field can have 'NUM_DISK_SECTORS-5.' type of contents
MyDict['physical_partition_number'] = int(MyDict['physical_partition_number'])
MyDict['byte_offset'] = int(float(MyDict['byte_offset']))
MyDict['size_in_bytes'] = int(float(MyDict['size_in_bytes']))
# These only affect patching
m = re.search("CRC32\((\d+).?,(\d+).?\)", MyDict['value'])
if type(m) is not NoneType:
MyDict['value'] = 0
MyDict['function'] = "CRC32"
MyDict['arg0'] = int(float(m.group(1))) # start_sector
MyDict['arg1'] = int(float(m.group(2))) # len_in_bytes
else:
## above didn't match, so try this
m = re.search("CRC32\((NUM_DISK_SECTORS-\d+).?,(\d+).?\)", MyDict['value'])
if type(m) is not NoneType:
MyDict['value'] = 0
MyDict['function'] = "CRC32"
MyDict['arg0'] = int(float( HandleNUM_DISK_SECTORS(m.group(1)) )) # start_sector
MyDict['arg1'] = int(float(m.group(2))) # len_in_bytes
MyDict['value'] = HandleNUM_DISK_SECTORS(MyDict['value']) # Means field can have 'NUM_DISK_SECTORS-5.' type of contents
return MyDict
def ParseXML(xml_filename): ## this function updates all the global arrays
global WriteArray,PatchArray,ReadArray,MinDiskSizeInSectors
root = ET.parse( xml_filename )
#Create an iterator
iter = root.getiterator()
for element in iter:
#device_log("\nElement: %s" % element.tag)
# Parse out include files
if element.tag=="read":
if element.keys():
ReadArray.append( ReturnParsedValues(element) )
else:
print "ERROR: Your <read> tag is not formed correctly\n"
sys.exit(1)
elif element.tag=="program":
if element.keys():
WriteArray.append( ReturnParsedValues(element) )
else:
print "ERROR: Your <program> tag is not formed correctly\n"
sys.exit(1)
elif element.tag=="patch":
if element.keys():
PatchArray.append( ReturnParsedValues(element) )
else:
print "ERROR: Your <patch> tag is not formed correctly\n"
sys.exit(1)
#print "\n\n-------------READ -----------------------------------\n\n\n"
#for Read in ReadArray:
# print Read
#print "\n\n-------------WRITE -----------------------------------\n\n\n"
#for Write in WriteArray:
# print Write
#print "\n\n-------------PATCH -----------------------------------\n\n\n"
#for Patch in PatchArray:
# print Patch
#print "------------------------------------------------\n\n\n"
def ReturnArrayFromCommaSeparatedList(sz):
temp = re.sub("\s+|\n"," ",sz)
temp = re.sub("^\s+","",temp)
temp = re.sub("\s+$","",temp)
return temp.split(',')
def find_file(filename, search_paths):
device_log("\n\n\tLooking for '%s'"%filename)
device_log("\t"+"-"*40)
for x in search_paths:
#device_log("\tSearching '%s'"%x)
temp = os.path.join(x, filename)
device_log("\tSearching for **%s**" % temp)
if os.path.exists(temp):
device_log("\n\t**Found %s (%i bytes)" % (temp,os.path.getsize(temp)))
return temp
## search cwd last
device_log("\tSearching '%s'"%os.getcwd())
if os.path.exists(filename):
device_log("\n\t**Found %s (%i bytes)" % (filename,os.path.getsize(filename)))
return filename
device_log("\tCound't find file OR perhaps you don't have permission to run os.stat() on this file\n")
return None
def DoubleCheckDiskSize():
if os.path.basename(Filename)=="singleimage.bin":
return
if noprompt is True:
return
if sys.platform.startswith("win"):
device_log("\n\nTesting of OS detected disk size correctly...\n")
Size = AvailablePartitions[Filename]
TrueSize = Size
count = 0
# Windows workaround to get the correct number of sectors
fp = open(Filename, 'rb')
fp.seek(int(Size))
try:
while True:
fp.read(SECTOR_SIZE)
if count % 128 == 0:
sys.stdout.write(".")
count += 1
except Exception, x:
TrueSize = fp.tell()
fp.close()
if TrueSize != Size and Size<=(64*1024*1024*1024):
PrintBigWarning(" ")
device_log("NOTE: This OS has *not* detected the correct size of the disk")
device_log("\nSECTORS: Size=%i, TrueSize=%i, Difference=%i sectors (%s)" % (Size/SECTOR_SIZE,TrueSize/SECTOR_SIZE,(TrueSize-Size)/SECTOR_SIZE,ReturnSizeString(TrueSize-Size)))
device_log("This means the backup GPT header will *not* be located at the true last sector")
device_log("This is only an issue if you care :) It will be off by %s" % ReturnSizeString(TrueSize-Size))
device_log("\nNOTE: This program *can't* write to the end of the disk, OS limitation")
else:
device_log("\n\nAll is well\n")
def PerformRead():
global ReadArray, search_paths, interactive, Filename
device_log("\t _ _ ")
device_log("\t | (_) ")
device_log("\t _ __ ___ __ _ __| |_ _ __ __ _ ")
device_log("\t| '__/ _ \\/ _` |/ _` | | '_ \\ / _` |")
device_log("\t| | | __/ (_| | (_| | | | | | (_| |")
device_log("\t|_| \\___|\\__,_|\\__,_|_|_| |_|\\__, |")
device_log("\t __/ |")
device_log("\t |___/ ")
CurrentSector = 0
for ReadCmd in ReadArray:
##<read filename="dump0.bin" physical_partition_number="0" start_sector="0" num_partition_sectors="34"/>
device_log("\nRead %d sectors (%s) from sector %d and save to '%s'\n" % (ReadCmd['num_partition_sectors'],ReturnSizeString(ReadCmd['num_partition_sectors']*SECTOR_SIZE),ReadCmd['start_sector'],ReadCmd['filename']))
if ReadCmd['physical_partition_number']!=0: ## msp tool can only write to PHY partition 0
device_log("WARNING '%s' for physical_partition_number=%d (only 0 is accessible) THIS MIGHT FAIL" % (ReadCmd['filename'],ReadCmd['physical_partition_number']))
if len(ReadCmd['filename'])==0:
device_log("WARNING filename was not specified, skipping this read")
continue
if ReadCmd['num_partition_sectors']==0:
device_log("WARNING num_partition_sectors was 0, skipping this read")
continue
if interactive is True:
device_log("Do you want to perform this read? (Y|n|q)",0)
loadfile = raw_input("Do you want to perform this read? (Y|n|q)")
if loadfile=='Y' or loadfile=='y' or loadfile=='':
pass
elif loadfile=='q' or loadfile=='Q':
device_log("\nmsp.py exiting by user pressing Q (quit) - Log is log_msp.txt\n\n")
sys.exit()
else:
continue
try:
if os.path.basename(Filename)=="singleimage.bin":
Filename = OutputFolder+os.path.basename(Filename)
opfile = open(Filename, "r+b") ## Filename = '\\.\PHYSICALDRIVE1'
#device_log("Opened '%s', cwd=%s" % (Filename, os.getcwd() ))
except:
PrintBigError("")
device_log("Could not open Filename=%s, cwd=%s" % (Filename, os.getcwd() ))
if sys.platform.startswith("linux"):
print "\t _ ___"
print "\t | | |__ \\"
print "\t ___ _ _ __| | ___ ) |"
print "\t/ __| | | |/ _` |/ _ \\ / /"
print "\t\\__ \\ |_| | (_| | (_) |_|"
print "\t|___/\\__,_|\\__,_|\\___/(_)\n"
device_log("\tDon't forget you need SUDO with this program")
device_log("\tsudo python msp.py partition.xml /dev/sdx (where x is the device node)")
else:
device_log("\t ___ _ _ _ _ _ ___ ")
device_log("\t / _ \\ | | (_) (_) | | | | |__ \\ ")
device_log("\t/ /_\\ \\ __| |_ __ ___ _ _ __ _ ___| |_ _ __ __ _| |_ ___ _ __ ) |")
device_log("\t| _ |/ _` | '_ ` _ \\| | '_ \\| / __| __| '__/ _` | __|/ _ \\| '__| / / ")
device_log("\t| | | | (_| | | | | | | | | | | \\__ \\ |_| | | (_| | |_| (_) | | |_| ")
device_log("\t\\_| |_/\\__,_|_| |_| |_|_|_| |_|_|___/\\__|_| \\__,_|\\__|\\___/|_| (_) \n\n")
device_log("\n"+"-"*78)
device_log("\tThis program needs to be run as Administrator!!")
device_log("-"*78+"\n")
device_log("-"*78)
device_log("\tTo fix, you must open a CMD prompt with \"Run as administrator\"")
device_log("-"*78+"\n")
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit()
device_log("\n\tOpened %s" % Filename)
if ReadCmd['start_sector'] < 0:
device_log("start sector is less than 0 - skipping this instruction, most likely for GPT HACK")
continue
if ReadCmd['start_sector'] > int(DiskSizeInBytes/SECTOR_SIZE):
PrintBigError("")
device_log("\nERROR: Start sector (%i) is BIGGER than the disk (%i sectors)" % (ReadCmd['start_sector'],int(DiskSizeInBytes/SECTOR_SIZE)))
device_log("\nERROR: Your device is TOO SMALL to handle this partition info")
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit(1)
try:
opfile.seek(int(ReadCmd['start_sector']*SECTOR_SIZE))
except:
PrintBigError("Could not move to sector %d on %s" % (ReadCmd['start_sector'],Filename))
device_log("\tMoved to sector %d on %s" % (ReadCmd['start_sector'],Filename))
size = int(ReadCmd['num_partition_sectors']*SECTOR_SIZE)
device_log("\tAttempting to read %i bytes" % (size))
try:
bytes_read = opfile.read(size)
except:
PrintBigError("Could not read %d bytes in %s" % (size,ReadCmd['filename']))
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit()
try:
opfile.close()
except:
device_log("\tWARNING: Can't close the file?")
#sys.exit()
pass
try:
ipfile = open(ReadCmd['filename'], "wb")
except:
PrintBigError("Could not create filename=%s, cwd=%s" % (ReadCmd['filename'], os.getcwd() ))
sys.exit(1)
try:
ipfile.write(bytes_read)
except:
PrintBigError("")
device_log("Could not write to %s" % (ReadCmd['filename']))
sys.exit(1)
try:
ipfile.close()
except:
device_log("\tWARNING: Can't close the file?")
#sys.exit()
pass
device_log("\nDone Reading Files\n")
def PerformWrite():
global WriteSorted, LoadSubsetOfFiles, search_paths, interactive, Filename
ThereWereWarnings = 0
device_log("\t _ ")
device_log("\t (_) ")
device_log("\t _ __ _ __ ___ __ _ _ __ __ _ _ __ ___ _ __ ___ _ _ __ __ _ ")
device_log("\t| '_ \\| '__/ _ \\ / _` | '__/ _` | '_ ` _ \\| '_ ` _ \\| | '_ \\ / _` |")
device_log("\t| |_) | | | (_) | (_| | | | (_| | | | | | | | | | | | | | | | (_| |")
device_log("\t| .__/|_| \\___/ \\__, |_| \\__,_|_| |_| |_|_| |_| |_|_|_| |_|\\__, |")
device_log("\t| | __/ | __/ |")
device_log("\t|_| |___/ |___/ ")
CurrentSector = 0
for Write in WriteSorted: # Here Write is a *sorted* entry from rawprogram.xml
if Write['physical_partition_number']!=0: ## msp tool can only write to PHY partition 0
PrintBigWarning("WARNING: '%s' for physical_partition_number=%d (only 0 is accessible) THIS MIGHT FAIL" % (Write['filename'],Write['physical_partition_number']))
device_log("WARNING '%s' for physical_partition_number=%d (only 0 is accessible) THIS MIGHT FAIL" % (Write['filename'],Write['physical_partition_number']))
device_log("WARNING '%s' for physical_partition_number=%d (only 0 is accessible) THIS MIGHT FAIL" % (Write['filename'],Write['physical_partition_number']))
device_log("WARNING '%s' for physical_partition_number=%d (only 0 is accessible) THIS MIGHT FAIL" % (Write['filename'],Write['physical_partition_number']))
if len(Write['filename'])==0:
continue
if LoadSubsetOfFiles is True:
# To be here means user only wants some of the files loaded from rawprogram0.xml
if Write['filename'] in file_list:
#device_log("LOAD: '%s' was specified to be programmed" % Write['filename'])
pass
else:
#device_log("SKIPPING: '%s', it was not specified to be programmed" % Write['filename'])
continue
device_log("\n"+"="*78)
device_log("="*78)
FileWithPath = find_file(Write['filename'], search_paths)
size=0
if FileWithPath is not None:
size = os.path.getsize(FileWithPath)
# to be here the rawprogram.xml file had to have a "filename" entry
device_log("\n'%s' (%s) to partition '%s' at sector %d (at %s)\n" % (Write['filename'],ReturnSizeString(size),Write['label'],Write['start_sector'],ReturnSizeString(Write['start_sector']*SECTOR_SIZE)))
if interactive is True:
device_log("Do you want to load this file? (Y|n|q)",0)
loadfile = raw_input("Do you want to load this file? (Y|n|q)")
if loadfile=='Y' or loadfile=='y' or loadfile=='':
pass
elif loadfile=='q' or loadfile=='Q':
device_log("\nmsp.py exiting by user pressing Q (quit) - Log is log_msp.txt\n\n")
sys.exit()
else:
continue
while FileWithPath is None:
FileNotFoundShowWarning = 1
device_log("\t______ _ _ ___ ")
device_log("\t| ___ \\ | | | | |__ \\ ")
device_log("\t| |_/ /__ _| |_| |__ ) |")
device_log("\t| __// _` | __| '_ \\ / / ")
device_log("\t| | | (_| | |_| | | | |_| ")
device_log("\t\\_| \\__,_|\\__|_| |_| (_) \n\n")
device_log("WARNING: '%s' listed in '%s' not found\n" % (Write['filename'],rawprogram_filename))
if noprompt is True:
device_log("\nUse option -s c:\\path1 -s c:\\path2 etc")
PrintBigError("")
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit(1)
device_log("Please provide a path for this file")
device_log("Ex. \\\\somepath\\folder OR c:\\somepath\\folder\n")
device_log("Enter PATH or Q to quit? ",0)
temppath = raw_input("Enter PATH or Q to quit? ")
if temppath=='Q' or temppath=='q' or temppath=='':
device_log("\nmsp.py exiting - user pressed Q (quit) - Log is log_msp.txt\n\n")
sys.exit()
device_log("\n")
FileWithPath = find_file(Write['filename'], [temppath])
size=0
if FileWithPath is not None:
size = os.path.getsize(FileWithPath)
device_log("\nShould this path be used to find other files? (Y|n|q)",0)
temp = raw_input("\nShould this path be used to find other files? (Y|n|q)")
if temp=='Q' or temp=='q':
device_log("\nmsp.py exiting - user pressed Q (quit) - Log is log_msp.txt\n\n")
sys.exit()
elif temp=='Y' or temp=='y' or temp=='':
search_paths.append(temppath)
device_log("\n")
if noprompt is False:
if size==0:
device_log("WARNING: This file is 0 bytes, do you want to load this file? (y|N|q)",0)
loadfile = raw_input("WARNING: This file is 0 bytes, do you want to load this file? (y|N|q)")
if loadfile=='N' or loadfile=='n' or loadfile=='':
continue
elif loadfile=='q' or loadfile=='Q':
device_log("\nmsp.py exiting - user pressed Q (quit) - Log is log_msp.txt\n\n")
sys.exit()
else:
pass
if Write['num_partition_sectors']==0:
Write['num_partition_sectors'] = int(size/SECTOR_SIZE)
if size%SECTOR_SIZE != 0:
Write['num_partition_sectors']+=1 # not an even multiple of SECTOR_SIZE, so ++
##device_log("At start_sector %i (%.2fKB) write %i sectors" % (Write['start_sector'],Write['start_sector']*SECTOR_SIZE/1024.0,Write['num_partition_sectors']))
##device_log("\tsize of \"%s\" is %i bytes" % (Write['filename'],size))
##device_log("\tsize of partition listed in in \"%s\" is %i bytes" % (rawprogram_filename,Write['num_partition_sectors']*SECTOR_SIZE))
## This below happens on files like partition0.bin, where they hold the entire partition table,
## but, only MBR is meant to be written, thus partition0.bin is 9 sectors but MBR is only 1 sector
if size > (Write['num_partition_sectors']*SECTOR_SIZE):
PrintBigWarning("WARNING: This complete image of size %i bytes is too big to fit on this partition of size %i bytes" % (size,Write['num_partition_sectors']*SECTOR_SIZE))
PrintBigWarning("WARNING: Only the first %i bytes of your image will be written\n\n" % (Write['num_partition_sectors']*SECTOR_SIZE))
size = Write['num_partition_sectors']*SECTOR_SIZE
ThereWereWarnings = 1
##device_log("\tAttempting to read %i bytes from \n\t\"%s\" at file_sector_offset %i" % (size,Write['filename'],Write['file_sector_offset']))
#os.getcwd()+"\\"+
try:
ipfile = open(FileWithPath, "rb")
except Exception, x:
PrintBigError("Could not open FileWithPath=%s, cwd=%s\nREASON: %s" % (Write['filename'], os.getcwd(), x ))
device_log("\tAttempting to move to sector %i (file file_sector_offset) in %s" % (Write['file_sector_offset'],Write['filename']))
try:
ipfile.seek(int(Write['file_sector_offset']*SECTOR_SIZE))
except Exception, x:
PrintBigError("Could not move to sector %d in %s\nREASON: %s" % (Write['file_sector_offset'],Write['filename'],x))
device_log("\tAttempting to read %i bytes" % (size))
try:
if size<MAX_FILE_SIZE_BEFORE_SPLIT:
bytes_read = ipfile.read(size)
else:
device_log("File is too large to read all at once, must be broken up")
except Exception, x:
PrintBigError("Could not read %d bytes in %s\nREASON: %s" % (size,Write['filename'],x))
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit()
if size<MAX_FILE_SIZE_BEFORE_SPLIT:
ipfile.close()
if size<MAX_FILE_SIZE_BEFORE_SPLIT:
device_log("\tSuccessfully read %d bytes of %d bytes and closed %s" % (len(bytes_read),size,Write['filename']))
Remainder = len(bytes_read)%SECTOR_SIZE
if Remainder != 0:
device_log("\tbytes_read is not a multiple of SECTOR_SIZE (%d bytes), appending zeros" % SECTOR_SIZE)
Bytes = struct.unpack("%dB" % len(bytes_read),bytes_read) ## unpack returns list, so get index 0
Temp = list(Bytes) + [0x00]*(SECTOR_SIZE-Remainder) # concat
TotalSize = len(Temp)
bytes_read = struct.pack("%dB" % TotalSize, *Temp)
device_log("\tNow len(bytes_read)=%d" % len(bytes_read))
# At this point bytes_read is a multiple of SECTOR_SIZE
#device_log("\t\tNeed to move to location %i (%i bytes) in %s" % (Write['start_sector'],(Write['start_sector']*SECTOR_SIZE),Filename))
#device_log("\t\tPartition['start_sector']*SECTOR_SIZE = %i" % (Write['start_sector']*SECTOR_SIZE))
if (2*DiskSizeInBytes)<Write['start_sector'] and os.path.basename(Filename)!="singleimage.bin":
device_log("2*DiskSizeInBytes=%d" % (2*DiskSizeInBytes))
device_log("Write['start_sector']=%i"%Write['start_sector'])
PrintBigError("Attempting to move to sector %i (%.2f MB) and only %i sectors (%.2f MB) exist (%i difference (%.2f MB) )" % (Write['start_sector'],Write['start_sector']*SECTOR_SIZE/1024.0,2*DiskSizeInBytes,DiskSizeInBytes/1024.0,Write['start_sector']-(2*DiskSizeInBytes),(Write['start_sector']-(2*DiskSizeInBytes))/2048.0))
try:
if os.path.basename(Filename)=="singleimage.bin":
Filename = OutputFolder+os.path.basename(Filename)
opfile = open(Filename, "r+b") ## Filename = '\\.\PHYSICALDRIVE1'
except Exception, x:
PrintBigError("")
device_log("Could not open Filename=%s, cwd=%s" % (Filename, os.getcwd() ))
device_log("REASON: %s" % (x))
if sys.platform.startswith("linux"):
print "\t _ ___"
print "\t | | |__ \\"
print "\t ___ _ _ __| | ___ ) |"
print "\t/ __| | | |/ _` |/ _ \\ / /"
print "\t\\__ \\ |_| | (_| | (_) |_|"
print "\t|___/\\__,_|\\__,_|\\___/(_)\n"
device_log("\tDon't forget you need SUDO with this program")
device_log("\tsudo python msp.py partition.xml /dev/sdx (where x is the device node)")
else:
device_log("\t ___ _ _ _ _ _ ___ ")
device_log("\t / _ \\ | | (_) (_) | | | | |__ \\ ")
device_log("\t/ /_\\ \\ __| |_ __ ___ _ _ __ _ ___| |_ _ __ __ _| |_ ___ _ __ ) |")
device_log("\t| _ |/ _` | '_ ` _ \\| | '_ \\| / __| __| '__/ _` | __|/ _ \\| '__| / / ")
device_log("\t| | | | (_| | | | | | | | | | | \\__ \\ |_| | | (_| | |_| (_) | | |_| ")
device_log("\t\\_| |_/\\__,_|_| |_| |_|_|_| |_|_|___/\\__|_| \\__,_|\\__|\\___/|_| (_) \n\n")
device_log("\n"+"-"*78)
device_log("\tThis program needs to be run as Administrator!!")
device_log("-"*78+"\n")
device_log("-"*78)
device_log("\tTo fix, you must open a CMD prompt with \"Run as administrator\"")
device_log("-"*78+"\n")
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit()
device_log("opfile = open('%s', 'r+b') , cwd=%s" % (Filename, os.getcwd() ))
device_log("\n\tOpened %s" % Filename)
if Write['start_sector'] < 0:
device_log("start sector is less than 0 - skipping this instruction, most likely for GPT HACK")
continue
if Write['start_sector'] > int(DiskSizeInBytes/SECTOR_SIZE):
PrintBigError("")
device_log("\nERROR: Start sector (%i) is BIGGER than the disk (%i sectors)" % (Write['start_sector'],int(DiskSizeInBytes/SECTOR_SIZE)))
device_log("\nERROR: Your device is TOO SMALL to handle this partition info")
device_log("\nmsp.py failed - Log is log_msp.txt\n\n")
sys.exit(1)
if int(Write['start_sector']) > 0:
try:
opfile.seek(int(Write['start_sector']*SECTOR_SIZE))
except Exception, x:
PrintBigError("Could not move to sector %d on %s" % (Write['start_sector'],Filename))
device_log("REASON: %s" % (x))
device_log("\tMoved to sector %d on %s" % (Write['start_sector'],Filename))
CurrentSector = Write['start_sector']
##device_log("size=",size)
##device_log("MAX_FILE_SIZE_BEFORE_SPLIT=",MAX_FILE_SIZE_BEFORE_SPLIT)
CurrentSector += (size/SECTOR_SIZE)
if size<MAX_FILE_SIZE_BEFORE_SPLIT:
device_log("\tFile can be written completely.")
device_log("\tCalling opfile.write(bytes_read)")
try:
opfile.write(bytes_read)
except Exception, x:
PrintBigError("")
device_log("Could not write %d bytes to %s" % (len(bytes_read),Filename))
device_log("REASON: %s" % (x))
device_log("\nPlease try removing the medium and re-inserting it")
device_log("Strangly this helps sometimes after writing *new* partition tables\n\n")
#traceback.print_exc(file=sys.stdout)
#traceback.print_exc()
sys.exit(1)
else:
## To be here means I need to break up the file
##device_log("I need to break up this file")
TempSize = size
NumLoop = int(TempSize/MAX_FILE_SIZE_BEFORE_SPLIT)
Remainder = size%MAX_FILE_SIZE_BEFORE_SPLIT
if Remainder>0:
Remainder=1
device_log("\nNeed to break up this file, will loop %d times writing %i bytes each time" % (NumLoop+Remainder,MAX_FILE_SIZE_BEFORE_SPLIT))
TempSize=0
for a in range(NumLoop):
#device_log("read %i bytes" % MAX_FILE_SIZE_BEFORE_SPLIT)
try:
bytes_read = ipfile.read(MAX_FILE_SIZE_BEFORE_SPLIT)
except Exception, x:
PrintBigError("Could not read from %s\nREASON: %s" % (FileWithPath,x))
##device_log("\n\t%i) Packing %i Bytes [%i:%i]" % (a+1,MAX_FILE_SIZE_BEFORE_SPLIT,TempSize,TempSize+MAX_FILE_SIZE_BEFORE_SPLIT))
##bytes_read = struct.pack("%dB" % MAX_FILE_SIZE_BEFORE_SPLIT, *Bytes[TempSize:(TempSize+MAX_FILE_SIZE_BEFORE_SPLIT)])
device_log("\t%.2i) Writing %i Bytes [%i:%i]" % (a+1,MAX_FILE_SIZE_BEFORE_SPLIT,TempSize,TempSize+MAX_FILE_SIZE_BEFORE_SPLIT))
try:
opfile.write(bytes_read)
except Exception, x:
PrintBigError("Could not write to %s\nREASON: %s" % (Filename,x))
TempSize += MAX_FILE_SIZE_BEFORE_SPLIT
##device_log("Out of loop")
a+=1
if Remainder == 1:
# Need to PAD the file to be a multiple of SECTOR_SIZE bytes too
#device_log("\n\t%i) Packing %i Bytes [%i:%i]" % (a,(len(Bytes)-TempSize),TempSize,len(Bytes)))
#bytes_read = struct.pack("%dB" % (len(Bytes)-TempSize), *Bytes[TempSize:len(Bytes)])
device_log("\t%.2i) Writing %i Bytes [%i:%i]" % (a+1,(size-TempSize),TempSize,size))
try:
bytes_read = ipfile.read(size-TempSize)
except Exception, x:
PrintBigError("Could not read from %s\nREASON: %s" % (FileWithPath,x))
##device_log("len(bytes_read)=",len(bytes_read))
Remainder = len(bytes_read)%SECTOR_SIZE
if Remainder != 0:
device_log("\tbytes_read is not a multiple of SECTOR_SIZE (%d bytes), appending zeros" % SECTOR_SIZE)
Bytes = struct.unpack("%dB" % len(bytes_read),bytes_read) ## unpack returns list, so get index 0
Temp = list(Bytes) + [0x00]*(SECTOR_SIZE-Remainder) # concat
TotalSize = len(Temp)
bytes_read = struct.pack("%dB" % TotalSize, *Temp)
device_log("\tNow len(bytes_read)=%d" % len(bytes_read))
# At this point bytes_read is a multiple of SECTOR_SIZE
#device_log("This is the final write")
try:
opfile.write(bytes_read)
except Exception, x:
PrintBigError("Could not write to %s\nREASON: %s" % (Filename,x))
ipfile.close()
if os.path.basename(Filename)=="singleimage.bin":
device_log("\tSingleImageSize %i bytes (%i sectors)" % (CurrentSector*SECTOR_SIZE,CurrentSector))
device_log("\tCurrentSector=%i" % CurrentSector)
device_log("\tDiskSize=%i sectors" % int(DiskSizeInBytes/SECTOR_SIZE))
#device_log("\tWrote %d bytes at sector %d on %s" % (len(bytes_read),Write['start_sector'],Filename))
try:
##print opfile
opfile.close()
except Exception, x:
device_log("\tWARNING: Can't close the file?")
device_log("REASON: %s" % (x))
#sys.exit()
pass
device_log("\n\tWritten with")
device_log("\tpython dd.py --if=%s --bs=%i --count=%i --seek=%i --of=%s" % (FileWithPath,SECTOR_SIZE,int((size-1)/SECTOR_SIZE)+1,Write['start_sector'],Filename))
device_log("\n\tVerify with")
device_log("\tpython dd.py --if=%s --bs=%i --count=%i --skip=%i --of=dump.bin" % (Filename,SECTOR_SIZE,int((size-1)/SECTOR_SIZE)+1,Write['start_sector']))
device_log("\n\tSuccessfully wrote \"%s\" (%s payload) to %s" % (Write['filename'],ReturnSizeString(size),Filename))
#raw_input("Enter something: ")
#if Write['filename']=="sbl3.mbn":
# sys.exit()
if os.path.basename(Filename)=="singleimage.bin":
if CurrentSector < int(DiskSizeInBytes/SECTOR_SIZE):
device_log("\n\nSingleImageSize %i bytes (%i sectors)" % (CurrentSector*SECTOR_SIZE,CurrentSector))
device_log("CurrentSector=%i" % CurrentSector)
device_log("DiskSizeInBytes=%i sectors" % int(DiskSizeInBytes/SECTOR_SIZE))
device_log("\nDone Writing Files\n")
return ThereWereWarnings
def GetPartitions():
global Devices,AvailablePartitions
if sys.platform.startswith("linux"):
#device_log("This is a linux system since sys.platform='%s'" % sys.platform)
device_log("-"*78 )
device_log("\tRemember - DON'T FORGET SUDO")
device_log("\tRemember - DON'T FORGET SUDO")
device_log("\tRemember - DON'T FORGET SUDO")
device_log("-"*78+"\n")
os.system("cat /proc/partitions > temp_partitions.txt")
IN = open("temp_partitions.txt")
output = IN.readlines()
for line in output:
#print line
m = re.search("(\d+) (sd[a-z])$", line)
if type(m) is not NoneType:
Size = int(m.group(1))
Device = "/dev/"+m.group(2)
#device_log("%s\tSize=%d,%.1fMB (%.2fGB) (%iKB)" % (Device,Size,int(Size)/1024.0,int(Size)/(1024.0*1024.0),int(Size))
AvailablePartitions[Device] = Size*1024.0 # linux reports in terms of 1024,
else:
##device_log("This is a windows system since sys.platform='%s'" % sys.platform
device_log("\t ___ _ _ _ _ _ ___ ")
device_log("\t / _ \\ | | (_) (_) | | | | |__ \\ ")
device_log("\t/ /_\\ \\ __| |_ __ ___ _ _ __ _ ___| |_ _ __ __ _| |_ ___ _ __ ) |")
device_log("\t| _ |/ _` | '_ ` _ \\| | '_ \\| / __| __| '__/ _` | __|/ _ \\| '__| / / ")
device_log("\t| | | | (_| | | | | | | | | | | \\__ \\ |_| | | (_| | |_| (_) | | |_| ")
device_log("\t\\_| |_/\\__,_|_| |_| |_|_|_| |_|_|___/\\__|_| \\__,_|\\__|\\___/|_| (_) \n")
device_log("-"*78 )
device_log("\tRemember - Under Win7 you must run this as Administrator")
device_log("-"*78)
response = external_call('wmic DISKDRIVE get DeviceID, MediaType, Model, Size')
m = re.search("Access is denied", response)
if type(m) is not NoneType:
PrintBigError("This computer does not have correct privileges, you need administrator group privilege\n")
device_log("\n"+response)
response = response.replace('\r', '').strip("\n").split("\n")[1:]
for line in response:
m = re.search("(PHYSICALDRIVE\d+).+ (\d+) ", line)
if type(m) is not NoneType:
Size = int(m.group(2)) # size in bytes
Device = "\\\\.\\"+m.group(1) # \\.\PHYSICALDRIVE1
AvailablePartitions[Device] = Size
Devices = AvailablePartitions.keys()
Devices.sort()
device_log("--------------------------------Partitions Detected--------------------------------------")
for device in Devices:
value = AvailablePartitions[device]
if value/(1024.0*1024.0*1024.0) > 31.0:
device_log("%s %s\tsectors:%i <--- Not likely an SD card, careful!" % (device,ReturnSizeString(value),value/SECTOR_SIZE) )
else:
device_log("%s %s\tsectors:%i" % (device,ReturnSizeString(value),value/SECTOR_SIZE))
device_log("-"*78+"\n")
def PerformPatching():
global PatchArray,Patching
device_log("\t _ _ _ ")
device_log("\t | | | | (_) ")
device_log("\t _ __ __ _| |_ ___| |__ _ _ __ __ _ ")
device_log("\t| '_ \\ / _` | __|/ __| '_ \\| | '_ \\ / _` |")
device_log("\t| |_) | (_| | |_| (__| | | | | | | | (_| |")
device_log("\t| .__/ \\__,_|\\__|\\___|_| |_|_|_| |_|\\__, |")
device_log("\t| | __/ |")
device_log("\t|_| |___/ ")
var = 'Y'
if Patching == "DISK":
var = 'N' ## user must authorize this
## PATCHING HAPPENS HERE - PATCHING HAPPENS HERE - PATCHING HAPPENS HERE
for Patch in PatchArray:
if Patch['physical_partition_number']!=0: ## msp tool can only write to PHY partition 0
device_log("WARNING '%s' for physical_partition_number=%d (only 0 is accessible) - THIS MIGHT FAIL" % (Patch['filename'],Patch['physical_partition_number']))
if Patching == "DISK":
## to be here means user wants to patch the actual disk
if Patch['filename'] == "DISK":
pass ## all is well, want to patch DISK, and this is DISK
else:
continue ## this was filename, so skip it
else:
## to be here means were patching files, not the disk
if Patch['filename'] == "DISK":
continue ## want to patch FILES, but this was a DISK, so skip it