-
Notifications
You must be signed in to change notification settings - Fork 0
/
platforms.py
222 lines (190 loc) · 6.63 KB
/
platforms.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
# SPDX-License-Identifier: Apache-2.0 or CC0-1.0
from mupq import mupq
import abc
import re
import serial
import subprocess
import time
import os
import tqdm
try:
import chipwhisperer as cw
except ImportError:
pass
class Qemu(mupq.Platform):
start_pat = re.compile('.*={4,}\n', re.DOTALL)
end_pat = re.compile('#\n', re.DOTALL)
def __init__(self, qemu, machine):
super().__init__()
self.qemu = qemu
self.machine = machine
self.platformname = "qemu"
def __enter__(self):
return super().__enter__()
def __exit__(self, *args, **kwargs):
return super().__exit__(*args, **kwargs)
def run(self, binary_path, expiterations=1):
if expiterations > 1:
pb = tqdm.tqdm(total=expiterations, leave=False, desc="Running...")
args = [
self.qemu,
"-M",
self.machine,
"-nographic",
"-semihosting",
"-kernel",
binary_path,
]
self.log.info(f'Running QEMU: {" ".join(args)}')
try:
proc = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, encoding="ascii")
output = ""
while "#" not in output:
buf = proc.stdout.readline()
# print(buf)
output += buf
if expiterations > 1:
if "+" in buf:
pb.update(buf.count("+"))
else:
pb.refresh()
proc.wait()
except Exception:
try:
if proc and proc.poll is not None:
proc.kill()
except Exception:
pass
raise
start = self.start_pat.search(output)
end = self.end_pat.search(output, start.end())
if end is None:
return 'ERROR'
proc.wait()
if expiterations > 1:
pb.close()
return output[start.end():end.start()]
class SerialCommsPlatform(mupq.Platform):
# Start pattern is at least five equal signs
start_pat = re.compile(b'.*={4,}\n', re.DOTALL)
def __init__(self, tty="/dev/ttyACM0", baud=38400, timeout=1):
super().__init__()
self._dev = serial.Serial(tty, baud, timeout=timeout)
def __enter__(self):
return super().__enter__()
def __exit__(self, *args, **kwargs):
self._dev.close()
return super().__exit__(*args, **kwargs)
def run(self, binary_path, expiterations=1):
if expiterations > 1:
pb = tqdm.tqdm(total=expiterations, leave=False, desc="Running...")
self._dev.reset_input_buffer()
self.flash(binary_path)
# Wait for the first equal sign
if self._dev.read_until(b'=')[-1] != b'='[0]:
raise RuntimeError('Timout waiting for start')
# Wait for the end of the equal delimiter
start = self._dev.read_until(b'\n')
self.log.debug(f'Found start pattern: {start}')
if self.start_pat.fullmatch(start) is None:
raise RuntimeError('Start does not match')
# Wait for the end
output = bytearray()
while len(output) == 0 or output[-1] != b'#'[0]:
data = self._dev.read_until(b'#', 128)
if expiterations > 1:
if b"+" in data:
pb.update(data.count(b"+"))
else:
pb.refresh()
output.extend(data)
if expiterations > 1:
pb.close()
return output[:-1].decode('utf-8', 'ignore')
@abc.abstractmethod
def flash(self, binary_path):
pass
class OpenOCD(SerialCommsPlatform):
def __init__(self, script, tty="/dev/ttyACM0", baud=38400, timeout=60):
super().__init__(tty, baud, timeout)
self.script = script
def flash(self, binary_path):
subprocess.check_call(
["openocd", "-f", self.script, "-c", f"program {binary_path} verify reset exit"],
# stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
class StLink(SerialCommsPlatform):
def flash(self, binary_path):
extraargs = []
if os.getenv("MUPQ_ST_FLASH_ARGS") is not None:
extraargs = os.getenv("MUPQ_ST_FLASH_ARGS").split()
subprocess.check_call(
["st-flash"] + extraargs + ["--reset", "write", binary_path, "0x8000000"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
class ChipWhisperer(mupq.Platform):
# Start pattern is at least five equal signs
start_pat = re.compile('.*={4,}\n', re.DOTALL)
# End pattern is a hash with a newline
end_pat = re.compile('.*#\n', re.DOTALL)
def __init__(self):
super().__init__()
self.platformname = "cw"
self.scope = cw.scope()
self.target = cw.target(self.scope)
self.scope.default_setup()
def __enter__(self):
return super().__enter__()
def __exit__(self, *args, **kwargs):
self.target.close()
return super().__exit__(*args, **kwargs)
def device(self):
return self.wrapper
def reset_target(self):
self.scope.io.nrst = 'low'
time.sleep(0.05)
self.scope.io.nrst = 'high'
time.sleep(0.05)
def flash(self, binary_path):
prog = cw.programmers.STM32FProgrammer()
prog.scope = self.scope
prog.open()
prog.find()
prog.erase()
prog.program(binary_path, memtype="flash", verify=False)
prog.close()
def run(self, binary_path, expiterations=1):
if expiterations > 1:
pb = tqdm.tqdm(total=expiterations, leave=False, desc="Running...")
self.flash(binary_path)
self.target.flush()
self.reset_target()
data = ''
# Wait for the first equal sign
while '=' not in data:
data += self.target.read()
# Wait for the end of the equal delimiter
match = None
while match is None:
buf = self.target.read()
data += buf
match = self.start_pat.match(data)
# Remove the start pattern
data = data[match.end():]
# Wait for the end
match = None
while match is None:
buf = self.target.read()
data += buf
if expiterations > 1:
if "+" in buf:
pb.update(buf.count("+"))
else:
pb.refresh()
match = self.end_pat.match(data)
# Remove stop pattern and return
if expiterations > 1:
pb.close()
return data[:match.end() - 2]