Added FreedomE300 Simulator target
[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 print "DELETE called for VcsSim"
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, keepAlive=None):
116
117 # keep handles to other processes -- don't let them be
118 # garbage collected yet.
119
120 self.keepAlive = keepAlive
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 stepi(self):
191 output = self.command("stepi")
192 assert "Cannot" not in output
193 return output
194
195 def load(self):
196 output = self.command("load", timeout=60)
197 assert "failed" not in output
198 assert "Transfer rate" in output
199
200 def b(self, location):
201 output = self.command("b %s" % location)
202 assert "not defined" not in output
203 assert "Breakpoint" in output
204 return output
205
206 def hbreak(self, location):
207 output = self.command("hbreak %s" % location)
208 assert "not defined" not in output
209 assert "Hardware assisted breakpoint" in output
210 return output