Some code cleanup
[riscv-tests.git] / debug / testlib.py
1 import os.path
2 import pexpect
3 import shlex
4 import subprocess
5 import tempfile
6 import testlib
7 import unittest
8 import time
9
10 # Note that gdb comes with its own testsuite. I was unable to figure out how to
11 # run that testsuite against the spike simulator.
12
13 def find_file(path):
14 for directory in (os.getcwd(), os.path.dirname(testlib.__file__)):
15 fullpath = os.path.join(directory, path)
16 if os.path.exists(fullpath):
17 return fullpath
18 return None
19
20 def compile(args, xlen=32):
21 cc = os.path.expandvars("$RISCV/bin/riscv%d-unknown-elf-gcc" % xlen)
22 cmd = [cc, "-g"]
23 for arg in args:
24 found = find_file(arg)
25 if found:
26 cmd.append(found)
27 else:
28 cmd.append(arg)
29 cmd = " ".join(cmd)
30 result = os.system(cmd)
31 assert result == 0, "%r failed" % cmd
32
33 def unused_port():
34 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
35 import socket
36 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
37 s.bind(("",0))
38 port = s.getsockname()[1]
39 s.close()
40 return port
41
42 class Spike(object):
43 def __init__(self, cmd, binary=None, halted=False, with_gdb=True, timeout=None,
44 xlen=64):
45 """Launch spike. Return tuple of its process and the port it's running on."""
46 if cmd:
47 cmd = shlex.split(cmd)
48 else:
49 cmd = ["spike"]
50 if (xlen == 32):
51 cmd += ["--isa", "RV32"]
52
53 if timeout:
54 cmd = ["timeout", str(timeout)] + cmd
55
56 if halted:
57 cmd.append('-H')
58 if with_gdb:
59 self.port = unused_port()
60 cmd += ['--gdb-port', str(self.port)]
61 cmd.append('pk')
62 if binary:
63 cmd.append(binary)
64 logfile = open("spike.log", "w")
65 logfile.write("+ %s\n" % " ".join(cmd))
66 logfile.flush()
67 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
68 stderr=logfile)
69
70 def __del__(self):
71 try:
72 self.process.kill()
73 self.process.wait()
74 except OSError:
75 pass
76
77 def wait(self, *args, **kwargs):
78 return self.process.wait(*args, **kwargs)
79
80 class VcsSim(object):
81 def __init__(self, simv=None, debug=False):
82 if simv:
83 cmd = shlex.split(simv)
84 else:
85 cmd = ["simv"]
86 cmd += ["+jtag_vpi_enable"]
87 if debug:
88 cmd[0] = cmd[0] + "-debug"
89 cmd += ["+vcdplusfile=output/gdbserver.vpd"]
90 logfile = open("simv.log", "w")
91 logfile.write("+ %s\n" % " ".join(cmd))
92 logfile.flush()
93 listenfile = open("simv.log", "r")
94 listenfile.seek(0,2)
95 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
96 stderr=logfile)
97 done = False
98 while (not done):
99 line = listenfile.readline()
100 if (not line):
101 time.sleep(1)
102 if ("Listening on port 5555" in line):
103 done = True
104
105 def __del__(self):
106 try:
107 self.process.kill()
108 self.process.wait()
109 except OSError:
110 pass
111
112
113 class Openocd(object):
114 def __init__(self, cmd=None, config=None, debug=False, otherProcess=None):
115
116 # keep handles to other processes -- don't let them be
117 # garbage collected yet.
118
119 self.otherProcess = otherProcess
120 if cmd:
121 cmd = shlex.split(cmd)
122 else:
123 cmd = ["openocd"]
124 if config:
125 cmd += ["-f", find_file(config)]
126 if debug:
127 cmd.append("-d")
128 logfile = open("openocd.log", "w")
129 logfile.write("+ %s\n" % " ".join(cmd))
130 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
131 stderr=logfile)
132 # TODO: Pick a random port
133 self.port = 3333
134
135 def __del__(self):
136 try:
137 self.process.kill()
138 self.process.wait()
139 except OSError:
140 pass
141
142 class Gdb(object):
143 def __init__(self,
144 cmd=os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
145 self.child = pexpect.spawn(cmd)
146 self.child.logfile = file("gdb.log", "w")
147 self.child.logfile.write("+ %s\n" % cmd)
148 self.wait()
149 self.command("set confirm off")
150 self.command("set width 0")
151 self.command("set height 0")
152 # Force consistency.
153 self.command("set print entry-values no")
154
155 def wait(self):
156 """Wait for prompt."""
157 self.child.expect("\(gdb\)")
158
159 def command(self, command, timeout=-1):
160 self.child.sendline(command)
161 self.child.expect("\n", timeout=timeout)
162 self.child.expect("\(gdb\)", timeout=timeout)
163 return self.child.before.strip()
164
165 def c(self, wait=True):
166 if wait:
167 output = self.command("c")
168 assert "Continuing" in output
169 return output
170 else:
171 self.child.sendline("c")
172 self.child.expect("Continuing")
173
174 def interrupt(self):
175 self.child.send("\003");
176 self.child.expect("\(gdb\)")
177 return self.child.before.strip()
178
179 def x(self, address, size='w'):
180 output = self.command("x/%s %s" % (size, address))
181 value = int(output.split(':')[1].strip(), 0)
182 return value
183
184 def p(self, obj):
185 output = self.command("p/x %s" % obj)
186 value = int(output.split('=')[-1].strip(), 0)
187 return value
188
189 def stepi(self):
190 output = self.command("stepi")
191 assert "Cannot" not in output
192 return output
193
194 def load(self):
195 output = self.command("load", timeout=60)
196 assert "failed" not in output
197 assert "Transfer rate" in output
198
199 def b(self, location):
200 output = self.command("b %s" % location)
201 assert "not defined" not in output
202 assert "Breakpoint" in output
203 return output
204
205 def hbreak(self, location):
206 output = self.command("hbreak %s" % location)
207 assert "not defined" not in output
208 assert "Hardware assisted breakpoint" in output
209 return output