forked from mon/cc3200tool
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcc.py
executable file
·1605 lines (1308 loc) · 59.8 KB
/
cc.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
#
# cc3200tool - work with TI's CC3200 SimpleLink (TM) filesystem.
# Copyright (C) 2016-2020 Allterco Robotics
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
import sys
import os
import tempfile
import time
import argparse
import struct
import math
import logging
from contextlib import contextmanager
from pkgutil import get_data
from collections import namedtuple
import json
import serial
log = logging.getLogger()
logging.basicConfig(stream=sys.stderr, level=logging.INFO,
format="%(asctime)-15s -- %(message)s")
CC3200_BAUD = 921600
# erasing blocks is time consuming and depends on flash type
# so separate timeout value is used
ERASE_TIMEOUT = 120
OPCODE_START_UPLOAD = b'\x21'
OPCODE_FINISH_UPLOAD = b'\x22'
OPCODE_GET_LAST_STATUS = b'\x23'
OPCODE_FILE_CHUNK = b'\x24'
OPCODE_GET_STORAGE_LIST = b'\x27'
OPCODE_FORMAT_FLASH = b'\x28'
OPCODE_GET_FILE_INFO = b'\x2A'
OPCODE_READ_FILE_CHUNK = b'\x2B'
OPCODE_RAW_STORAGE_READ = b'\x2C'
OPCODE_RAW_STORAGE_WRITE = b'\x2D'
OPCODE_ERASE_FILE = b'\x2E'
OPCODE_GET_VERSION_INFO = b'\x2F'
OPCODE_RAW_STORAGE_ERASE = b'\x30'
OPCODE_GET_STORAGE_INFO = b'\x31'
OPCODE_EXEC_FROM_RAM = b'\x32'
OPCODE_SWITCH_2_APPS = b'\x33'
STORAGE_ID_SRAM = 0x0
STORAGE_ID_SFLASH = 0x2
FLASH_BLOCK_SIZES = [0x100, 0x400, 0x1000, 0x4000, 0x10000]
SLFS_SIZE_MAP = {
"512": 512,
"1M": 1024,
"2M": 2 * 1024,
"4M": 4 * 1024,
"8M": 8 * 1024,
"16M": 16 * 1024,
}
SLFS_BLOCK_SIZE = 4096
# defines from cc3200-sdk/simplelink/include/fs.h
SLFS_FILE_OPEN_FLAG_COMMIT = 0x1 # /* MIRROR - for fail safe */
SLFS_FILE_OPEN_FLAG_SECURE = 0x2 # /* SECURE */
SLFS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST = 0x4 # /* Relevant to secure file only */
SLFS_FILE_OPEN_FLAG_STATIC = 0x8 # /* Relevant to secure file only */
SLFS_FILE_OPEN_FLAG_VENDOR = 0x10 # /* Relevant to secure file only */
SLFS_FILE_PUBLIC_WRITE = 0x20 # /* Relevant to secure file only, the file can be opened for write without Token */
SLFS_FILE_PUBLIC_READ = 0x40 # /* Relevant to secure file only, the file can be opened for read without Token */
SLFS_MODE_OPEN_READ = 0
SLFS_MODE_OPEN_WRITE = 1
SLFS_MODE_OPEN_CREATE = 2
SLFS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST = 3
def hexify(s):
return " ".join([hex(x) for x in s])
Pincfg = namedtuple('Pincfg', ['invert', 'pin'])
def pinarg(extra=None):
choices = ['dtr', 'rts', 'none']
if extra:
choices.extend(extra)
def _parse(apin):
invert = False
if apin.startswith('~'):
invert = True
apin = apin[1:]
if apin not in choices:
raise argparse.ArgumentTypeError(f"{apin} not one of {choices}")
return Pincfg(invert, apin)
return _parse
def auto_int(x):
return int(x, 0)
class PathType(object):
def __init__(self, exists=True, type='file', dash_ok=True):
'''exists:
True: a path that does exist
False: a path that does not exist, in a valid parent directory
None: don't care
type: file, dir, symlink, None, or a function returning True for valid paths
None: don't care
dash_ok: whether to allow "-" as stdin/stdout'''
assert exists in (True, False, None)
assert type in ('file','dir','symlink',None) or hasattr(type,'__call__')
self._exists = exists
self._type = type
self._dash_ok = dash_ok
def __call__(self, string):
if string=='-':
# the special argument "-" means sys.std{in,out}
if self._type == 'dir':
raise CC3200Error('standard input/output (-) not allowed as directory path')
elif self._type == 'symlink':
raise CC3200Error('standard input/output (-) not allowed as symlink path')
elif not self._dash_ok:
raise CC3200Error('standard input/output (-) not allowed')
else:
e = os.path.exists(string)
if self._exists==True:
if not e:
raise CC3200Error("path does not exist: '%s'" % string)
if self._type is None:
pass
elif self._type=='file':
if not os.path.isfile(string):
raise CC3200Error("path is not a file: '%s'" % string)
elif self._type=='symlink':
if not os.path.symlink(string):
raise CC3200Error("path is not a symlink: '%s'" % string)
elif self._type=='dir':
if not os.path.isdir(string):
raise CC3200Error("path is not a directory: '%s'" % string)
elif not self._type(string):
raise CC3200Error("path not valid: '%s'" % string)
else:
if self._exists==False and e:
raise CC3200Error("path exists: '%s'" % string)
p = os.path.dirname(os.path.normpath(string)) or '.'
if not os.path.isdir(p):
raise CC3200Error("parent path is not a directory: '%s'" % p)
elif not os.path.exists(p):
raise CC3200Error("parent directory does not exist: '%s'" % p)
return string
# TODO: replace argparse.FileType('rb') with manual file handling
parser = argparse.ArgumentParser(description='Serial flash utility for CC3200')
parser.add_argument(
"-p", "--port", type=str, default="/dev/ttyUSB0",
help="The serial port to use")
parser.add_argument(
"-if", "--image_file", type=str, default=None,
help="Use a image file instead of serial link (read)")
parser.add_argument(
"-of", "--output_file", type=str, default=None,
help="Use a image file instead of serial link (write)")
parser.add_argument(
"--reset", type=pinarg(['prompt']), default="none",
help="dtr, rts, none or prompt, optinally prefixed by ~ to invert")
parser.add_argument(
"--sop2", type=pinarg(), default="none",
help="dtr, rts or none, optinally prefixed by ~ to invert")
parser.add_argument(
"--erase_timeout", type=auto_int, default=ERASE_TIMEOUT,
help="Specify block erase timeout for all operations which involve block erasing")
parser.add_argument(
"--reboot-to-app", action="store_true",
help="When finished, reboot to the application")
parser.add_argument(
"-d", "--device", type=str, default="cc3200",
help="Device to select cc3200/cc32xx (to decide which offsets to use)")
subparsers = parser.add_subparsers(dest="cmd")
parser_format_flash = subparsers.add_parser(
"format_flash", help="Format the flash memory")
parser_format_flash.add_argument(
"-s", "--size", choices=list(SLFS_SIZE_MAP.keys()), default="1M")
parser_erase_file = subparsers.add_parser(
"erase_file", help="Erase a file from the SL filesystem")
parser_erase_file.add_argument(
"filename", help="file on the target to be removed")
parser_write_file = subparsers.add_parser(
"write_file", help="Upload a file on the SL filesystem")
parser_write_file.add_argument(
"local_file", type=argparse.FileType('rb'),
help="file on the local file system")
parser_write_file.add_argument(
"cc_filename", help="file name to write on the target")
parser_write_file.add_argument(
"--signature", type=argparse.FileType('rb'),
help="file which contains the 256 bytes of signature for secured files")
parser_write_file.add_argument(
"--file-size", type=auto_int, default=0,
help="allows allocating more space than needed for this upload")
parser_write_file.add_argument(
"--commit-flag", action="store_true",
help="enables fail safe MIRROR feature")
parser_write_file.add_argument(
"--file-id", type=auto_int, default=-1, help="if filename not available you can read a file by its id (image_file only!)")
parser_write_file.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a read of the written data to verify")
parser_read_file = subparsers.add_parser(
"read_file", help="read a file from the SL filesystem")
parser_read_file.add_argument(
"cc_filename", help="file to read from the target")
parser_read_file.add_argument(
"local_file", type=argparse.FileType('w+b'),
help="local path to store the file contents in")
parser_read_file.add_argument(
"--file-id", type=auto_int, default=-1, help="if filename not available you can read a file by its id")
parser_read_file.add_argument(
"--inactive", action="store_true",
help="read from inactive FAT copy")
parser_read_file.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a second read of the data to verify")
parser_write_flash = subparsers.add_parser(
"write_flash", help="Write a Gang image on the flash")
parser_write_flash.add_argument(
"gang_image_file", type=argparse.FileType('rb'),
help="gang image file prepared with Uniflash")
parser_write_flash.add_argument(
"--no-erase", type=bool, default=False,
help="do not perform an erase before write (for blank chips)")
parser_write_flash.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a read of the written data to verify")
parser_read_flash = subparsers.add_parser(
"read_flash", help="Read SFFS contents into the file")
parser_read_flash.add_argument(
"dump_file", type=argparse.FileType('w+b'),
help="path to store the SFFS dump")
parser_read_flash.add_argument(
"--offset", type=auto_int, default=0,
help="starting offset (default is 0)")
parser_read_flash.add_argument(
"--size", type=auto_int, default=-1,
help="dump size (default is complete SFFS)")
parser_read_flash.add_argument(
"--ignore-max-size", type=bool, default=False,
help="ignore the maximum size of the flash")
parser_read_flash.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a second read of the data to verify")
parser_list_filesystem = subparsers.add_parser(
"list_filesystem",
help="List SFFS contents and statistics (blocks total/used, inter-file gaps, etc)")
parser_list_filesystem.add_argument(
"--json-output", action="store_true",
help="output in JSON format to stdout")
parser_list_filesystem.add_argument(
"--inactive", action="store_true",
help="output inactive FAT copy")
parser_list_filesystem.add_argument(
"--extended", action="store_true",
help="Read file header and show size in bytes")
parser_read_all_files = subparsers.add_parser(
"read_all_files",
help="Reads all files into a subfolder structure")
parser_read_all_files.add_argument(
#"local_dir", type=PathType(exists=False, type='dir'),
"local_dir",
help="local path to store the files in")
parser_read_all_files.add_argument(
"--by-file-id", action="store_true",
help="Read unknown filenames by its id")
parser_read_all_files.add_argument(
"--all-by-file-id", action="store_true",
help="Read all filenames by its id")
parser_read_all_files.add_argument(
"--inactive", action="store_true",
help="read from inactive FAT copy")
parser_read_all_files.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a second read of the data to verify")
parser_write_all_files = subparsers.add_parser(
"write_all_files",
help="Writes all files from a subfolder structure")
parser_write_all_files.add_argument(
"local_dir", type=PathType(exists=True, type='dir'),
help="local path to read the files from")
parser_write_all_files.add_argument(
"--simulate", action="store_false",
help="List all files to be written and skip writing them")
parser_write_all_files.add_argument(
"--no-verify", type=bool, default=False,
help="do not perform a read of the written data to verify")
parser_dll_data_test = subparsers.add_parser(
"dll_data_test",
help="Tests the dll_data function")
def dll_data(fname):
data = None
path = os.path.join(os.path.dirname(__file__), os.path.join('dll', fname))
if os.path.exists(path):
log.info("Reading %s from file %s" % (fname, path))
data = open(path, 'rb').read()
if data is None:
log.info("Reading %s from package" % fname)
data = get_data('cc3200tool', os.path.join('dll', fname))
if data is None:
raise CC3200Error("could not find dll file %s" % fname)
return data
class CC3200Error(Exception):
pass
class CC3x00VersionInfo(object):
def __init__(self, bootloader, nwp, mac, phy, chip_type):
self.bootloader = bootloader
self.nwp = nwp
self.mac = mac
self.phy = phy
self.chip_type = chip_type
@property
def is_cc3200(self):
return (self.chip_type[0] & 0x10) != 0
@classmethod
def from_packet(cls, data):
bootloader = tuple(data[0:4])
nwp = tuple(data[4:8])
mac = tuple(data[8:12])
phy = tuple(data[12:16])
chip_type = tuple(data[16:20])
return cls(bootloader, nwp, mac, phy, chip_type)
def __repr__(self):
return "CC3x00VersionInfo({}, {}, {}, {}, {})".format(
self.bootloader, self.nwp, self.mac, self.phy, self.chip_type)
class CC3x00StorageList(object):
FLASH_BIT = 0x02
SFLASH_BIT = 0x04
SRAM_BIT = 0x80
def __init__(self, value):
self.value = value
@property
def flash(self):
return (self.value & self.FLASH_BIT) != 0
@property
def sflash(self):
return (self.value & self.SFLASH_BIT) != 0
@property
def sram(self):
return (self.value & self.SRAM_BIT) != 0
def __repr__(self):
return "{}({})".format(self.__class__.__name__, hex(self.value))
class CC3x00StorageInfo(object):
def __init__(self, block_size, block_count):
self.block_size = block_size
self.block_count = block_count
@classmethod
def from_packet(cls, data):
bsize, bcount = struct.unpack(">HH", data[:4])
return cls(bsize, bcount)
def __repr__(self):
return "{}(block_size={}, block_count={})".format(
self.__class__.__name__, self.block_size, self.block_count)
class CC3x00Status(object):
def __init__(self, value):
self.value = value
@property
def is_ok(self):
return self.value == 0x40
@classmethod
def from_packet(cls, packet):
return cls(packet[3])
class CC3x00FileInfo(object):
def __init__(self, exists, size=0):
self.exists = exists
self.size = size
@classmethod
def from_packet(cls, data):
exists = data[0] == 0x01
size = struct.unpack(">I", data[4:8])[0]
return cls(exists, size)
class CC3x00SffsStatsFileEntry(object):
def __init__(self, index, start_block, size_blocks, mirrored, flags, fname, header=None):
self.index = index
self.start_block = start_block
self.size_blocks = size_blocks
self.mirrored = mirrored
self.flags = flags
self.fname = fname
self.total_blocks = self.size_blocks
if self.mirrored:
self.total_blocks = self.total_blocks * 2
self.header = header
self.magic = None
self.size = 0
if header != None:
self.read_header(header)
def read_header(self, header):
self.header = header
self.size = header[2]<<16 | header[1]<<8 | header[0]<<0
self.magic = bytearray(header[3:])
def get_magic(self):
##fileheader[6:7] 4c 53
return ''.join('{:02x}'.format(x) for x in self.magic)
class CC3x00SffsHole(object):
def __init__(self, start_block, size_blocks):
self.start_block = start_block
self.size_blocks = size_blocks
class CC3x00SffsHeader(object):
SFFS_HEADER_SIGNATURE = 0x534c
def __init__(self, fat_index, fat_bytes, storage_info):
self.is_valid = False
self.storage_info = storage_info
if len(fat_bytes) != storage_info.block_size:
raise CC3200Error("incorrect FAT size")
"""
perform just a basic parsing for now, a caller will select a more
relevant fat and then call get_sffs_stats() in order to initiate
complete parsing
"""
fat_commit_revision, header_sign = struct.unpack("<HH", fat_bytes[:4])
if fat_commit_revision == 0xffff or header_sign == 0xffff:
# empty FAT
return
if header_sign != self.SFFS_HEADER_SIGNATURE:
log.warning("broken FAT: (invalid header signature: 0x%08x, 0x%08x)",
fat_commit_revision, header_sign)
return
self.fat_bytes = fat_bytes
self.fat_commit_revision = fat_commit_revision
log.info("[%d] detected a valid FAT revision: %d", fat_index, self.fat_commit_revision)
self.is_valid = True
class CC3x00SffsInfo(object):
SFFS_FAT_FILE_NAME_ARRAY_CC3200_OFFSET = 0x200
SFFS_FAT_FILE_NAME_ARRAY_CC32XX_OFFSET = 0x3C0
def __init__(self, fat_header, storage_info, meta2, device):
self.fat_commit_revision = fat_header.fat_commit_revision
self.block_size = storage_info.block_size
self.block_count = storage_info.block_count
occupied_block_snippets = []
self.used_blocks = 5 # FAT table size, as per documentation
occupied_block_snippets.append((0, 5))
self.files = []
file_name_array_offset = self.SFFS_FAT_FILE_NAME_ARRAY_CC3200_OFFSET
if device == "cc32xx":
file_name_array_offset = self.SFFS_FAT_FILE_NAME_ARRAY_CC32XX_OFFSET
"""
TI's doc: "Total number of files is limited to 128 files, including
system and configuration files"
"""
for i in range(128):
# scan the complete FAT table (as it appears to be)
meta = fat_header.fat_bytes[(i + 1) * 4:(i + 2) * 4]
if meta == b"\xff\xff\xff\xff" or meta == struct.pack("BBBB", 0xff, i, 0xff, 0x7f):
# empty entry in the middle of the FAT table
continue
index, size_blocks, start_block_lsb, flags_sb_msb = struct.unpack("BBBB", meta)
if index != i:
raise CC3200Error("incorrect FAT entry (index %d != %d)" % (index, i))
"""
It's not completely clear, what all of these flags do mean, and
where does the boundary between 'start block MSB' and 'flags'
exactly lie.
According to observations:
- 0x8 seems to be set to '1' for all the files except for
/sys/mcuimg.bin (looks like this is the mark of the
user's app image for the CC3200's ROM bootloader)
- 0x4 seems to be a negated flag of the mirrored/commit option
- 4 LSB bits should be exactly enough to address the SFFS
max size of 16 MB using 4K blocks
"""
flags = flags_sb_msb >> 4
start_block_msb = flags_sb_msb & 0xf
mirrored = (flags & 0x4) == 0
start_block = (start_block_msb << 8) + start_block_lsb
meta2_e = meta2[i * 4 : (i + 1) * 4]
fname_offset, fname_len = struct.unpack("<HH", meta2_e)
fo_abs = file_name_array_offset + fname_offset
fname = meta2[fo_abs:fo_abs + fname_len]
try:
filename_decoded = fname.decode('ascii')
except UnicodeDecodeError:
filename_decoded = fname.decode('ascii', 'replace')
log.warning("broken FAT fileinfo: invalid filename: %s", filename_decoded)
filename_decoded = "<invalid>"
entry = CC3x00SffsStatsFileEntry(i, start_block, size_blocks,
mirrored, flags, filename_decoded)
self.files.append(entry)
occupied_block_snippets.append((start_block, entry.total_blocks))
self.used_blocks = self.used_blocks + entry.total_blocks
# in order to track the trailing "hole", like uniflash does
occupied_block_snippets.append((self.block_count, 0))
self.holes = []
occupied_block_snippets.sort(key=lambda e: e[0])
prev_end_block = 0
for snippet in occupied_block_snippets:
if snippet[0] < prev_end_block:
for f in self.files:
log.info("[%d] block %d..%d fname=%s" %
(f.index, f.start_block, f.start_block + f.total_blocks, f.fname))
raise CC3200Error("broken FAT: overlapping entry at block %d (prev end was %d)" %
(snippet[0], prev_end_block))
if snippet[0] > prev_end_block:
hole = CC3x00SffsHole(prev_end_block, snippet[0] - prev_end_block - 1)
self.holes.append(hole)
prev_end_block = snippet[0] + snippet[1]
def print_sffs_info(self, extended=False):
log.info("Serial Flash block size:\t%d bytes", self.block_size)
log.info("Serial Flash capacity:\t%d blocks", self.block_count)
log.info("")
if extended:
log.info("\tfile\tstart\tsize\tsize\tfail\tflags\ttotal\tmagic\t\tfilename")
log.info("\tindex\tblock\t[BLKs]\t[bytes]\tsafe\t\t[BLKs]")
log.info("-------------------------------------------------------------------------------------------------")
log.info("\tN/A\t0\t5\tN/A\tN/A\t5\tN/A\tN/A\t\tFATFS")
else:
log.info("\tfile\tstart\tsize\tfail\tflags\ttotal\tfilename")
log.info("\tindex\tblock\t[BLKs]\tsafe\t[BLKs]")
log.info("----------------------------------------------------------------------------")
log.info("\tN/A\t0\t5\tN/A\tN/A\t5\tFATFS")
for f in self.files:
if extended:
log.info("\t%d\t%d\t%d\t%d\t%s\t0x%x\t%d\t%s\t%s" %
(f.index, f.start_block, f.size_blocks, f.size,
f.mirrored and "yes" or "no",
f.flags, f.total_blocks, f.get_magic(), f.fname))
else:
log.info("\t%d\t%d\t%d\t%s\t0x%x\t%d\t%s" %
(f.index, f.start_block, f.size_blocks,
f.mirrored and "yes" or "no",
f.flags, f.total_blocks, f.fname))
log.info("")
log.info(" Flash usage")
log.info("-------------------------")
log.info("used space:\t%d blocks", self.used_blocks)
log.info("free space:\t%d blocks",
self.block_count - self.used_blocks)
for h in self.holes:
log.info("memory hole:\t[%d-%d]", h.start_block,
h.start_block + h.size_blocks)
def print_sffs_info_short(self):
log.info("FAT r%d, num files: %d, used/free blocks: %d/%d",
self.fat_commit_revision, len(self.files), self.used_blocks,
self.block_count - self.used_blocks)
def print_sffs_info_json(self):
print(json.dumps(self, cls=CustomJsonEncoder))
class CustomJsonEncoder(json.JSONEncoder):
def default(self, o):
return o.__dict__
class CC3200Connection(object):
SFFS_FAT_METADATA2_CC3200_OFFSET = 0x774
SFFS_FAT_METADATA2_CC32XX_OFFSET = 0x2000
SFFS_FAT_METADATA2_LENGTH = 0x1000
SFFS_FAT_PART_OFFSET = 0x1000
SFFS_FAT_FILE_HEADER_SIZE = 0x8
TIMEOUT = 5
DEFAULT_SLFS_SIZE = "1M"
def __init__(self, port, reset=None, sop2=None, erase_timeout=ERASE_TIMEOUT, device=None, image_file=None, output_file=None):
self.port = port
if not self.port is None:
port.timeout = self.TIMEOUT
self._device = device
self._reset = reset
self._sop2 = sop2
self._erase_timeout = erase_timeout
self._image_file = None
self._output_file = None
self.vinfo = None
self.vinfo_apps = None
if not image_file is None:
self._image_file = open(image_file, 'rb')
if not output_file is None:
self._output_file = open(output_file, 'w+b')
def copy_input_file_to_output_file(self):
if not self._image_file is None or not self._output_file is None:
self._image_file.seek(0)
data = self._image_file.read()
self._output_file.seek(0)
self._output_file.write(data)
@contextmanager
def _serial_timeout(self, timeout=None):
if timeout is None:
yield self.port
return
if timeout == self.port.timeout:
yield self.port
return
orig_timeout, self.port.timeout = self.port.timeout, timeout
yield self.port
self.port.timeout = orig_timeout
def _set_sop2(self, level):
if self._sop2.pin == "none":
return
toset = level ^ self._sop2.invert
if self._sop2.pin == 'dtr':
self.port.dtr = toset
if self._sop2.pin == 'rts':
self.port.rts = toset
def _do_reset(self, sop2):
self._set_sop2(sop2)
if self._reset.pin == "none":
return
if self._reset.pin == "prompt":
print("Reset the device with SOP2 {}asserted and press Enter".format(
'' if sop2 else 'de'
))
input()
return
in_reset = True ^ self._reset.invert
if self._reset.pin == 'dtr':
self.port.dtr = in_reset
time.sleep(.1)
self.port.dtr = not in_reset
if self._reset.pin == 'rts':
self.port.rts = in_reset
time.sleep(.1)
self.port.rts = not in_reset
def _read_ack(self, timeout=None):
ack_bytes = []
with self._serial_timeout(timeout) as port:
while True:
b = port.read(1)
if not b:
log.error("timed out while waiting for ack")
return False
ack_bytes.append(b)
if len(ack_bytes) > 2:
ack_bytes.pop(0)
if ack_bytes == [b'\x00', b'\xCC']:
return True
def _read_packet(self, timeout=None):
with self._serial_timeout(timeout) as port:
header = port.read(3)
if len(header) != 3:
raise CC3200Error("read_packed timed out on header")
len_bytes = header[:2]
csum_byte = header[2]
data_len = struct.unpack(">H", len_bytes)[0] - 2
with self._serial_timeout(timeout):
data = self.port.read(data_len)
if (len(data) != data_len):
raise CC3200Error("did not get entire response")
ccsum = sum(data)
ccsum = ccsum & 0xff
if ccsum != csum_byte:
raise CC3200Error("rx csum failed")
self._send_ack()
return data
def _send_packet(self, data, timeout=None):
assert len(data)
checksum = sum(data)
len_blob = struct.pack(">H", len(data) + 2)
csum = struct.pack("B", checksum & 0xff)
self.port.write(len_blob + csum + data)
if not self._read_ack(timeout):
raise CC3200Error(
f"No ack for packet opcode=0x{data[0]:02x}")
def _send_ack(self):
self.port.write(b'\x00\xCC')
def _get_last_status(self):
self._send_packet(OPCODE_GET_LAST_STATUS)
if not self.port is None:
status = self._read_packet()
log.debug("get last status got %s", hexify(status))
return CC3x00Status(status[0])
return CC3x00Status(0)
def _do_break(self, timeout):
self.port.send_break(.2)
return self._read_ack(timeout)
def _try_breaking(self, tries=5, timeout=2):
for _ in range(tries):
if self._do_break(timeout):
break
else:
raise CC3200Error("Did not get ACK on break condition")
def _get_version(self):
self._send_packet(OPCODE_GET_VERSION_INFO)
if not self.port is None:
version_data = self._read_packet()
if len(version_data) != 28:
raise CC3200Error(f"Version info should be 28 bytes, got {len(version_data)}")
return CC3x00VersionInfo.from_packet(version_data)
return CC3x00VersionInfo((0,4,1,2), (0,0,0,0), (0,0,0,0), (0,0,0,0), (16,0,0,0))
def _get_storage_list(self):
log.info("Getting storage list...")
if not self.port is None:
self._send_packet(OPCODE_GET_STORAGE_LIST)
with self._serial_timeout(.5):
slist_byte = self.port.read(1)
if len(slist_byte) != 1:
raise CC3200Error("Did not receive storage list byte")
return CC3x00StorageList(slist_byte[0])
return CC3x00StorageList(15)
def _get_storage_info(self, storage_id=STORAGE_ID_SRAM):
log.info("Getting storage info...")
if not self.port is None:
self._send_packet(OPCODE_GET_STORAGE_INFO +
struct.pack(">I", storage_id))
sinfo = self._read_packet()
if len(sinfo) < 4:
raise CC3200Error(f"getting storage info got {len(sinfo)} bytes")
log.info("storage #%d info bytes: %s", storage_id, ", "
.join([hex(x) for x in sinfo]))
return CC3x00StorageInfo.from_packet(sinfo)
return CC3x00StorageInfo(SLFS_BLOCK_SIZE, 1024) #TODO: as parameter
def _erase_blocks(self, start, count, storage_id=STORAGE_ID_SRAM):
command = OPCODE_RAW_STORAGE_ERASE + \
struct.pack(">III", storage_id, start, count)
self._send_packet(command, timeout=self._erase_timeout)
def _send_chunk(self, offset, data, storage_id=STORAGE_ID_SRAM):
if not self.port is None:
command = OPCODE_RAW_STORAGE_WRITE + \
struct.pack(">III", storage_id, offset, len(data))
self._send_packet(command + data)
return
self._output_file.seek(offset)
self._output_file.write(data)
def _raw_write(self, offset, data, storage_id=STORAGE_ID_SRAM):
slist = self._get_storage_list()
if storage_id == STORAGE_ID_SFLASH and not slist.sflash:
raise CC3200Error("no serial flash?!")
if storage_id == STORAGE_ID_SRAM and not slist.sram:
raise CC3200Error("no sram?!")
chunk_size = 4080
sent = 0
while sent < len(data):
chunk = data[sent:sent + chunk_size]
self._send_chunk(offset + sent, chunk, storage_id)
sent += len(chunk)
def _raw_write_file(self, offset, filename, storage_id=STORAGE_ID_SRAM):
with open(filename, 'r') as f:
data = f.read()
return self._raw_write(offset, data, storage_id)
def _read_chunk(self, offset, size, storage_id=STORAGE_ID_SRAM):
if not self.port is None:
# log.info("Reading chunk at 0x%x size 0x%x..." % (offset, size))
command = OPCODE_RAW_STORAGE_READ + \
struct.pack(">III", storage_id, offset, size)
self._send_packet(command)
data = self._read_packet()
if len(data) != size:
raise CC3200Error("invalid received size: %d vs %d" % (len(data), size))
return data
self._image_file.seek(offset)
data = self._image_file.read(size)
return data
def _raw_read(self, offset, size, storage_id=STORAGE_ID_SRAM, sinfo=None, ignore_max_size=False):
slist = self._get_storage_list()
if storage_id == STORAGE_ID_SFLASH and not slist.sflash:
raise CC3200Error("no serial flash?!")
if storage_id == STORAGE_ID_SRAM and not slist.sram:
raise CC3200Error("no sram?!")
if not sinfo:
sinfo = self._get_storage_info(storage_id)
storage_size = sinfo.block_count * sinfo.block_size
if ignore_max_size:
storage_size = offset + size
log.warning("Ignoring storage size limits")
if offset > storage_size:
raise CC3200Error("offset %d is bigger than available mem %d" %
(offset, storage_size))
if size < 1:
size = storage_size - offset
log.info("Setting raw read size to maximum: %d", size)
elif size + offset > storage_size:
raise CC3200Error("size %d + offset %d is bigger than available mem %d" %
(size, offset, storage_size))
log.info("Reading raw storage #%d start 0x%x, size 0x%x..." %
(storage_id, offset, size))
# XXX 4096 works faster, but 256 was sniffed from the uniflash
chunk_size = 4096
rx_data = b''
while size - len(rx_data) > 0:
rx_data += self._read_chunk(offset + len(rx_data),
min(chunk_size, size - len(rx_data)),
storage_id)
sys.stderr.write('.')
sys.stderr.flush()
sys.stderr.write("\n")
return rx_data
def _exec_from_ram(self):
self._send_packet(OPCODE_EXEC_FROM_RAM)
def _get_file_info(self, filename, file_id=-1, inactive=False):
if not self.port is None and file_id == -1:
command = OPCODE_GET_FILE_INFO \
+ struct.pack(">I", len(filename)) \
+ filename.encode()
self._send_packet(command)
finfo = self._read_packet()
if len(finfo) < 5:
raise CC3200Error()
return CC3x00FileInfo.from_packet(finfo)
fat_info = self.get_fat_info(inactive=inactive)
finfo = CC3x00FileInfo(exists=False, size=0)
for file in fat_info.files:
if file_id == -1:
if file.fname == filename:
finfo = CC3x00FileInfo(exists=True, size=file.size_blocks*SLFS_BLOCK_SIZE)
break
elif file.index == file_id:
finfo = CC3x00FileInfo(exists=True, size=file.size_blocks*SLFS_BLOCK_SIZE)
break
return finfo
def _open_file_for_write(self, filename, file_len, fs_flags=None):
for bsize_idx, bsize in enumerate(FLASH_BLOCK_SIZES):
if (bsize * 255) >= file_len:
blocks = int(math.ceil(float(file_len) / bsize))
break
else:
raise CC3200Error("file is too big")
fs_access = SLFS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST
flags = (((fs_access & 0x0f) << 12) |
((bsize_idx & 0x0f) << 8) |
(blocks & 0xff))
if fs_flags is not None:
flags |= (fs_flags & 0xff) << 16
return self._open_file(filename, flags)
def _open_file_for_read(self, filename):
return self._open_file(filename, 0)
def _open_file(self, filename, slfs_flags):
command = OPCODE_START_UPLOAD + struct.pack(">II", slfs_flags, 0) + \
filename.encode() + b'\x00\x00'
self._send_packet(command)
token = self.port.read(4)
if not len(token) == 4:
raise CC3200Error("open")
def _close_file(self, signature=None):
if signature is None: