-
Notifications
You must be signed in to change notification settings - Fork 5
/
jluboottool.py
1019 lines (774 loc) · 30.2 KB
/
jluboottool.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
from jl_stuff import *
from jl_uboot import JL_MSCDevice, JL_UBOOT, JL_LoaderV2, JL_LoaderV1
from scsiio.common import SCSIException
import argparse, cmd, time
import pathlib, yaml
ap = argparse.ArgumentParser(description='JieLi UBOOT tool - the swiss army knife for JieLi technology',
epilog="// it's not that great, actually.")
def anyint(s):
return int(s, 0)
ap.add_argument('--device',
help='Specify a path to the JieLi disk (e.g. /dev/sg2 or \\\\.\\E:), ' +
'if not specified, then it tries to search for devices.')
ap.add_argument('--loader-arg', type=anyint, metavar='ARG',
help="Loader's argument (overrides the default).\n" +
"Hint: usually, the argument is parsed by the loader as follows:\n" +
" bit0-3: Target memory (1 = SPI flash, 7 = OTP),\n" +
" bit4-11: Clock divider (0 = default, >0 = 1/n) - base is usually 48 MHz,\n" +
" bit12-13: SPI mode (0 = half-duplex (2-wire) SPI, 1 = duplex (3-wire) SPI, 2 = DSPI, 3 = QSPI)")
ap.add_argument('--custom-loaders', metavar='FILE',
help='Path to the custom loader spec YAML file. ' +
'If something goes wrong when loading it, then the builtin loader spec is used.')
args = ap.parse_args()
###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ######
scriptroot = pathlib.Path(__file__).parent
dataroot = scriptroot/'data'
JL_chips = yaml.load(open(dataroot/'chips.yaml'), Loader=yaml.SafeLoader)
JL_usb_loaders = yaml.load(open(dataroot/'usb-loaders.yaml'), Loader=yaml.SafeLoader)
JL_uart_loaders = yaml.load(open(dataroot/'uart-loaders.yaml'), Loader=yaml.SafeLoader)
print('** %d chips, %d USB loaders, %d UART loaders **' % (len(JL_chips), len(JL_usb_loaders), len(JL_uart_loaders)))
###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ######
# XXX: this is specific to V2 loaders.
dev_type_strs = {
0x00: 'None',
0x01: 'SDRAM',
0x02: 'SD card',
0x03: 'SPI NOR flash on SPI0',
0x04: 'SPI NAND flash on SPI0',
0x05: 'OTP',
0x10: 'SD card 2',
0x11: 'SD card 3',
0x12: 'SD card 4',
0x13: 'Something 0x13',
0x14: 'Something 0x14',
0x15: 'Something 0x15',
0x16: 'SPI NOR flash on SPI1',
0x17: 'SPI NOR flash on SPI1',
}
def makebar(ratio, length):
bratio = int(ratio * length)
bar = ''
if bratio > 0:
bar += '=' * (bratio - 1)
bar += '>'
bar += ' ' * (length - bratio)
return bar
#
# Well, yeah, that's cool but do we really need this?
#
def print_largeletters(string):
string = string.upper()
chars = {
'0': (r' _____ ', r' | / |', r' | / |', r' |_/___|'),
'1': (r' _ ', r' /| ', r' | ', r' __|__ '),
'2': (r' _____ ', r' | |', r' _____|', r' |______'),
'3': (r' _____ ', r' ___|', r' |', r' ______|'),
'4': (r' ', r' | | ', r' |____|_', r' | '),
'5': (r' ______', r' |_____ ', r' |', r' ______|'),
'6': (r' ______', r' |_____ ', r' | |', r' |_____|'),
'7': (r' _____ ', r' | |', r' |', r' |'),
'8': (r' _____ ', r' |_____|', r' | |', r' |_____|'),
'9': (r' _____ ', r' | |', r' |_____|', r' ______|'),
'A': (r' _____ ', r' |_____|', r' | |', r' | |'),
'B': (r' ______', r' |_____/', r' | |', r' |_____|'),
'C': (r' _____ ', r' | |', r' | ', r' |______'),
'D': (r' _____ ', r' | |', r' | |', r' |____/ '),
'E': (r' ______', r' |_____ ', r' | ', r' |______'),
'F': (r' ______', r' |_____ ', r' | ', r' | '),
'G': (r' _____ ', r' | ', r' | ___ ', r' |_____|'),
'H': (r' ', r' |_____|', r' | |', r' | |'),
'I': (r' _______', r' | ', r' | ', r' ___|___'),
'J': (r' ___ ', r' |', r' |', r' |_____|'),
'K': (r' ', r' |___/ ', r' | \ ', r' | \\'),
'L': (r' ', r' | ', r' | ', r' |_____|'),
'M': (r' ______ ', r' | | |', r' | |', r' | |'),
'N': (r' ', r' |\ |', r' | \ |', r' | \|'),
'O': (r' _____ ', r' | |', r' | |', r' |_____|'),
'P': (r' ______', r' |_____/', r' | ', r' | '),
'Q': (r' _____ ', r' | |', r' | \ |', r' |____\|'),
'R': (r' ______', r' |_____/', r' | |', r' | |'),
'S': (r' _______', r' \_____ ', r' |', r' ______|'),
'T': (r' _______', r' | ', r' | ', r' | '),
'U': (r' ', r' | |', r' | |', r' |_____|'),
'V': (r' ', r' | |', r' \ / ', r' \_/ '),
'W': (r' ', r' | |', r' | | |', r' |__|__|'),
'X': (r' ', r' \ /', r' >---< ', r' / \\'),
'Y': (r' ', r' | |', r' |_____|', r' ______|'),
'Z': (r' _______', r' ___/', r' / ', r' _/_____'),
}
height = 0
for c in string:
char = chars.get(c, [])
height = max(height, len(char))
for line in range(height):
ln = ''
for c in string:
char = chars.get(c, [])
if line >= len(char): continue
ln += char[line]
print(ln)
print()
###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ######
class DasShell(cmd.Cmd):
intro = \
"""
.------------------------------------------------------.
| _____________ .------------------------------. |
| /___ __ ___/ | JieLi UBOOT Tool |
| / / / / | - Das Shell - |
| __ / / / / `------------------------------. |
| / /_/ / / /____ -*- JieLi tech console -*- | |
| `____/ /______/ Type 'help' or '?' for help. | |
| `------------------------------' |
`------------------------------------------------------'
"""
prompt = '=>JL: '
def __init__(self, dev):
super(DasShell, self).__init__()
self.dev = dev
try:
self.buffsize = self.dev.usb_buffer_size()
except:
self.buffsize = 512
def emptyline(self):
pass
def do_exit(self, args):
"""Get out of the shell"""
print("Bye!")
return True
#------#------#------#------#------#------#------#------#------#------#
def do_chipkey(self, args):
"""Read the chip key from the chip
chipkey
"""
try:
key = self.dev.chip_key()
except SCSIException:
print("Failed to get the chip key")
return
print('Your chip key is:')
print_largeletters('%04X' % key)
if key == 0xffff:
print("Chip key is blank! You're good to go.")
elif key == 0x0000:
print("Chip key bits seem to be fully burnt out.")
print("Did something go wrong? Or that's what it is supposed to be?")
else:
nbits = bin(key).count('1')
print("- %d bits are still intact." % nbits)
def do_burnchipkey(self, args):
""" Burn the chipkey into the chip
burnchipkey <key>
"""
args = args.split(maxsplit=1)
if len(args) < 1:
print("Not enough arguments!")
self.do_help('burnchipkey')
return
try:
newkey = int(args[0], 0) & 0xffff
except ValueError:
print("<key> [%s] is not a number!" % args[0])
return
try:
key = self.dev.chip_key()
except SCSIException:
print("Failed to get the chip key")
return
print('Your current chip key:')
print_largeletters('%04X' % key)
print("Chip key you're going to burn:")
print_largeletters('%04X' % newkey)
realkey = newkey & key
#
# Print the messages..
#
if key == 0x0000:
if newkey == 0xffff:
print("You think you can restore this back to normal?")
elif newkey == 0x0000:
print("Well, everything is burnt down already. So there's nothing to do.")
return
else:
print("Your chipkey seems to be fully burnt out, you think you can do something about it?")
elif key == 0xffff:
if newkey == 0xffff:
print("Your chipkey is already nice and clean! Cheers!")
return
elif newkey == 0x0000:
print("Well, you want to burn all bits down?")
else:
print("You are about to burn the chipkey into a chip. Do you want to proceed?")
else:
if newkey == 0xffff:
print("Hmmm... You really think you can clear the chipkey?")
elif newkey == 0x0000:
print("Oh, so you want to burn the remaining bits to death? Do you?")
elif key == newkey:
print("This chipkey is already burnt into the chip.")
return
else:
if realkey == newkey:
print("This key can be successfully written. Do you want to proceed?")
else:
print("Well, this key won't be written as you think it will.")
print("That's what you get instead:")
print_largeletters('%04X' % realkey)
print("\nDo you still want to proceed?")
# silly approach to confirming a possibly-dangerous task.
answer = input('Say "yes i do" to proceed: ')
if answer.strip().lower() != 'yes i do':
print("You didn't answer correctly. Aborting")
return
try:
result = self.dev.write_chipkey(newkey)
except SCSIException:
print("Failed to burn chipkey!")
return
print("Command result: 0x%08x" % result)
print("Current chipkey: %04x" % self.dev.chip_key())
def do_onlinedev(self, args):
"""Get the device type and info we're working with
onlinedev
"""
try:
info = self.dev.online_device()
except SCSIException:
print("Failed to get the online device info")
return
print('Device type:\n 0x%02x [%s]' % (info['type'], dev_type_strs.get(info['type'])))
print("\nDevice ID:")
print_largeletters('%08X' % info['id'])
def do_execcmd(self, args):
"""Execute an arbitrary loader command (those which do not transfer any data, but simply return a response)
execcmd <opcode> [<arg bytes>]
"""
args = args.split(maxsplit=1)
if len(args) < 1:
print("Not enough arguments!")
self.do_help('execcmd')
return
try:
opcode = int(args[0], 0) & 0xffff
except ValueError:
print("<opcode> [%s] is not a number!" % args[0])
return
try:
data = bytes.fromhex(args[1])
except IndexError:
data = b''
except ValueError:
print('Wrong hex string "%s"!' % args[1])
return
try:
resp = self.dev.cmd_exec(opcode, data, check_response=True)
print('Response: %04x / [%s]' % (resp[0], resp[1].hex(' ')))
except Exception as e:
print("Command execution failed: ", e)
#------#------#------#------#------#------#------#------#------#------#
def flash_erase(self, address, length):
dlength = 0
while length > 0:
if length >= 0x10000 and (address & 0xffff) == 0:
block = 0x10000
else:
block = 0x1000
n = min(length, block - (address % block))
#print("\rErasing %x-%x..." % (address, address + length - 1), end='', flush=True)
t = time.time()
if block > 0x1000: self.dev.flash_erase_block(address)
else: self.dev.flash_erase_sector(address)
t = time.time() - t
length -= n
dlength += n
ratio = dlength / (dlength + length)
print("\rErasing %08x [%s] %3d%%" % (address, makebar(ratio, 40), ratio * 100), end='')
print(" %.2f KB/s" % ((block / 1000 / t) if t > 0 else 0), end='', flush=True)
address += n
print()
def flash_write_file(self, address, length, fil):
dlength = 0
while length > 0:
block = fil.read(self.buffsize)
if block == b'': break
n = len(block)
t = time.time()
self.dev.flash_write(address, block)
t = time.time() - t
length -= n
dlength += n
ratio = dlength / (dlength + length)
print("\rWriting %08x [%s] %3d%%" % (address, makebar(ratio, 40), ratio * 100), end='')
print(" %.2f KB/s" % ((len(block) / 1000 / t) if t > 0 else 0), end='', flush=True)
address += n
print()
def flash_read_file(self, address, length, fil):
dlength = 0
while length > 0:
n = min(self.buffsize, length)
t = time.time()
data = self.dev.flash_read(address, n)
t = time.time() - t
fil.write(data)
length -= n
dlength += n
ratio = dlength / (dlength + length)
print("\rReading %08x [%s] %3d%%" % (address, makebar(ratio, 40), ratio * 100), end='')
print(" %.2f KB/s" % ((len(data) / 1000 / t) if t > 0 else 0), end='', flush=True)
address += n
print()
#-------------------------------------
def do_read(self, args):
"""Read flash to file.
read <address> <length> <file>
"""
# <length> can be 0 to dump whole flash (size aligned to the address used)
# """
args = args.split(maxsplit=2)
if len(args) < 3:
print("Not enough arguments!")
self.do_help('read')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
length = int(args[1], 0)
except ValueError:
print("<length> [%s] is not a number!" % args[1])
return
try:
fil = open(args[2], 'wb')
except Exception as e:
print("Can't open file [%s] - %s" % (args[2], e))
return
with fil:
print()
self.flash_read_file(address, length, fil)
#-------------------------------------
def do_write(self, args):
"""Write file to flash.
write <address> <file>
"""
args = args.split(maxsplit=1)
if len(args) < 2:
print("Not enough arguments!")
self.do_help('write')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
fil = open(args[1], 'rb')
except Exception as e:
print("Can't open file [%s] - %s" % (args[1], e))
return
with fil:
fil.seek(0, 2)
length = fil.tell()
fil.seek(0)
print()
self.flash_erase(address, length)
self.flash_write_file(address, length, fil)
#-------------------------------------
def do_erasechip(self, args):
"""Erase whole flash.
erasechip
Warning: may not always work!
"""
self.dev.flash_erase_chip()
def do_erase(self, args):
"""Erase flash.
erase <address> <length>
"""
# erase [<address> [<length>]]
#
# If <address> and <length> is not specified,
# then the whole flash will be erased.
#
# If only the <address> is specified, then everything starting from
# that address will be erased. (the same works when <length> specified as 0)
# """
args = args.split(maxsplit=2)
if len(args) < 2:
print("Not enough arguments!")
self.do_help('erase')
return
try:
address = int(args[0], 0)
except IndexError:
address = 0
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
length = int(args[1], 0)
except IndexError:
length = 0
except ValueError:
print("<length> [%s] is not a number!" % args[1])
return
print()
self.flash_erase(address, length)
#-------------------------------------
def do_dump(self, args):
"""Dump flash to console.
dump <address> [<length>]
If <length> is not specified, then it will default to 256 bytes.
"""
args = args.split(maxsplit=2)
if len(args) < 1:
print("Not enough arguments!")
self.do_help('dump')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
length = int(args[1], 0)
except IndexError:
length = 256
except ValueError:
print("<length> [%s] is not a number!" % args[1])
return
while length > 0:
n = min(length, self.buffsize)
hexdump(self.dev.flash_read(address, n), address=address)
address += n
length -= n
#------#------#------#------#------#------#------#------#------#------#
def do_memread(self, args):
"""Read memory to file.
memread <address> <length> <file>
"""
args = args.split(maxsplit=2)
if len(args) < 3:
print("Not enough arguments!")
self.do_help('memread')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
length = int(args[1], 0)
except ValueError:
print("<length> [%s] is not a number!" % args[1])
return
try:
fil = open(args[2], 'wb')
except Exception as e:
print("Can't open file [%s] - %s" % (args[2], e))
return
with fil:
dlength = 0
while length > 0:
n = min(256, length) # FIXME: the BR25 loader doesn't like reading more than 256+15 bytes!
t = time.time()
data = self.dev.mem_read(address, n)
t = time.time() - t
fil.write(data)
length -= n
dlength += n
ratio = dlength / (dlength + length)
print("\rReading %08x [%s] %3d%%" % (address, makebar(ratio, 40), ratio * 100), end='')
print(" %.2f KB/s" % ((len(data) / 1000 / t) if t > 0 else 0), end='', flush=True)
address += n
print()
#-------------------------------------
def do_memwrite(self, args):
"""Write file to memory.
memwrite <address> <file>
"""
args = args.split(maxsplit=1)
if len(args) < 2:
print("Not enough arguments!")
self.do_help('memwrite')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
fil = open(args[1], 'rb')
except Exception as e:
print("Can't open file [%s] - %s" % (args[1], e))
return
with fil:
fil.seek(0, 2)
length = fil.tell()
fil.seek(0)
dlength = 0
while length > 0:
block = fil.read(256) # FIXME: same deal
if block == b'': break
n = len(block)
t = time.time()
self.dev.mem_write(address, block)
t = time.time() - t
length -= n
dlength += n
ratio = dlength / (dlength + length)
print("\rWriting %08x [%s] %3d%%" % (address, makebar(ratio, 40), ratio * 100), end='')
print(" %.2f kB/s" % ((len(block) / 1000 / t) if t > 0 else 0), end='', flush=True)
address += n
print()
#-------------------------------------
def do_memdump(self, args):
"""Dump memory to console.
memdump <address> [<length>]
If <length> is not specified, then it will default to 256 bytes.
"""
args = args.split(maxsplit=2)
if len(args) < 1:
print("Not enough arguments!")
self.do_help('memdump')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
length = int(args[1], 0)
except IndexError:
length = 256
except ValueError:
print("<length> [%s] is not a number!" % args[1])
return
while length > 0:
n = min(length, 256) # FIXME: same deal
hexdump(self.dev.mem_read(address, n), address=address)
address += n
length -= n
#-------------------------------------
def memjump(self, args):
"""Execute code at a given address
memjump <addr> [<arg>]
[<arg>] specifies an 16-bit integer which is passed to the
code in its loader parameters structure, if any is supported by the chip or its loader.
If it is not specified, it defaults to 0
"""
args = args.split(maxsplit=2)
if len(args) < 1:
print("Not enough arguments!")
self.do_help('memjump')
return
try:
address = int(args[0], 0)
except ValueError:
print("<address> [%s] is not a number!" % args[0])
return
try:
arg = int(args[1], 0)
except IndexError:
arg = 0
except ValueError:
print("<arg> [%s] is not a number!" % args[1])
return
try:
self.dev.mem_jump(address, arg)
except SCSIException as e:
print('Something failed while executing code.')
print(e)
#------#------#------#------#------#------#------#------#------#------#
def do_reset(self, args):
"""Reset the chip. (or "Run App")
reset [<arg>]
If <arg> is not specified, then it will default to 1.
"""
args = args.split(maxsplit=2)
try:
code = int(args[0], 0)
except IndexError:
code = 1
except ValueError:
print("<code> [%s] is not a number!" % args[0])
return
try:
self.dev.run_app(code)
except Exception as e:
print("<!> Exiting..", e)
return True
###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ######
if args.device is not None:
device = args.device
else:
from jldevfind import choose_jl_device
device = choose_jl_device()
if device is None:
exit(1)
with JL_MSCDevice(device) as dev:
vendor, product, prodrev = dev.inquiry()
chipname = vendor.lower()
if chipname not in JL_chips:
print("Chip '%s' is not supported, or it is invalid." % chipname)
exit(2)
print()
chipspec = JL_chips[chipname]
print('Chip: %s (%s series)' % (chipname.upper(), ', '.join(chipspec['name'])))
#
# Load the loader.
# TODO: MUST be moved out somewhere, in order to reuse this in other tools as well.
#
uboot = JL_UBOOT(dev.dev)
runtheloader = False
if product == 'UBOOT1.00':
print("This is a UBOOT1.00 device, running the loader.")
runtheloader = True
if runtheloader:
custom_loaderspecs = None
#
# Is there any custom loader spec passed?
#
if args.custom_loaders is not None:
print("Trying to use custom loader specs from [%s]..." % args.custom_loaders)
try:
custom_loaderspecs = yaml.load(open(args.custom_loaders), Loader=yaml.SafeLoader)
except Exception as e:
print("Something went wrong while loading the custom loader spec file:", e)
#
# Is there a chip and its USB loader spec in the custom loader spec?
#
if custom_loaderspecs is not None:
if chipname not in custom_loaderspecs:
print("The custom loader spec does not contain definition for chip %s" % chipname)
custom_loaderspecs = None
elif 'usb' not in custom_loaderspecs[chipname]:
print("There is no USB loader in the custom loader spec for chip %s" % chipname)
custom_loaderspecs = None
else:
loaderspec = custom_loaderspecs[chipname]['usb']
loaderroot = pathlib.Path(args.custom_loaders).parent
#
# If we didn't load the custom loader specs, then try to use the builtin one..
#
if custom_loaderspecs is None:
if chipname not in JL_usb_loaders:
print("There is no USB loader for chip %s" % chipname)
exit(3)
loaderspec = JL_usb_loaders[chipname]
loaderroot = dataroot
#
# Upload the loader!
#
with open(loaderroot/loaderspec['file'], 'rb') as f:
blocksz = loaderspec.get('blocksize', 512)
ldrcrypt = loaderspec.get('encryption')
menglicrypt = False
# does this chip's UBOOT1.00 accept data in mengli encrypted form?
if 'uboot1.00' in chipspec:
if 'quirks' in chipspec['uboot1.00']:
menglicrypt = chipspec['uboot1.00']['quirks'].get('memory-rw-mengli-crypt') == True
# shall we ever perform the mengli de/encryption?
menglicrypt = (not menglicrypt and ldrcrypt == 'MengLi') or (menglicrypt and ldrcrypt != 'MengLi')
#
# Write
#
addr = loaderspec['address']
while True:
block = f.read(blocksz)
if block == b'': break
if ldrcrypt == 'RxGp':
# just pass it into the dedicated memory write command
uboot.mem_write_rxgp(addr, block)
else:
if menglicrypt:
block = jl_crypt_mengli(block)
uboot.mem_write(addr, block)
addr += len(block)
f.seek(0)
#
# Verify
#
addr = loaderspec['address']
while True:
block = f.read(blocksz)
if block == b'': break
if ldrcrypt == 'RxGp':
# Decrypt this block in order to check it with an ordinary memory read command
block = jl_crypt_rxgp(block)
elif menglicrypt:
# if it is mengli encrypted or the mem_read returns it this way, then de/encrypt it.
block = jl_crypt_mengli(block)
rblock = uboot.mem_read(addr, len(block))
if block != rblock:
print('Mismatch at %08x!' % addr)
break
addr += len(block)
if 'argument' not in loaderspec:
loaderspec['argument'] = (0<<12) | (4<<4) | (1<<0) # spi mode=0, div=4, mem=1 (spi nor)
if args.loader_arg is not None:
print('Overriding the default loader argument (%04x) with %04x' % (loaderspec['argument'], args.loader_arg))
loaderspec['argument'] = args.loader_arg
if 'entry' not in loaderspec:
loaderspec['entry'] = loaderspec['address']
print("Running loader (loaded to 0x%(address)04x) on 0x%(entry)04x, with argument 0x%(argument)04x..." % loaderspec)
try:
uboot.mem_jump(loaderspec['entry'], loaderspec['argument'])
print("Loader ran successfully.")
except SCSIException:
print("!! Failed to run the loader !!")
exit(3)
loader = JL_LoaderV2(dev.dev)
#
# Print some quick info summary
#
print()
print('================ Quick info ==================')
print(' ** %s (%s series) **' % (chipname.upper(), '/'.join(chipspec['name']))) # redundant?
if isinstance(loader, JL_LoaderV2):
print(' Loader protocol: V2')
try:
print(' >> Chip key: 0x%04X <<' % loader.chip_key())
except SCSIException:
pass
try:
print(' - USB buffer size: %d bytes' % loader.usb_buffer_size())
except SCSIException:
pass
try:
ondev = loader.online_device()
print(' - Online device:')
print(' ID: 0x%06x' % ondev['id'])
print(' Type: 0x%02x (%s)' % (ondev['type'], dev_type_strs.get(ondev['type'], 'unknown')))
except SCSIException:
pass
try:
print(' - Another Device ID: 0x%08x' % loader.read_id())
except SCSIException:
pass
#try:
# print(' - Status: 0x%02x' % loader.read_status())
#except SCSIException:
# pass
#try:
# print(' - MaskROM ID: 0x%08x' % loader.maskrom_id())
#except SCSIException:
# pass
elif isinstance(loader, JL_LoaderV1):
print(' Loader protocol: V1')
try:
print(' - Device ID: 0x%08x' % loader.read_id())
except SCSIException: