forked from eerimoq/bincopy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bincopy.py
executable file
·1966 lines (1504 loc) · 62.6 KB
/
bincopy.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
"""Mangling of various file formats that conveys binary information
(Motorola S-Record, Intel HEX, TI-TXT and binary files).
"""
import copy
import binascii
import string
import sys
import argparse
from collections import namedtuple
from io import StringIO
from humanfriendly import format_size
from argparse_addons import Integer
__author__ = 'Erik Moqvist'
__version__ = '17.9.0'
DEFAULT_WORD_SIZE_BITS = 8
# Intel hex types.
IHEX_DATA = 0
IHEX_END_OF_FILE = 1
IHEX_EXTENDED_SEGMENT_ADDRESS = 2
IHEX_START_SEGMENT_ADDRESS = 3
IHEX_EXTENDED_LINEAR_ADDRESS = 4
IHEX_START_LINEAR_ADDRESS = 5
# TI-TXT defines
TI_TXT_BYTES_PER_LINE = 16
class Error(Exception):
"""Bincopy base exception.
"""
pass
class UnsupportedFileFormatError(Error):
def __str__(self):
return 'Unsupported file format.'
class AddDataError(Error):
pass
def crc_srec(hexstr):
"""Calculate the CRC for given Motorola S-Record hexstring.
"""
crc = sum(binascii.unhexlify(hexstr))
crc &= 0xff
crc ^= 0xff
return crc
def crc_ihex(hexstr):
"""Calculate the CRC for given Intel HEX hexstring.
"""
crc = sum(binascii.unhexlify(hexstr))
crc &= 0xff
crc = ((~crc + 1) & 0xff)
return crc
def pack_srec(type_, address, size, data):
"""Create a Motorola S-Record record of given data.
"""
if type_ in '0159':
line = f'{size + 2 + 1:02X}{address:04X}'
elif type_ in '268':
line = f'{size + 3 + 1:02X}{address:06X}'
elif type_ in '37':
line = f'{size + 4 + 1:02X}{address:08X}'
else:
raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")
if data:
line += binascii.hexlify(data).decode('ascii').upper()
return f'S{type_}{line}{crc_srec(line):02X}'
def unpack_srec(record):
"""Unpack given Motorola S-Record record into variables.
"""
# Minimum STSSCC, where T is type, SS is size and CC is crc.
if len(record) < 6:
raise Error(f"record '{record}' too short")
if record[0] != 'S':
raise Error(f"record '{record}' not starting with an 'S'")
value = bytearray.fromhex(record[2:])
size = value[0]
if size != len(value) - 1:
raise Error(f"record '{record}' has wrong size")
type_ = record[1]
if type_ in '0159':
width = 2
elif type_ in '268':
width = 3
elif type_ in '37':
width = 4
else:
raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")
data_offset = (1 + width)
address = int.from_bytes(value[1:data_offset], byteorder='big')
data = value[data_offset:-1]
actual_crc = value[-1]
expected_crc = crc_srec(record[2:-2])
if actual_crc != expected_crc:
raise Error(
f"expected crc '{expected_crc:02X}' in record {record}, but got "
f"'{actual_crc:02X}'")
return (type_, address, len(data), data)
def pack_ihex(type_, address, size, data):
"""Create a Intel HEX record of given data.
"""
line = f'{size:02X}{address:04X}{type_:02X}'
if data:
line += binascii.hexlify(data).decode('ascii').upper()
return f':{line}{crc_ihex(line):02X}'
def unpack_ihex(record):
"""Unpack given Intel HEX record into variables.
"""
# Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is
# type and CC is crc.
if len(record) < 11:
raise Error(f"record '{record}' too short")
if record[0] != ':':
raise Error(f"record '{record}' not starting with a ':'")
value = bytearray.fromhex(record[1:])
size = value[0]
if size != len(value) - 5:
raise Error(f"record '{record}' has wrong size")
address = int.from_bytes(value[1:3], byteorder='big')
type_ = value[3]
data = value[4:-1]
actual_crc = value[-1]
expected_crc = crc_ihex(record[1:-2])
if actual_crc != expected_crc:
raise Error(
f"expected crc '{expected_crc:02X}' in record {record}, but got "
f"'{actual_crc:02X}'")
return (type_, address, size, data)
def pretty_srec(record):
"""Make given Motorola S-Record pretty by adding colors to it.
"""
type_ = record[1:2]
if type_ == '0':
width = 4
type_color = '\033[0;92m'
type_text = ' (header)'
elif type_ in '1':
width = 4
type_color = '\033[0;32m'
type_text = ' (data)'
elif type_ in '2':
width = 6
type_color = '\033[0;32m'
type_text = ' (data)'
elif type_ in '3':
width = 8
type_color = '\033[0;32m'
type_text = ' (data)'
elif type_ in '5':
width = 4
type_color = '\033[0;93m'
type_text = ' (count)'
elif type_ in '6':
width = 6
type_color = '\033[0;93m'
type_text = ' (count)'
elif type_ in '7':
width = 8
type_color = '\033[0;96m'
type_text = ' (start address)'
elif type_ in '8':
width = 6
type_color = '\033[0;96m'
type_text = ' (start address)'
elif type_ in '9':
width = 4
type_color = '\033[0;96m'
type_text = ' (start address)'
else:
raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")
return (type_color + record[:2]
+ '\033[0;95m' + record[2:4]
+ '\033[0;33m' + record[4:4 + width]
+ '\033[0m' + record[4 + width:-2]
+ '\033[0;36m' + record[-2:]
+ '\033[0m' + type_text)
def pretty_ihex(record):
"""Make given Intel HEX record pretty by adding colors to it.
"""
type_ = int(record[7:9], 16)
if type_ == IHEX_DATA:
type_color = '\033[0;32m'
type_text = ' (data)'
elif type_ == IHEX_END_OF_FILE:
type_color = '\033[0;96m'
type_text = ' (end of file)'
elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:
type_color = '\033[0;34m'
type_text = ' (extended segment address)'
elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:
type_color = '\033[0;96m'
type_text = ' (extended linear address)'
elif type_ == IHEX_START_SEGMENT_ADDRESS:
type_color = '\033[0;92m'
type_text = ' (start segment address)'
elif type_ == IHEX_START_LINEAR_ADDRESS:
type_color = '\033[0;92m'
type_text = ' (start linear address)'
else:
raise Error(f"expected type 1..5 in record {record}, but got {type_}")
return ('\033[0;31m' + record[:1]
+ '\033[0;95m' + record[1:3]
+ '\033[0;33m' + record[3:7]
+ type_color + record[7:9]
+ '\033[0m' + record[9:-2]
+ '\033[0;36m' + record[-2:]
+ '\033[0m' + type_text)
def pretty_ti_txt(line):
"""Make given TI TXT line pretty by adding colors to it.
"""
if line.startswith('@'):
line = '\033[0;33m' + line + '\033[0m (segment address)'
elif line == 'q':
line = '\033[0;35m' + line + '\033[0m (end of file)'
else:
line += ' (data)'
return line
def is_srec(records):
try:
unpack_srec(records.partition('\n')[0].rstrip())
except Error:
return False
else:
return True
def is_ihex(records):
try:
unpack_ihex(records.partition('\n')[0].rstrip())
except Error:
return False
else:
return True
def is_ti_txt(data):
try:
return data[0] in ['@', 'q']
except IndexError:
return False
class _Segment:
"""A segment is a chunk data with given minimum and maximum address.
"""
_Chunk = namedtuple('Chunk', ['address', 'data'])
def __init__(self, minimum_address, maximum_address, data, word_size_bytes):
self.minimum_address = minimum_address
self.maximum_address = maximum_address
self.data = data
self._word_size_bytes = word_size_bytes
@property
def address(self):
return self.minimum_address // self._word_size_bytes
def chunks(self, size=32, alignment=1):
"""Return chunks of the data aligned as given by `alignment`. `size`
must be a multiple of `alignment`. Each chunk is returned as a
named two-tuple of its address and data. Both `size` and
`alignment` are in words.
"""
if (size % alignment) != 0:
raise Error(f'size {size} is not a multiple of alignment {alignment}')
size *= self._word_size_bytes
alignment *= self._word_size_bytes
address = self.minimum_address
data = self.data
# First chunk may be shorter than `size` due to alignment.
chunk_offset = (address % alignment)
if chunk_offset != 0:
first_chunk_size = (alignment - chunk_offset)
yield self._Chunk(address // self._word_size_bytes,
data[:first_chunk_size])
address += (first_chunk_size // self._word_size_bytes)
data = data[first_chunk_size:]
else:
first_chunk_size = 0
for offset in range(0, len(data), size):
yield self._Chunk((address + offset) // self._word_size_bytes,
data[offset:offset + size])
def add_data(self, minimum_address, maximum_address, data, overwrite):
"""Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown.
"""
if minimum_address == self.maximum_address:
self.maximum_address = maximum_address
self.data += data
elif maximum_address == self.minimum_address:
self.minimum_address = minimum_address
self.data = data + self.data
elif (overwrite
and minimum_address < self.maximum_address
and maximum_address > self.minimum_address):
self_data_offset = minimum_address - self.minimum_address
# Prepend data.
if self_data_offset < 0:
self_data_offset *= -1
self.data = data[:self_data_offset] + self.data
del data[:self_data_offset]
self.minimum_address = minimum_address
# Overwrite overlapping part.
self_data_left = len(self.data) - self_data_offset
if len(data) <= self_data_left:
self.data[self_data_offset:self_data_offset + len(data)] = data
data = bytearray()
else:
self.data[self_data_offset:] = data[:self_data_left]
data = data[self_data_left:]
# Append data.
if len(data) > 0:
self.data += data
self.maximum_address = maximum_address
else:
raise AddDataError(
'data added to a segment must be adjacent to or overlapping '
'with the original segment data')
def remove_data(self, minimum_address, maximum_address):
"""Remove given data range from this segment. Returns the second
segment if the removed data splits this segment in two.
"""
if ((minimum_address >= self.maximum_address)
and (maximum_address <= self.minimum_address)):
raise Error('cannot remove data that is not part of the segment')
if minimum_address < self.minimum_address:
minimum_address = self.minimum_address
if maximum_address > self.maximum_address:
maximum_address = self.maximum_address
remove_size = maximum_address - minimum_address
part1_size = minimum_address - self.minimum_address
part1_data = self.data[0:part1_size]
part2_data = self.data[part1_size + remove_size:]
if len(part1_data) and len(part2_data):
# Update this segment and return the second segment.
self.maximum_address = self.minimum_address + part1_size
self.data = part1_data
return _Segment(maximum_address,
maximum_address + len(part2_data),
part2_data,
self._word_size_bytes)
else:
# Update this segment.
if len(part1_data) > 0:
self.maximum_address = minimum_address
self.data = part1_data
elif len(part2_data) > 0:
self.minimum_address = maximum_address
self.data = part2_data
else:
self.maximum_address = self.minimum_address
self.data = bytearray()
def __eq__(self, other):
if isinstance(other, tuple):
return self.address, self.data == other
elif isinstance(other, _Segment):
return ((self.minimum_address == other.minimum_address)
and (self.maximum_address == other.maximum_address)
and (self.data == other.data)
and (self._word_size_bytes == other._word_size_bytes))
else:
return False
def __iter__(self):
# Allows unpacking as ``address, data = segment``.
yield self.address
yield self.data
def __repr__(self):
return f'Segment(address={self.address}, data={self.data})'
class _Segments:
"""A list of segments.
"""
def __init__(self, word_size_bytes):
self._word_size_bytes = word_size_bytes
self._current_segment = None
self._current_segment_index = None
self._list = []
def __str__(self):
return '\n'.join([str(s) for s in self._list])
def __iter__(self):
"""Iterate over all segments.
"""
for segment in self._list:
yield segment
def __getitem__(self, index):
try:
return self._list[index]
except IndexError:
raise Error('segment does not exist')
@property
def minimum_address(self):
"""The minimum address of the data, or ``None`` if no data is
available.
"""
if not self._list:
return None
return self._list[0].minimum_address
@property
def maximum_address(self):
"""The maximum address of the data, or ``None`` if no data is
available.
"""
if not self._list:
return None
return self._list[-1].maximum_address
def add(self, segment, overwrite=False):
"""Add segments by ascending address.
"""
if self._list:
if segment.minimum_address == self._current_segment.maximum_address:
# Fast insertion for adjacent segments.
self._current_segment.add_data(segment.minimum_address,
segment.maximum_address,
segment.data,
overwrite)
else:
# Linear insert.
for i, s in enumerate(self._list):
if segment.minimum_address <= s.maximum_address:
break
if segment.minimum_address > s.maximum_address:
# Non-overlapping, non-adjacent after.
self._list.append(segment)
elif segment.maximum_address < s.minimum_address:
# Non-overlapping, non-adjacent before.
self._list.insert(i, segment)
else:
# Adjacent or overlapping.
s.add_data(segment.minimum_address,
segment.maximum_address,
segment.data,
overwrite)
segment = s
self._current_segment = segment
self._current_segment_index = i
# Remove overwritten and merge adjacent segments.
while self._current_segment is not self._list[-1]:
s = self._list[self._current_segment_index + 1]
if self._current_segment.maximum_address >= s.maximum_address:
# The whole segment is overwritten.
del self._list[self._current_segment_index + 1]
elif self._current_segment.maximum_address >= s.minimum_address:
# Adjacent or beginning of the segment overwritten.
self._current_segment.add_data(
self._current_segment.maximum_address,
s.maximum_address,
s.data[self._current_segment.maximum_address - s.minimum_address:],
overwrite=False)
del self._list[self._current_segment_index+1]
break
else:
# Segments are not overlapping, nor adjacent.
break
else:
self._list.append(segment)
self._current_segment = segment
self._current_segment_index = 0
def remove(self, minimum_address, maximum_address):
new_list = []
for segment in self._list:
if (segment.maximum_address <= minimum_address
or maximum_address < segment.minimum_address):
# No overlap.
new_list.append(segment)
else:
# Overlapping, remove overwritten parts segments.
split = segment.remove_data(minimum_address, maximum_address)
if segment.minimum_address < segment.maximum_address:
new_list.append(segment)
if split:
new_list.append(split)
self._list = new_list
def chunks(self, size=32, alignment=1):
"""Iterate over all segments and return chunks of the data aligned as
given by `alignment`. `size` must be a multiple of
`alignment`. Each chunk is returned as a named two-tuple of
its address and data. Both `size` and `alignment` are in
words.
"""
if (size % alignment) != 0:
raise Error(f'size {size} is not a multiple of alignment {alignment}')
for segment in self:
for chunk in segment.chunks(size, alignment):
yield chunk
def __len__(self):
"""Get the number of segments.
"""
return len(self._list)
class BinFile:
"""A binary file.
`filenames` may be a single file or a list of files. Each file is
opened and its data added, given that the format is Motorola
S-Records, Intel HEX or TI-TXT.
Set `overwrite` to ``True`` to allow already added data to be
overwritten.
`word_size_bits` is the number of bits per word.
`header_encoding` is the encoding used to encode and decode the
file header (if any). Give as ``None`` to disable encoding,
leaving the header as an untouched bytes object.
"""
def __init__(self,
filenames=None,
overwrite=False,
word_size_bits=DEFAULT_WORD_SIZE_BITS,
header_encoding='utf-8'):
if (word_size_bits % 8) != 0:
raise Error(
f'word size must be a multiple of 8 bits, but got {word_size_bits} '
f'bits')
self.word_size_bits = word_size_bits
self.word_size_bytes = (word_size_bits // 8)
self._header_encoding = header_encoding
self._header = None
self._execution_start_address = None
self._segments = _Segments(self.word_size_bytes)
if filenames is not None:
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
self.add_file(filename, overwrite=overwrite)
def __setitem__(self, key, data):
"""Write data to given absolute address or address range.
"""
if isinstance(key, slice):
if key.start is None:
address = self.minimum_address
else:
address = key.start
else:
address = key
data = hex((0x80 << (8 * self.word_size_bytes)) | data)
data = binascii.unhexlify(data[4:])
self.add_binary(data, address, overwrite=True)
def __getitem__(self, key):
"""Read data from given absolute address or address range.
"""
if isinstance(key, slice):
if key.start is None:
minimum_address = self.minimum_address
else:
minimum_address = key.start
if key.stop is None:
maximum_address = self.maximum_address
else:
maximum_address = key.stop
return self.as_binary(minimum_address, maximum_address)
else:
if key < self.minimum_address or key >= self.maximum_address:
raise IndexError(f'binary file index {key} out of range')
return int(binascii.hexlify(self.as_binary(key, key + 1)), 16)
def __len__(self):
"""Number of words in the file.
"""
length = sum([len(segment.data) for segment in self.segments])
length //= self.word_size_bytes
return length
def __iadd__(self, other):
self.add_srec(other.as_srec())
return self
def __str__(self):
return str(self._segments)
@property
def execution_start_address(self):
"""The execution start address, or ``None`` if missing.
"""
return self._execution_start_address
@execution_start_address.setter
def execution_start_address(self, address):
self._execution_start_address = address
@property
def minimum_address(self):
"""The minimum address of the data, or ``None`` if the file is empty.
"""
minimum_address = self._segments.minimum_address
if minimum_address is not None:
minimum_address //= self.word_size_bytes
return minimum_address
@property
def maximum_address(self):
"""The maximum address of the data plus one, or ``None`` if the file
is empty.
"""
maximum_address = self._segments.maximum_address
if maximum_address is not None:
maximum_address //= self.word_size_bytes
return maximum_address
@property
def header(self):
"""The binary file header, or ``None`` if missing. See
:class:`BinFile's<.BinFile>` `header_encoding` argument for
encoding options.
"""
if self._header_encoding is None:
return self._header
else:
return self._header.decode(self._header_encoding)
@header.setter
def header(self, header):
if self._header_encoding is None:
if not isinstance(header, bytes):
raise TypeError(f'expected a bytes object, but got {type(header)}')
self._header = header
else:
self._header = header.encode(self._header_encoding)
@property
def segments(self):
"""The segments object. Can be used to iterate over all segments in
the binary.
Below is an example iterating over all segments, two in this
case, and printing them.
>>> for segment in binfile.segments:
... print(segment)
...
Segment(address=0, data=bytearray(b'\\x00\\x01\\x02'))
Segment(address=10, data=bytearray(b'\\x03\\x04\\x05'))
All segments can be split into smaller pieces using the
`chunks(size=32, alignment=1)` method.
>>> for chunk in binfile.segments.chunks(2):
... print(chunk)
...
Chunk(address=0, data=bytearray(b'\\x00\\x01'))
Chunk(address=2, data=bytearray(b'\\x02'))
Chunk(address=10, data=bytearray(b'\\x03\\x04'))
Chunk(address=12, data=bytearray(b'\\x05'))
Each segment can be split into smaller pieces using the
`chunks(size=32, alignment=1)` method on a single segment.
>>> for segment in binfile.segments:
... print(segment)
... for chunk in segment.chunks(2):
... print(chunk)
...
Segment(address=0, data=bytearray(b'\\x00\\x01\\x02'))
Chunk(address=0, data=bytearray(b'\\x00\\x01'))
Chunk(address=2, data=bytearray(b'\\x02'))
Segment(address=10, data=bytearray(b'\\x03\\x04\\x05'))
Chunk(address=10, data=bytearray(b'\\x03\\x04'))
Chunk(address=12, data=bytearray(b'\\x05'))
"""
return self._segments
def add(self, data, overwrite=False):
"""Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten.
"""
if is_srec(data):
self.add_srec(data, overwrite)
elif is_ihex(data):
self.add_ihex(data, overwrite)
elif is_ti_txt(data):
self.add_ti_txt(data, overwrite)
else:
raise UnsupportedFileFormatError()
def add_srec(self, records, overwrite=False):
"""Add given Motorola S-Records string. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
"""
for record in StringIO(records):
record = record.strip()
# Ignore blank lines.
if not record:
continue
type_, address, size, data = unpack_srec(record)
if type_ == '0':
self._header = data
elif type_ in '123':
address *= self.word_size_bytes
self._segments.add(_Segment(address,
address + size,
data,
self.word_size_bytes),
overwrite)
elif type_ in '789':
self.execution_start_address = address
def add_ihex(self, records, overwrite=False):
"""Add given Intel HEX records string. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
"""
extended_segment_address = 0
extended_linear_address = 0
for record in StringIO(records):
record = record.strip()
# Ignore blank lines.
if not record:
continue
type_, address, size, data = unpack_ihex(record)
if type_ == IHEX_DATA:
address = (address
+ extended_segment_address
+ extended_linear_address)
address *= self.word_size_bytes
self._segments.add(_Segment(address,
address + size,
data,
self.word_size_bytes),
overwrite)
elif type_ == IHEX_END_OF_FILE:
pass
elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:
extended_segment_address = int(binascii.hexlify(data), 16)
extended_segment_address *= 16
elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:
extended_linear_address = int(binascii.hexlify(data), 16)
extended_linear_address <<= 16
elif type_ in [IHEX_START_SEGMENT_ADDRESS, IHEX_START_LINEAR_ADDRESS]:
self.execution_start_address = int(binascii.hexlify(data), 16)
else:
raise Error(f"expected type 1..5 in record {record}, but got {type_}")
def add_ti_txt(self, lines, overwrite=False):
"""Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
"""
address = None
eof_found = False
for line in StringIO(lines):
# Abort if data is found after end of file.
if eof_found:
raise Error("bad file terminator")
line = line.strip()
if len(line) < 1:
raise Error("bad line length")
if line[0] == 'q':
eof_found = True
elif line[0] == '@':
try:
address = int(line[1:], 16)
except ValueError:
raise Error("bad section address")
else:
# Try to decode the data.
try:
data = bytearray(binascii.unhexlify(line.replace(' ', '')))
except (TypeError, binascii.Error):
raise Error("bad data")
size = len(data)
# Check that there are correct number of bytes per
# line. There should TI_TXT_BYTES_PER_LINE. Only
# exception is last line of section which may be
# shorter.
if size > TI_TXT_BYTES_PER_LINE:
raise Error("bad line length")
if address is None:
raise Error("missing section address")
self._segments.add(_Segment(address,
address + size,
data,
self.word_size_bytes),
overwrite)
if size == TI_TXT_BYTES_PER_LINE:
address += size
else:
address = None
if not eof_found:
raise Error("missing file terminator")
def add_binary(self, data, address=0, overwrite=False):
"""Add given data at given address. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
"""
address *= self.word_size_bytes
self._segments.add(_Segment(address,
address + len(data),
bytearray(data),
self.word_size_bytes),
overwrite)
def add_file(self, filename, overwrite=False):
"""Open given file and add its data by guessing its format. The format
must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten.
"""
with open(filename, 'r') as fin:
self.add(fin.read(), overwrite)
def add_srec_file(self, filename, overwrite=False):