forked from kierdavis/IHex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ihex.py
187 lines (153 loc) · 5.46 KB
/
ihex.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
from binascii import hexlify, unhexlify
import struct
from six import int2byte, byte2int, indexbytes, iteritems, PY2
from six.moves import map
class IHex(object):
def __init__(self):
self.areas = {}
self.start = None
self.mode = 8
self.row_bytes = 16
@classmethod
def read(cls, lines):
ihex = cls()
segbase = 0
for line in lines:
line = line.strip()
if not line:
continue
t, a, d = IHex.parse_line(line)
if t == 0x00:
ihex.insert_data(segbase + a, d)
elif t == 0x01:
break # Should we check for garbage after this?
elif t == 0x02:
ihex.mode = 16
segbase = struct.unpack(">H", d[0:2])[0] << 4
elif t == 0x03:
ihex.mode = 16
ihex.start = struct.unpack(">2H", d[0:2])
elif t == 0x04:
ihex.mode = 32
segbase = struct.unpack(">H", d[0:2])[0] << 16
elif t == 0x05:
ihex.mode = 32
ihex.start = struct.unpack(">I", d[0:4])[0]
else:
raise ValueError("Invalid type byte")
return ihex
@classmethod
def read_file(cls, filename):
with open(filename) as f:
return cls.read(f)
@property
def row_bytes(self):
return self._row_bytes
@row_bytes.setter
def row_bytes(self, row_bytes):
"""Set output hex file row width (bytes represented per row)."""
if row_bytes < 1 or row_bytes > 0xff:
raise ValueError("Value out of range: (%r)" % row_bytes)
self._row_bytes = row_bytes
def get_area(self, addr):
# FIXME: py2
for start, data in iteritems(self.areas):
end = start + len(data)
if start <= addr <= end:
return start
raise ValueError("No area contains address {:#x}.".format(addr))
def insert_data(self, istart, idata):
iend = istart + len(idata)
try:
area = self.get_area(istart)
except ValueError:
self.areas[istart] = idata
else:
data = self.areas[area]
# istart - iend + len(idata) + len(data)
self.areas[area] = data[:istart-area] + idata + data[iend-area:]
@staticmethod
def calc_checksum(bytes):
# FIXME: py2
if PY2:
bytes = map(ord, bytes)
total = sum(bytes)
return (-total) & 0xFF
@staticmethod
def parse_line(rawline):
if rawline[0] != ":":
raise ValueError(
"Invalid line start character {!r}".format(rawline[0])
)
try:
line = unhexlify(rawline[1:])
except TypeError as err:
raise ValueError(
"Invalid hex data {!r}".format(rawline[1:])
)
length, addr, record_type = struct.unpack(">BHB", line[:4])
dataend = length + 4
data = line[4:dataend]
# FIXME: py2
if indexbytes(line, dataend) != IHex.calc_checksum(line[:dataend]):
raise ValueError("Checksums do not match")
return (record_type, addr, data)
def make_line(self, record_type, addr, data):
line = struct.pack(">BHB", len(data), addr, record_type) + data
return ":{}{}\n".format(
hexlify(line).decode("ascii").upper(),
hexlify(
# FIXME: py2
int2byte(IHex.calc_checksum(line))
).decode("ascii").upper()
)
def write(self):
output = []
# FIXME: py2
for start, data in sorted(iteritems(self.areas)):
i = 0
segbase = 0
while i < len(data):
chunk = data[i:i + self.row_bytes]
addr = start
newsegbase = segbase
if self.mode == 8:
addr = addr & 0xFFFF
elif self.mode == 16:
t = addr & 0xFFFF
newsegbase = (addr - t) >> 4
addr = t
if newsegbase != segbase:
output.append(
self.make_line(0x02, 0, struct.pack(">H", newsegbase))
)
segbase = newsegbase
elif self.mode == 32:
newsegbase = addr >> 16
addr = addr & 0xFFFF
if newsegbase != segbase:
output.append(
self.make_line(0x04, 0, struct.pack(">H", newsegbase))
)
segbase = newsegbase
output.append(self.make_line(0x00, addr, chunk))
i += self.row_bytes
start += self.row_bytes
if self.start is not None:
if self.mode == 16:
output.append(
self.make_line(
0x03,
0,
struct.pack(">2H", self.start[0], self.start[1])
)
)
elif self.mode == 32:
output.append(
self.make_line(0x05, 0, struct.pack(">I", self.start))
)
output.append(self.make_line(0x01, 0, b""))
return "".join(output)
def write_file(self, filename):
with open(filename, "w") as f:
f.write(self.write())