Limit spike RAM so I can run valgrind on it.
[riscv-tests.git] / debug / testlib.py
1 import os.path
2 import shlex
3 import subprocess
4 import tempfile
5 import unittest
6 import time
7
8 import pexpect
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(__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("-m32")
62 cmd.append('pk')
63 if binary:
64 cmd.append(binary)
65 logfile = open("spike.log", "w")
66 logfile.write("+ %s\n" % " ".join(cmd))
67 logfile.flush()
68 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
69 stderr=logfile)
70
71 def __del__(self):
72 try:
73 self.process.kill()
74 self.process.wait()
75 except OSError:
76 pass
77
78 def wait(self, *args, **kwargs):
79 return self.process.wait(*args, **kwargs)
80
81 class VcsSim(object):
82 def __init__(self, simv=None, debug=False):
83 if simv:
84 cmd = shlex.split(simv)
85 else:
86 cmd = ["simv"]
87 cmd += ["+jtag_vpi_enable"]
88 if debug:
89 cmd[0] = cmd[0] + "-debug"
90 cmd += ["+vcdplusfile=output/gdbserver.vpd"]
91 logfile = open("simv.log", "w")
92 logfile.write("+ %s\n" % " ".join(cmd))
93 logfile.flush()
94 listenfile = open("simv.log", "r")
95 listenfile.seek(0,2)
96 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
97 stderr=logfile)
98 done = False
99 while (not done):
100 line = listenfile.readline()
101 if (not line):
102 time.sleep(1)
103 if ("Listening on port 5555" in line):
104 done = True
105
106 def __del__(self):
107 try:
108 self.process.kill()
109 self.process.wait()
110 except OSError:
111 pass
112
113
114 class Openocd(object):
115 def __init__(self, cmd=None, config=None, debug=False, otherProcess=None):
116
117 # keep handles to other processes -- don't let them be
118 # garbage collected yet.
119
120 self.otherProcess = otherProcess
121 if cmd:
122 cmd = shlex.split(cmd)
123 else:
124 cmd = ["openocd"]
125 if config:
126 cmd += ["-f", find_file(config)]
127 if debug:
128 cmd.append("-d")
129 logfile = open("openocd.log", "w")
130 logfile.write("+ %s\n" % " ".join(cmd))
131 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
132 stderr=logfile)
133 # TODO: Pick a random port
134 self.port = 3333
135
136 def __del__(self):
137 try:
138 self.process.kill()
139 self.process.wait()
140 except OSError:
141 pass
142
143 class Gdb(object):
144 def __init__(self,
145 cmd=os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
146 self.child = pexpect.spawn(cmd)
147 self.child.logfile = file("gdb.log", "w")
148 self.child.logfile.write("+ %s\n" % cmd)
149 self.wait()
150 self.command("set confirm off")
151 self.command("set width 0")
152 self.command("set height 0")
153 # Force consistency.
154 self.command("set print entry-values no")
155
156 def wait(self):
157 """Wait for prompt."""
158 self.child.expect("\(gdb\)")
159
160 def command(self, command, timeout=-1):
161 self.child.sendline(command)
162 self.child.expect("\n", timeout=timeout)
163 self.child.expect("\(gdb\)", timeout=timeout)
164 return self.child.before.strip()
165
166 def c(self, wait=True):
167 if wait:
168 output = self.command("c")
169 assert "Continuing" in output
170 return output
171 else:
172 self.child.sendline("c")
173 self.child.expect("Continuing")
174
175 def interrupt(self):
176 self.child.send("\003");
177 self.child.expect("\(gdb\)")
178 return self.child.before.strip()
179
180 def x(self, address, size='w'):
181 output = self.command("x/%s %s" % (size, address))
182 value = int(output.split(':')[1].strip(), 0)
183 return value
184
185 def p(self, obj):
186 output = self.command("p/x %s" % obj)
187 value = int(output.split('=')[-1].strip(), 0)
188 return value
189
190 def p_string(self, obj):
191 output = self.command("p %s" % obj)
192 value = shlex.split(output.split('=')[-1].strip())[1]
193 return value
194
195 def stepi(self):
196 output = self.command("stepi")
197 assert "Cannot" not in output
198 return output
199
200 def load(self):
201 output = self.command("load", timeout=60)
202 assert "failed" not in output
203 assert "Transfer rate" in output
204
205 def b(self, location):
206 output = self.command("b %s" % location)
207 assert "not defined" not in output
208 assert "Breakpoint" in output
209 return output
210
211 def hbreak(self, location):
212 output = self.command("hbreak %s" % location)
213 assert "not defined" not in output
214 assert "Hardware assisted breakpoint" in output
215 return output