forked from eerimoq/bincopy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bincopy.py
executable file
·1075 lines (787 loc) · 33.2 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 and binary files).
"""
from __future__ import print_function, division
import binascii
import string
import sys
import argparse
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
__author__ = 'Erik Moqvist'
__version__ = '10.0.0'
DEFAULT_WORD_SIZE_BITS = 8
class Error(Exception):
"""Bincopy base exception.
"""
pass
def crc_srec(hexstr):
"""Calculate the CRC for given Motorola S-Record hexstring.
"""
crc = sum(bytearray(binascii.unhexlify(hexstr)))
crc &= 0xff
crc ^= 0xff
return crc
def crc_ihex(hexstr):
"""Calculate crc for given Intel HEX hexstring.
"""
crc = sum(bytearray(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 = '%02X%04X' % (size + 2 + 1, address)
elif type_ in '268':
line = '%02X%06X' % (size + 3 + 1, address)
elif type_ in '37':
line = '%02X%08X' % (size + 4 + 1, address)
else:
raise Error("expected record type 0..3 or 5..9, but got '{}'".format(
type_))
if data:
line += binascii.hexlify(data).decode('utf-8').upper()
return 'S%s%s%02X' % (type_, line, crc_srec(line))
def unpack_srec(record):
"""Unpack given Motorola S-Record record into variables.
"""
if len(record) < 6:
raise Error("record '{}' too short".format(record))
if record[0] != 'S':
raise Error("record '{}' not starting with an 'S'".format(
record))
size = int(record[2:4], 16)
type_ = record[1:2]
if type_ in '0159':
width = 4
elif type_ in '268':
width = 6
elif type_ in '37':
width = 8
else:
raise Error("expected record type 0..3 or 5..9, but got '{}'".format(
type_))
address = int(record[4:4+width], 16)
data = binascii.unhexlify(record[4 + width:4 + 2 * size - 2])
actual_crc = int(record[4 + 2 * size - 2:], 16)
expected_crc = crc_srec(record[2:4 + 2 * size - 2])
if actual_crc != expected_crc:
raise Error("expected crc {:#02x} in record {}, but got {:#02x}".format(
expected_crc,
record,
actual_crc))
return (type_, address, size - 1 - width // 2, data)
def pack_ihex(type_, address, size, data):
"""Create a Intel HEX record of given data.
"""
line = '%02X%04X%02X' % (size, address, type_)
if data:
line += binascii.hexlify(data).decode('utf-8').upper()
return ':%s%02X' % (line, crc_ihex(line))
def unpack_ihex(record):
"""Unpack given Intel HEX record into variables.
"""
if len(record) < 11:
raise Error("record '{}' too short".format(record))
if record[0] != ':':
raise Error("record '{}' not starting with a ':'".format(record))
size = int(record[1:3], 16)
address = int(record[3:7], 16)
type_ = int(record[7:9], 16)
if size > 0:
data = binascii.unhexlify(record[9:9 + 2 * size])
else:
data = ''
actual_crc = int(record[9 + 2 * size:], 16)
expected_crc = crc_ihex(record[1:9 + 2 * size])
if actual_crc != expected_crc:
raise Error("expected crc {:#02x} in record {}, but got {:#02x}".format(
expected_crc,
record,
actual_crc))
return (type_, address, size, data)
def is_srec(records):
try:
unpack_srec(records.splitlines()[0])
except Error:
return False
else:
return True
def is_ihex(records):
try:
unpack_ihex(records.splitlines()[0])
except Error:
return False
else:
return True
class _Segment(object):
"""A segment is a chunk data with given minimum and maximum address.
"""
def __init__(self, minimum_address, maximum_address, data):
self.minimum_address = minimum_address
self.maximum_address = maximum_address
self.data = data
def __str__(self):
return '[%#x .. %#x]: %s' % (self.minimum_address,
self.maximum_address,
binascii.hexlify(self.data))
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 Error('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)
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()
class _Segments(object):
"""A list of segments.
"""
def __init__(self):
self.current_segment = None
self.current_segment_index = None
self.list = []
def __str__(self):
return '\n'.join([s.__str__() for s in self.list])
@property
def minimum_address(self):
"""The minimum address of the data.
"""
if not self.list:
return None
return self.list[0].minimum_address
@property
def maximum_address(self):
"""The maximum address of the data.
"""
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 iter(self, size=32):
"""Iterate over all segments and return chunks of the data.
"""
for segment in self.list:
data = segment.data
address = segment.minimum_address
for offset in range(0, len(data), size):
yield address + offset, data[offset:offset + size]
def __len__(self):
"""Get the length of the binary, including holes in the data.
"""
if not self.list:
return 0
else:
return self.maximum_address - self.minimum_address
class BinFile(object):
"""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 or Intel HEX. Set `overwrite` to True to allow already
added data to be overwritten. `word_size_bits` is the number of
bits per word.
"""
def __init__(self,
filenames=None,
overwrite=False,
word_size_bits=DEFAULT_WORD_SIZE_BITS):
if (word_size_bits % 8) != 0:
raise Error('word size must be a multiple of 8 bits')
self.word_size_bits = word_size_bits
self.word_size_bytes = (word_size_bits // 8)
self._header = None
self._execution_start_address = None
self.segments = _Segments()
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
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
size = maximum_address - minimum_address
else:
if key < self.minimum_address or key >= self.maximum_address:
return b''
minimum_address = key
size = 1
return self.as_binary(minimum_address)[:size]
def __len__(self):
return len(self.segments)
def __iadd__(self, other):
self.add_srec(other.as_srec())
return self
def __str__(self):
return self.segments.__str__()
@property
def execution_start_address(self):
"""The execution start address.
"""
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.
"""
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.
"""
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.
"""
return self._header
@header.setter
def header(self, header):
self._header = header
def add(self, data, overwrite=False):
"""Add given data by guessing its format. The format must be Motorola
S-Records or Intel HEX. 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)
else:
raise Error('unsupported file format')
def add_srec(self, records, overwrite=False):
"""Add given Motorola S-Records. Set `overwrite` to True to allow
already added data to be overwritten.
"""
for record in StringIO(records):
type_, address, size, data = unpack_srec(record.strip())
if type_ == '0':
self._header = data.decode('utf-8')
elif type_ in '123':
address *= self.word_size_bytes
self.segments.add(_Segment(address, address + size,
bytearray(data)),
overwrite)
elif type_ in '789':
self.execution_start_address = address
def add_ihex(self, records, overwrite=False):
"""Add given Intel HEX records. Set `overwrite` to True to allow
already added data to be overwritten.
"""
extmaximum_addressed_segment_address = 0
extmaximum_addressed_linear_address = 0
for record in StringIO(records):
type_, address, size, data = unpack_ihex(record.strip())
if type_ == 0:
address = (address
+ extmaximum_addressed_segment_address
+ extmaximum_addressed_linear_address)
address *= self.word_size_bytes
self.segments.add(_Segment(address, address + size,
bytearray(data)),
overwrite)
elif type_ == 1:
pass
elif type_ == 2:
extmaximum_addressed_segment_address = int(
binascii.hexlify(data), 16) * 16
elif type_ == 3:
pass
elif type_ == 4:
extmaximum_addressed_linear_address = (int(
binascii.hexlify(data), 16) * 65536)
elif type_ == 5:
self.execution_start_address = int(binascii.hexlify(data), 16)
else:
raise Error("expected type 1..5 in record {}, but got '{}'".format(
record,
type_))
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.
"""
self.segments.add(_Segment(address, address + len(data),
bytearray(data)),
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 or Intel HEX. 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):
"""Open given Motorola S-Records file and add its records. Set
`overwrite` to True to allow already added data to be
overwritten.
"""
with open(filename, "r") as fin:
self.add_srec(fin.read(), overwrite)
def add_ihex_file(self, filename, overwrite=False):
"""Open given Intel HEX file and add its records. Set `overwrite` to
True to allow already added data to be overwritten.
"""
with open(filename, "r") as fin:
self.add_ihex(fin.read(), overwrite)
def add_binary_file(self, filename, address=0, overwrite=False):
"""Open given binary file and add its contents. Set `overwrite` to
True to allow already added data to be overwritten.
"""
with open(filename, "rb") as fin:
self.add_binary(fin.read(), address, overwrite)
def as_srec(self, number_of_data_bytes=32, address_length_bits=32):
"""Format the binary file as Motorola S-Records records and return
them as a string.
:param number_of_data_bytes: Number of data bytes in each
record.
:param address_length_bits: Number of address bits in each
record.
:returns: A string of Motorola S-Records records separated by
a newline.
"""
header = []
if self._header:
encoded_header = self._header.encode('utf-8')
record = pack_srec('0', 0, len(encoded_header), encoded_header)
header.append(record)
type_ = str((address_length_bits // 8) - 1)
if type_ not in ['1', '2', '3']:
raise Error("expected type 1..3, bit got {}".format(type_))
data = [pack_srec(type_,
address // self.word_size_bytes,
len(data),
data)
for address, data in self.segments.iter(number_of_data_bytes)]
number_of_records = len(data)
if number_of_records <= 0xffff:
footer = [pack_srec('5', number_of_records, 0, None)]
elif number_of_records <= 0xffffff:
footer = [pack_srec('6', number_of_records, 0, None)]
else:
raise Error('too many records {}'.format(number_of_records))
# Add the execution start address.
if self.execution_start_address is not None:
if type_ == '1':
record = pack_srec('9', self.execution_start_address, 0, None)
elif type_ == '2':
record = pack_srec('8', self.execution_start_address, 0, None)
else:
record = pack_srec('7', self.execution_start_address, 0, None)
footer.append(record)
return '\n'.join(header + data + footer) + '\n'
def as_ihex(self, number_of_data_bytes=32, address_length_bits=32):
"""Format the binary file as Intel HEX records and return them as a
string.
:param number_of_data_bytes: Number of data bytes in each
record.
:param address_length_bits: Number of address bits in each
record.
:returns: A string of Intel HEX records separated by a
newline.
"""
data_address = []
extended_linear_address = 0
for address, data in self.segments.iter(number_of_data_bytes):
address //= self.word_size_bytes
address_upper_16_bits = (address >> 16)
address_lower_16_bits = (address & 0xffff)
if address_length_bits == 32:
# All segments are sorted by address. Update the
# extended linear address when required.
if address_upper_16_bits > extended_linear_address:
extended_linear_address = address_upper_16_bits
packed = pack_ihex(4,
0,
2,
binascii.unhexlify(
'%04X'
% extended_linear_address))
data_address.append(packed)
else:
raise Error('expected address length 32, but got {}'.format(
address_length_bits))
data_address.append(pack_ihex(0,
address_lower_16_bits,
len(data), data))
footer = []
if self.execution_start_address is not None:
if address_length_bits == 16:
address = binascii.unhexlify(
'%08X' % self.execution_start_address)
footer.append(pack_ihex(3, 0, 4, address))
elif address_length_bits == 32:
address = binascii.unhexlify(
'%08X' % self.execution_start_address)
footer.append(pack_ihex(5, 0, 4, address))
footer.append(pack_ihex(1, 0, 0, None))
return '\n'.join(data_address + footer) + '\n'
def as_binary(self, minimum_address=None, padding=None):
"""Return a byte string of all data.
:param minimum_address: Absolute start address of the
resulting binary data.
:param padding: Word value of the padding between non-adjacent
segments. Give as a bytes object of length 1
when the word size is 8 bits, length 2 when
the word size is 16 bits, and so on.
:returns: A byte string of the binary data.
"""
if len(self.segments) == 0:
return b''
res = b''
current_maximum_address = self.minimum_address
if padding is None:
padding = b'\xff' * self.word_size_bytes
if minimum_address is not None:
if minimum_address >= self.maximum_address:
return b''
current_maximum_address = minimum_address
for address, data in self.segments.iter():
address //= self.word_size_bytes
if address < current_maximum_address:
if address + len(data) <= current_maximum_address:
continue
data = data[current_maximum_address - address:]
current_maximum_address = address
res += padding * (address - current_maximum_address)
res += data
current_maximum_address = address + (len(data) // self.word_size_bytes)
return res
def as_array(self, minimum_address=None, padding=None, separator=', '):
"""Format the binary file as a string values separated by given
separator. This function can be used to generate array
initialization code for c and other languages.
:param minimum_address: Start address of the resulting binary
data. Must be less than or equal to
the start address of the binary data.
:param padding: Value of the padding between not adjacent
segments.
:param separator: Value separator.
:returns: A string of the separated values.
"""
binary_data = self.as_binary(minimum_address, padding)
words = []
for offset in range(0, len(binary_data), self.word_size_bytes):
word = 0
for byte in binary_data[offset:offset + self.word_size_bytes]:
word <<= 8
word += byte
words.append('0x{:02x}'.format(word))
return separator.join(words)
def as_hexdump(self):
"""Format the binary file as a hexdump. This function can be used to
generate array.
:returns: A hexdump string.
"""
def format_line(address, data):
"""`data` is a list of integers and None for unused elements.
"""
hexdata = []
for byte in data:
if byte is not None:
elem = '{:02x}'.format(byte)
else:
elem = ' '
hexdata.append(elem)
first_half = ' '.join(hexdata[0:8])
second_half = ' '.join(hexdata[8:16])
ascii = ''
for byte in data:
non_dot_characters = set(string.printable)
non_dot_characters -= set(string.whitespace)
non_dot_characters |= set(' ')
if byte is None:
ascii += ' '
elif chr(byte) in non_dot_characters:
ascii += chr(byte)
else:
ascii += '.'
return '{:08x} {:23s} {:23s} |{:16s}|'.format(
address, first_half, second_half, ascii)
lines = []
line_address = None
line_data = []
for address, data in self.segments.iter(16):
if line_address is None:
# A new line.
line_address = address - (address % 16)
line_data = []
elif address > line_address + 16:
line_data += [None] * (16 - len(line_data))
lines.append(format_line(line_address, line_data))
if address > line_address + 32:
lines.append('...')
line_address = address - (address % 16)
line_data = []
line_data += [None] * (address - (line_address + len(line_data)))
line_left = 16 - len(line_data)
if len(data) > line_left:
line_data += [byte for byte in data[0:line_left]]
lines.append(format_line(line_address, line_data))
line_address = line_address + 16
line_data = [byte for byte in data[line_left:]]
elif len(data) == line_left:
line_data += [byte for byte in data]
lines.append(format_line(line_address, line_data))
line_address = None
else:
line_data += [byte for byte in data]
if line_address is not None:
line_data += [None] * (16 - len(line_data))
lines.append(format_line(line_address, line_data))
return '\n'.join(lines) + '\n'
def fill(self, value=b'\xff'):
"""Fill all empty space between segments with given value.
:param value: Value to fill with.
"""
previous_segment_maximum_address = None
fill_segments = []
for minimum_address, maximum_address, _ in self.iter_segments():
if previous_segment_maximum_address is not None:
fill_size = minimum_address - previous_segment_maximum_address
fill_size_words = fill_size // self.word_size_bytes
fill_segments.append(_Segment(
previous_segment_maximum_address,
previous_segment_maximum_address + fill_size,
value * fill_size_words))
previous_segment_maximum_address = maximum_address
for segment in fill_segments:
self.segments.add(segment)
def exclude(self, minimum_address, maximum_address):
"""Exclude given range and keep the rest.
:param minimum_address: First word address to exclude (including).
:param maximum_address: Last word address to exclude (excluding).
"""
if maximum_address < minimum_address:
raise Error('bad address range')
minimum_address *= self.word_size_bytes
maximum_address *= self.word_size_bytes
self.segments.remove(minimum_address, maximum_address)
def crop(self, minimum_address, maximum_address):
"""Keep given range and discard the rest.
:param minimum_address: First word address to keep (including).
:param maximum_address: Last word address to keep (excluding).
"""
minimum_address *= self.word_size_bytes
maximum_address *= self.word_size_bytes
maximum_address_address = self.segments.maximum_address
self.segments.remove(0, minimum_address)
self.segments.remove(maximum_address, maximum_address_address)
def info(self):
"""Return a string of human readable information about the binary
file.
"""
info = ''