-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnuwriter.py
2606 lines (2296 loc) · 95.2 KB
/
nuwriter.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
# NOTE: This script is test under Python 3.x
__copyright__ = "Copyright (C) 2020~2021 Nuvoton Technology Corp. All rights reserved"
__version__ = "v0.37"
import os
import sys
import argparse
import json
import crcmod
from Crypto.Cipher import AES
import hashlib
import ecdsa
import binascii
from datetime import datetime
import random
import shutil
from tqdm import tqdm
from xusbcom import XUsbComList
from concurrent.futures import ThreadPoolExecutor, as_completed
from UnpackImage import UnpackImage
from collections import namedtuple
from struct import unpack
import time
import platform
# for debug
import usb.core
import usb.util
ACK = 0x55AA55AA
TRANSFER_SIZE = 4096
MAX_HEADER_IMG = 4
# SPI NOR align for erase/program starting address
SPINOR_ALIGN = 4096
# Storage device type
DEV_DDR_SRAM = 0
DEV_NAND = 1
DEV_SD_EMMC = 2
DEV_SPINOR = 3
DEV_SPINAND = 4
DEV_OTP = 6
DEV_USBH = 7
DEV_USBD = 8
DEV_UNKNOWN = 0xFF
# For OTP programming
ACT_LOAD = 1
ACT_WRITE = 2
ACT_ERASE = 3
ACT_READ = 4
ACT_MSC = 5
# Command options
OPT_NONE = 0
OPT_SCRUB = 1 # For erase, use with care
OPT_WITHBAD = 1 # For read
OPT_EXECUTE = 2 # For write
OPT_VERIFY = 3 # For write
OPT_UNPACK = 4 # For pack
OPT_RAW = 5 # For write
OPT_EJECT = 6 # For msc
OPT_STUFF = 7 # For stuff pack, output could be used by dd command
OPT_SETINFO = 8 # For set storage info for attach
OPT_CONCAT = 9 # For convert, concatenate at the end of encrypted data file
OPT_SHOWHDR = 10 # For convert. Instead of convert, show header content instead
OPT_NOCRC = 11 # For pack. unpack file without crc32 check
OPT_CONVOTP = 12 # For convert. convert otp.json to otp.bin
OPT_DDR_INIT = 1 # For ddr
OPT_DDR_800 = 2 # For ddr, ddr_pll
OPT_DDR_667 = 3 # For ddr, ddr_pll
OPT_UNKNOWN = 0xFF # Error
# OPT block definitions
OPT_OTPBLK1 = 0x100
OPT_OTPBLK2 = 0x200
OPT_OTPBLK3 = 0x400
OPT_OTPBLK4 = 0x800
OPT_OTPBLK5 = 0x1000
OPT_OTPBLK6 = 0x2000
OPT_OTPBLK7 = 0x4000
OPT_OTPKEY = 0x8000
# for key lock
OPT_OTPKEY0 = 0x10000
OPT_OTPKEY1 = 0x20000
OPT_OTPKEY2 = 0x40000
OPT_OTPKEY3 = 0x80000
OPT_OTPKEY4 = 0x100000
OPT_OTPKEY5 = 0x200000
OPT_OTPKEY6 = 0x400000
OPT_OTPKEY7 = 0x800000
OPT_OTPKEY8 = 0x1000000
# Image type definitions
IMG_DATA = 0
IMG_TFA = 1
IMG_UBOOT = 2
IMG_LINUX = 3
IMG_DDR = 4
IMG_TEE = 5
IMG_DTB = 6
# If attach is a must. maybe better for real chip.
# devices = []
mp_mode = False
WINDOWS_PATH = "C:\\Program Files (x86)\\Nuvoton Tools\\NuWriter\\"
LINUX_PATH = "/usr/share/nuwriter/"
def switch_mp_mode(flag):
global mp_mode
mp_mode = not mp_mode
def conv_env(env_file_name, blk_size) -> bytearray:
try:
with open(env_file_name, "r") as env_file:
env_data = env_file.read().splitlines()
except (IOError, OSError) as err:
print(f"Open {env_file_name} failed")
sys.exit(err)
out = bytearray(4) # Reserved for CRC
for lines in env_data:
out += bytes(lines, 'ascii')
out += b'\x00'
out += b'\x00'
out += b'\xFF' * (blk_size - len(out))
crc32_func = crcmod.predefined.mkCrcFun('crc-32')
checksum = crc32_func(out[4:])
out[0:4] = checksum.to_bytes(4, byteorder="little")
return out
def get_dpm(dpm) -> int:
return {
'a35sdsdis': 0x00000001,
'a35sdslock': 0x00000002,
'a35sndsdis': 0x00000004,
'a35sndslock': 0x00000008,
'a35nsdsdis': 0x00000010,
'a35nsdslock': 0x00000020,
'a35nsndsdis': 0x00000040,
'a35nsndslock': 0x00000080,
'm4dsdis': 0x00000100,
'm4dslock': 0x00000200,
'm4ndsdis': 0x00000400,
'm4ndslock': 0x00000800,
'extdis': 0x00001000,
'extlock': 0x00002000,
'exttdis': 0x00004000,
'exttlock': 0x00008000,
'giccfgsdis': 0x00010000,
'giccfgslock': 0x00020000
}.get(dpm, 0)
def get_plm(plm) -> int:
return {
'oem': 0x1,
'deploy': 0x3,
'rma': 0x7,
'prma': 0xF
}.get(plm, 0)
def conv_otp(opt_file_name) -> (bytearray, int):
try:
with open(opt_file_name, "r") as json_file:
try:
d = json.load(json_file)
except json.decoder.JSONDecodeError as err:
print(f"{opt_file_name} parsing error")
sys.exit(err)
except (IOError, OSError) as err:
print(f"Open {opt_file_name} failed")
sys.exit(err)
# Bootcfg, DPM, PLM, and PWD 4 bytes each, MAC addr 8 bytes each, sec/nsec 88 bytes each
data = bytearray(208)
option = 0
for key in d.keys():
if key == 'boot_cfg':
cfg_val = 0
for sub_key in d['boot_cfg'].keys():
if sub_key == 'posotp':
if d['boot_cfg']['posotp'] == 'enable':
cfg_val |= 1
if sub_key == 'qspiclk':
if d['boot_cfg']['qspiclk'] == '50mhz':
cfg_val |= 2
if sub_key == 'wdt1en':
if d['boot_cfg']['wdt1en'] == 'enable':
cfg_val |= 4
if sub_key == 'uart0en':
if d['boot_cfg']['uart0en'] == 'disable':
cfg_val |= 0x10
if sub_key == 'sd0bken':
if d['boot_cfg']['sd0bken'] == 'enable':
cfg_val |= 0x20
if sub_key == 'tsiimg':
if d['boot_cfg']['tsiimg'] == 'enable':
cfg_val |= 0x40
if sub_key == 'tsidbg':
if d['boot_cfg']['tsidbg'] == 'disable':
cfg_val |= 0x80
if sub_key == 'boot_iovol':
if d['boot_cfg']['boot_iovol'] == '1_8v':
cfg_val |= 0x200
if sub_key == 'bootsrc':
if d['boot_cfg']['bootsrc'] == 'sd' or d['boot_cfg']['bootsrc'] == 'emmc':
cfg_val |= 0x400
elif d['boot_cfg']['bootsrc'] == 'nand':
cfg_val |= 0x800
elif d['boot_cfg']['bootsrc'] == 'usb':
cfg_val |= 0xC00
if sub_key == 'page':
if d['boot_cfg']['page'] == '2k':
cfg_val |= 0x1000
elif d['boot_cfg']['page'] == '4k':
cfg_val |= 0x2000
elif d['boot_cfg']['page'] == '8k':
cfg_val |= 0x3000
if sub_key == 'option':
if d['boot_cfg']['option'] == 'sd1' or d['boot_cfg']['option'] == 'emmc1' or \
d['boot_cfg']['option'] == 't12' or d['boot_cfg']['option'] == 'spinand4':
cfg_val |= 0x4000
elif d['boot_cfg']['option'] == 't24' or d['boot_cfg']['option'] == 'spinor1':
cfg_val |= 0x8000
elif d['boot_cfg']['option'] == 'noecc' or d['boot_cfg']['option'] == 'spinor4':
cfg_val |= 0xC000
if sub_key == 'secboot':
if d['boot_cfg']['secboot'] == 'disable':
cfg_val |= 0x5A000000
data[0:4] = cfg_val.to_bytes(4, byteorder='little')
option |= OPT_OTPBLK1
elif key == 'dpm_plm':
for sub_key in d['dpm_plm'].keys():
if sub_key == 'dpm':
dpm_val = 0
for dpm_key in d['dpm_plm']['dpm'].keys():
dpm_val |= get_dpm(dpm_key)
if dpm_val != 0:
data[4:8] = dpm_val.to_bytes(4, byteorder='little')
elif sub_key == 'plm':
plm_val = get_plm(d['dpm_plm']['plm'])
if plm_val != 0:
data[8:12] = plm_val.to_bytes(4, byteorder='little')
option |= OPT_OTPBLK2
elif key == 'mac0':
if len(bytes.fromhex(d['mac0'])) != 6:
print("mac0 is 6 bytes, please check the size")
sys.exit(2)
data[12:18] = bytes.fromhex(d['mac0'])
option |= OPT_OTPBLK3
elif key == 'mac1':
if len(bytes.fromhex(d['mac1'])) != 6:
print("mac1 is 6 bytes, please check the size")
sys.exit(2)
data[20:26] = bytes.fromhex(d['mac1'])
option |= OPT_OTPBLK4
elif key == 'dplypwd':
if len(bytes.fromhex(d['dplypwd'])) != 4:
print("dplypwd is 4 bytes, please check the size")
sys.exit(2)
data[28:32] = bytes.fromhex(d['dplypwd'])
option |= OPT_OTPBLK5
elif key == 'sec':
if len(bytes.fromhex(d['sec'])) > 88:
print("sec at most 88 bytes, please check the size")
sys.exit(2)
newkey = bytes.fromhex(d['sec'])
newkey += b'\x00' * (88 - len(newkey))
data[32:120] = newkey
option |= OPT_OTPBLK6
elif key == 'nonsec':
if len(bytes.fromhex(d['nonsec'])) > 88:
print("nonsec at most 88 bytes, please check the size")
sys.exit(2)
newkey = bytes.fromhex(d['nonsec'])
newkey += b'\x00' * (88 - len(newkey))
data[120:208] = newkey
option |= OPT_OTPBLK7
elif key == 'huk0':
newkey = bytes.fromhex(d['huk0']['key'])
if len(newkey) != 16:
print("HUK0 is 128-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 128-bit
newkey += b'\x08\x00\x00\x00'
# key number - 0
newkey += b'\x00\x00\x00\x00'
# meta - owner: cpu, cpu readable
newkey += b'\x04\x00\x05\x80'
data += newkey
elif key == 'huk1':
newkey = bytes.fromhex(d['huk1']['key'])
if len(newkey) != 16:
print("HUK1 is 128-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 128-bit
newkey += b'\x08\x00\x00\x00'
# key number - 1
newkey += b'\x01\x00\x00\x00'
# meta - owner: cpu, cpu readable
newkey += b'\x04\x00\x05\x80'
data += newkey
elif key == 'huk2':
newkey = bytes.fromhex(d['huk2']['key'])
if len(newkey) != 16:
print("HUK0 is 128-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 128-bit
newkey += b'\x08\x00\x00\x00'
# key number - 2
newkey += b'\x02\x00\x00\x00'
# meta - owner: cpu, cpu readable
newkey += b'\x04\x00\x05\x80'
data += newkey
elif key == 'key3':
newkey = bytes.fromhex(d['key3']['key'])
if len(newkey) != 32:
print("key3 is 256-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 256-bit
newkey += b'\x00\x01\x00\x00'
# key number - 3
newkey += b'\x03\x00\x00\x00'
if d['key3']['meta'] == 'aes256-unreadable':
newkey += b'\x00\x06\x00\x80'
elif d['key3']['meta'] == 'aes256-cpu-readable':
newkey += b'\x04\x06\x00\x80'
elif d['key3']['meta'] == 'sha256-unreadable':
newkey += b'\x00\x06\x01\x80'
elif d['key3']['meta'] == 'sha256-cpu-readable':
newkey += b'\x04\x06\x01\x80'
elif d['key3']['meta'] == 'eccp256-unreadable':
newkey += b'\x00\x06\x04\x80'
elif d['key3']['meta'] == 'eccp256-cpu-readable':
newkey += b'\x04\x06\x04\x80'
data += newkey
elif key == 'key4':
newkey = bytes.fromhex(d['key4']['key'])
if len(newkey) != 32:
print("key4 is 256-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 256-bit
newkey += b'\x00\x01\x00\x00'
# key number - 4
newkey += b'\x04\x00\x00\x00'
if d['key4']['meta'] == 'aes256-unreadable':
newkey += b'\x00\x06\x00\x80'
elif d['key4']['meta'] == 'aes256-cpu-readable':
newkey += b'\x04\x06\x00\x80'
elif d['key4']['meta'] == 'sha256-unreadable':
newkey += b'\x00\x06\x01\x80'
elif d['key4']['meta'] == 'sha256-cpu-readable':
newkey += b'\x04\x06\x01\x80'
elif d['key4']['meta'] == 'eccp256-unreadable':
newkey += b'\x00\x06\x04\x80'
elif d['key4']['meta'] == 'eccp256-cpu-readable':
newkey += b'\x04\x06\x04\x80'
data += newkey
elif key == 'key5':
newkey = bytes.fromhex(d['key5']['key'])
if len(newkey) != 32:
print("key5 is 256-bit")
sys.exit(2)
newkey += b'\x00' * (32 - len(newkey))
# size - 256-bit
newkey += b'\x00\x01\x00\x00'
# key number - 5
newkey += b'\x05\x00\x00\x00'
if d['key5']['meta'] == 'aes256-unreadable':
newkey += b'\x00\x06\x00\x80'
elif d['key5']['meta'] == 'aes256-cpu-readable':
newkey += b'\x04\x06\x00\x80'
elif d['key5']['meta'] == 'sha256-unreadable':
newkey += b'\x00\x06\x01\x80'
elif d['key5']['meta'] == 'sha256-cpu-readable':
newkey += b'\x04\x06\x01\x80'
elif d['key5']['meta'] == 'eccp256-unreadable':
newkey += b'\x00\x06\x04\x80'
elif d['key5']['meta'] == 'eccp256-cpu-readable':
newkey += b'\x04\x06\x04\x80'
data += newkey
elif key == 'publicx':
newkey = bytes.fromhex(d['publicx'])
if len(newkey) != 32:
print("IBR publicx is 256-bit")
sys.exit(2)
data += bytes.fromhex(d['publicx'])
data += b'\x00\x01\x00\x00' # 256 bits
data += b'\x06\x00\x00\x00'
data += b'\x01\x06\x04\x80'
elif key == 'publicy':
newkey = bytes.fromhex(d['publicy'])
if len(newkey) != 32:
print("IBR publicy is 256-bit")
sys.exit(2)
data += bytes.fromhex(d['publicy'])
data += b'\x00\x01\x00\x00' # 256 bits
data += b'\x07\x00\x00\x00'
data += b'\x01\x06\x04\x80'
elif key == 'aeskey':
newkey = bytes.fromhex(d['aeskey'])
if len(newkey) != 32:
print("IBR aeskey is 256-bit")
sys.exit(2)
data += bytes.fromhex(d['aeskey'])
data += b'\x00\x01\x00\x00' # 256 bits
data += b'\x08\x00\x00\x00'
data += b'\x01\x06\x00\x80'
try:
with open("otp_data.bin", "wb") as out_file:
out_file.write(data[0:len(data)])
except (IOError, OSError) as err:
print(f"Open otp_data.bin failed")
sys.exit(err)
if len(data) > 208:
option |= OPT_OTPKEY
return data, option
def __img_erase(dev, media, start, length, option) -> int:
nand_align, spinand_align, npage, nblock, nbcnt, noob, snpage, snblock, snbcnt, snoob, emmc_block = dev.get_align()
if (media == DEV_NAND and nand_align == 0) or \
(media == DEV_SPINAND and spinand_align == 0):
print("Unable to get block size")
return -1
if (media == DEV_NAND and start % nand_align != 0) or\
(media == DEV_SPINAND and start % spinand_align != 0) or \
(media == DEV_SD_EMMC and start % 512 != 0) or \
(media == DEV_SPINOR and start % SPINOR_ALIGN != 0):
print("Starting address must be block aligned")
return -1
cmd = start.to_bytes(8, byteorder='little')
cmd += length.to_bytes(8, byteorder='little')
cmd += ACT_ERASE.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(media)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
bar = tqdm(total=100, position=dev.get_id(), ascii=True, bar_format='{l_bar}{bar:10}{bar:-10b}')
previous_progress = 0
while True:
# xusb ack with total erase progress.
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") <= 100:
bar.update(int.from_bytes(ack, byteorder="little") - previous_progress)
previous_progress = int.from_bytes(ack, byteorder="little")
if int.from_bytes(ack, byteorder="little") == 100:
break
bar.close()
return 0
# default erase all (count=0)
def do_img_erase(media, start, length=0, option=OPT_NONE) -> None:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
with ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(__img_erase, dev, media, start, length, option) for dev in devices]
success = 0
failed = 0
for future in as_completed(futures):
if future.result() == 0:
success += 1
else:
failed += 1
print(f"Successfully erased {success} device(s)")
if failed > 0:
print(f"Failed to erase {failed} device(s)")
def do_otp_erase(option) -> None:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
start = 0
length = 0
dev = devices[0]
load_otp_writer(dev)
cmd = start.to_bytes(8, byteorder='little')
cmd += length.to_bytes(8, byteorder='little')
cmd += ACT_ERASE.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(DEV_OTP)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
print(f"Failed to erase device(s)")
# There's no way to tell the progress...
ack = dev.read(4)
data = int.from_bytes(ack, byteorder="little")
if option == 0x100:
data >>= 2
data &= 0x3
if option == 0x400:
data >>= 6
data &= 0x3
if option == 0x800:
data >>= 8
data &= 0x3
if option & 0x8000:
data >>= 16
#print(f"Erase count state {hex(data)}")
print(f"Successfully erased device(s)")
def load_otp_writer(dev) -> int:
try:
with open("otp_writer.bin", "rb") as writer_file:
otp_writer = writer_file.read()
except (IOError, OSError) as err:
print(f"Open {opt_file_name} failed")
sys.exit(err)
option = 0
img_length = len(otp_writer)
cmd = b'\x00\x00\xf0\x86\x00\x00\x00\x00'
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_LOAD.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(DEV_OTP)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
for offset in range(0, img_length, TRANSFER_SIZE):
xfer_size = TRANSFER_SIZE if offset + TRANSFER_SIZE < img_length else img_length - offset
dev.write(otp_writer[offset: offset + xfer_size])
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != xfer_size:
print("Acked size error")
return -1
while True:
# wait TSI update firmware
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") == ACK:
break
return 0
def __otp_program(dev, otp_data, option) -> int:
img_length = len(otp_data)
cmd = b'\x00\x00\xf0\x86\x00\x00\x00\x00'
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_WRITE.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(DEV_OTP)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
# There's no way to tell the progress...
dev.write(otp_data)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != img_length:
print("Acked size error")
return -1
# There's no way to tell the progress...
ack = dev.read(4)
data = int.from_bytes(ack, byteorder="little")
#print(f"Can program count {hex(data)}")
return 0
def do_otp_program(opt_file_name) -> None:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
load_otp_writer(devices[0])
otp_data, option = conv_otp(opt_file_name)
with ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(__otp_program, dev, otp_data, option) for dev in devices]
success = 0
failed = 0
for future in as_completed(futures):
if future.result() == 0:
success += 1
else:
failed += 1
print(f"Successfully programmed {success} device(s)")
if failed > 0:
print(f"Failed to program {failed} device(s)")
def do_otp_read(media, start, out_file_name, length=0x1, option=OPT_NONE) -> None:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
# Only support one device in read function
dev = devices[0]
load_otp_writer(dev)
cmd = start.to_bytes(8, byteorder='little')
cmd += length.to_bytes(8, byteorder='little')
cmd += ACT_READ.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(media)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return
# FIXME: Don't know real length for "read all"
bar = tqdm(total=length, ascii=True, bar_format='{l_bar}{bar:10}{bar:-10b}')
data = b''
remain = length
while remain > 0:
ack = dev.read(4)
# Get the transfer length of next read
xfer_size = int.from_bytes(ack, byteorder="little")
data += dev.read(xfer_size)
dev.write(xfer_size.to_bytes(4, byteorder='little')) # ack
remain -= xfer_size
bar.update(xfer_size)
try:
with open(out_file_name, "wb") as out_file:
out_file.write(data[0:length])
except (IOError, OSError) as err:
print(f"Open {out_file_name} failed")
sys.exit(err)
bar.close()
def __pack_program(dev, media, pack_image, option) -> int:
nand_align, spinand_align, npage, nblock, nbcnt, noob, snpage, snblock, snbcnt, snoob, emmc_block = dev.get_align()
image_cnt = pack_image.img_count()
if (media == DEV_NAND and nand_align == 0) or \
(media == DEV_SPINAND and spinand_align == 0):
print("Unable to get block size")
return -1
for i in range(image_cnt):
img_length, img_start, img_type = pack_image.img_attr(i)
if (media == DEV_NAND and img_start % nand_align != 0) or \
(media == DEV_SPINAND and img_start % spinand_align != 0) or \
(media == DEV_SPINOR and img_start % SPINOR_ALIGN != 0):
print("Starting address must be block aligned")
return -1
time.sleep(1)
dev.set_media(media)
cmd = img_start.to_bytes(8, byteorder='little')
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_WRITE.to_bytes(4, byteorder='little')
cmd += img_type.to_bytes(4, byteorder='little')
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
text = f"Programming {i+1}/{image_cnt}"
bar = tqdm(total=img_length, position=dev.get_id(), ascii=True, desc=text, bar_format='{l_bar}{bar:10}{bar:-10b}')
for offset in range(0, img_length, TRANSFER_SIZE):
xfer_size = TRANSFER_SIZE if offset + TRANSFER_SIZE < img_length else img_length - offset
dev.write(pack_image.img_content(i, offset, xfer_size))
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != xfer_size:
print("Ack size error")
return -1
bar.update(xfer_size)
bar.close()
dev.read(4)
# FIXME: Added time.sleep(1) to make SPI NAND Pack Program + Verify PASS
time.sleep(1)
if option == OPT_VERIFY:
dev.set_media(media)
cmd = img_start.to_bytes(8, byteorder='little')
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_READ.to_bytes(4, byteorder='little')
cmd += b'\x00' * 4
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
remain = img_length
text = f"Verifying {i}/{image_cnt}"
bar = tqdm(total=img_length, position=dev.get_id(), ascii=True, desc=text, bar_format='{l_bar}{bar:10}{bar:-10b}')
while remain > 0:
ack = dev.read(4)
# Get the transfer length of next read
xfer_size = int.from_bytes(ack, byteorder="little")
data = dev.read(xfer_size)
dev.write(xfer_size.to_bytes(4, byteorder='little'))
offset = img_length - remain
# For SD/eMMC
if xfer_size > remain:
xfer_size = remain
data = data[0: remain]
if data != bytearray(pack_image.img_content(i, offset, xfer_size)):
print("Verify failed")
return -1
remain -= xfer_size
bar.update(xfer_size)
bar.close()
return 0
def do_pack_program(media, pack_file_name, option=OPT_NONE) -> int:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
pack_image = UnpackImage(pack_file_name, option)
with ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(__pack_program, dev, media, pack_image, option) for dev in devices]
success = 0
failed = 0
for future in as_completed(futures):
if future.result() == 0:
success += 1
else:
failed += 1
print(f"Successfully programmed {success} device(s)")
if failed > 0:
print(f"Failed to program {failed} device(s)")
return -1
return 0
def __img_program(dev, media, start, img_data, option) -> int:
nand_align, spinand_align, npage, nblock, nbcnt, noob, snpage, snblock, snbcnt, snoob, emmc_block = dev.get_align()
if (media == DEV_NAND and nand_align == 0) or \
(media == DEV_SPINAND and spinand_align == 0):
print("Unable to get block size")
return -1
if (media == DEV_NAND and start % nand_align != 0) or\
(media == DEV_SPINAND and start % spinand_align != 0) or \
(media == DEV_SPINOR and start % SPINOR_ALIGN != 0):
print("Starting address must be block aligned")
return -1
img_length = len(img_data)
#print(f"image length is {img_length}")
cmd = start.to_bytes(8, byteorder='little')
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_WRITE.to_bytes(4, byteorder='little')
if option == OPT_EXECUTE:
cmd += option.to_bytes(4, byteorder='little')
else:
cmd += b'\x00' * 4
dev.set_media(media)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
# Set ascii=True is for Windows cmd terminal, position > 0 doesn't work as expected in cmd though...
text = f"Programming {dev.get_id()}"
bar = tqdm(total=img_length, position=dev.get_id(), ascii=True, desc=text, bar_format='{l_bar}{bar:10}{bar:-10b}')
for offset in range(0, img_length, TRANSFER_SIZE):
xfer_size = TRANSFER_SIZE if offset + TRANSFER_SIZE < img_length else img_length - offset
dev.write(img_data[offset: offset + xfer_size])
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != xfer_size:
print("Ack size error")
return -1
bar.update(xfer_size)
dev.read(4)
bar.close()
if option == OPT_VERIFY:
dev.set_media(media)
cmd = start.to_bytes(8, byteorder='little')
cmd += img_length.to_bytes(8, byteorder='little')
cmd += ACT_READ.to_bytes(4, byteorder='little')
cmd += b'\x00' * 4
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return -1
remain = img_length
text = f"Verifying {dev.get_id()}"
bar = tqdm(total=img_length, position=dev.get_id(), ascii=True, desc=text, bar_format='{l_bar}{bar:10}{bar:-10b}')
while remain > 0:
ack = dev.read(4)
# Get the transfer length of next read
xfer_size = int.from_bytes(ack, byteorder="little")
data = dev.read(xfer_size)
dev.write(xfer_size.to_bytes(4, byteorder='little')) # ack
offset = img_length - remain
# For SD/eMMC
if xfer_size > remain:
xfer_size = remain
data = data[0: remain]
if data != bytearray(img_data[offset: offset + xfer_size]):
print("Verify failed")
return -1
remain -= xfer_size
bar.update(xfer_size)
print("Verify pass")
bar.close()
return 0
def do_img_program(media, start, image_file_name, option=OPT_NONE) -> int:
global mp_mode
# devices = XUsbComList(attach_all=mp_mode).get_dev()
_XUsbComList = XUsbComList(attach_all=mp_mode)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
try:
with open(image_file_name, "rb") as image_file:
print("Loading Image...")
img_data = image_file.read()
print("done")
except (IOError, OSError) as err:
print(f"Open {image_file_name} failed")
sys.exit(err)
with ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(__img_program, dev, media, start, img_data, option) for dev in devices]
success = 0
failed = 0
for future in as_completed(futures):
if future.result() == 0:
success += 1
else:
failed += 1
print(f"Successfully programmed {success} device(s)")
if failed > 0:
print(f"Failed to program {failed} device(s)")
return -1
return 0;
def do_img_read(media, start, out_file_name, length=0x1, option=OPT_NONE) -> None:
# only support read from 1 device
# devices = XUsbComList(attach_all=False).get_dev()
_XUsbComList = XUsbComList(attach_all=False)
devices = _XUsbComList.get_dev()
if len(devices) == 0:
print("Device not found")
sys.exit(2)
# Only support one device in read function
dev = devices[0]
cmd = start.to_bytes(8, byteorder='little')
cmd += length.to_bytes(8, byteorder='little')
cmd += ACT_READ.to_bytes(4, byteorder='little')
cmd += option.to_bytes(4, byteorder='little')
dev.set_media(media)
dev.write(cmd)
ack = dev.read(4)
if int.from_bytes(ack, byteorder="little") != ACK:
print("Receive ACK error")
return
# Get real length for "read all"
if length == 0:
nand_align, spinand_align, npage, nblock, nbcnt, noob, snpage, snblock, snbcnt, snoob, emmc_block = dev.get_align()
if (media == DEV_NAND and nbcnt == 0) or (media == DEV_SD_EMMC and emmc_block == 0) \
or (media == DEV_SPINAND and snbcnt == 0):
print("Unable to get block count")
return -1
if media == DEV_NAND:
if option == OPT_WITHBAD:
print("read with bad")
length = (npage + noob) * nblock * nbcnt
else:
length = nand_align * nbcnt
elif media == DEV_SPINAND:
if option == OPT_WITHBAD:
print("read with bad")
length = (snpage + snoob) * snblock * snbcnt
else:
length = spinand_align * snbcnt
elif media == DEV_SD_EMMC:
length = emmc_block * 512;
print(length)
bar = tqdm(total=length, ascii=True, bar_format='{l_bar}{bar:10}{bar:-10b}')
data = b''
remain = length
try:
out_file = open(out_file_name, "wb")
except (IOError, OSError) as err:
print(f"Open {out_file_name} failed")
sys.exit(err)
while remain > 0:
ack = dev.read(4)
# Get the transfer length of next read
xfer_size = int.from_bytes(ack, byteorder="little")