Made some progress towards working with spike.
[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
9 # Note that gdb comes with its own testsuite. I was unable to figure out how to
10 # run that testsuite against the spike simulator.
11
12 def find_file(path):
13 for directory in (os.getcwd(), os.path.dirname(testlib.__file__)):
14 fullpath = os.path.join(directory, path)
15 if os.path.exists(fullpath):
16 return fullpath
17 return None
18
19 def compile(args, xlen=32):
20 """Compile a single .c file into a binary."""
21 dst = os.path.splitext(args[0])[0]
22 cc = os.path.expandvars("$RISCV/bin/riscv%d-unknown-elf-gcc" % xlen)
23 cmd = [cc, "-g", "-o", dst]
24 for arg in args:
25 found = find_file(arg)
26 if found:
27 cmd.append(found)
28 else:
29 cmd.append(arg)
30 cmd = " ".join(cmd)
31 result = os.system(cmd)
32 assert result == 0, "%r failed" % cmd
33 return dst
34
35 def unused_port():
36 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
37 import socket
38 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
39 s.bind(("",0))
40 port = s.getsockname()[1]
41 s.close()
42 return port
43
44 class Spike(object):
45 def __init__(self, cmd, binary=None, halted=False, with_gdb=True, timeout=None):
46 """Launch spike. Return tuple of its process and the port it's running on."""
47 if cmd:
48 cmd = shlex.split(cmd)
49 else:
50 cmd = ["spike"]
51
52 if timeout:
53 cmd = ["timeout", str(timeout)] + cmd
54
55 if halted:
56 cmd.append('-H')
57 if with_gdb:
58 self.port = unused_port()
59 cmd += ['--gdb-port', str(self.port)]
60 cmd.append('pk')
61 if binary:
62 cmd.append(binary)
63 logfile = open("spike.log", "w")
64 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
65 stderr=logfile)
66
67 def __del__(self):
68 try:
69 self.process.kill()
70 self.process.wait()
71 except OSError:
72 pass
73
74 def wait(self, *args, **kwargs):
75 return self.process.wait(*args, **kwargs)
76
77 class Openocd(object):
78 def __init__(self, cmd=None, config=None, debug=True):
79 if cmd:
80 cmd = shlex.split(cmd)
81 else:
82 cmd = ["openocd"]
83 if config:
84 cmd += ["-f", find_file(config)]
85 if debug:
86 cmd.append("-d")
87 logfile = open("openocd.log", "w")
88 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
89 stderr=logfile)
90 # TODO: Pick a random port
91 self.port = 3333
92
93 def __del__(self):
94 try:
95 self.process.kill()
96 self.process.wait()
97 except OSError:
98 pass
99
100 class Gdb(object):
101 def __init__(self):
102 path = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")
103 self.child = pexpect.spawn(path)
104 self.child.logfile = file("gdb.log", "w")
105 self.wait()
106 self.command("set width 0")
107 self.command("set height 0")
108 # Force consistency.
109 self.command("set print entry-values no")
110
111 def wait(self):
112 """Wait for prompt."""
113 self.child.expect("\(gdb\)")
114
115 def command(self, command, timeout=-1):
116 self.child.sendline(command)
117 self.child.expect("\n", timeout=timeout)
118 self.child.expect("\(gdb\)", timeout=timeout)
119 return self.child.before.strip()
120
121 def c(self, wait=True):
122 if wait:
123 output = self.command("c")
124 assert "Continuing" in output
125 return output
126 else:
127 self.child.sendline("c")
128 self.child.expect("Continuing")
129
130 def interrupt(self):
131 self.child.send("\003");
132 self.child.expect("\(gdb\)")
133 return self.child.before.strip()
134
135 def x(self, address, size='w'):
136 output = self.command("x/%s %s" % (size, address))
137 value = int(output.split(':')[1].strip(), 0)
138 return value
139
140 def p(self, obj):
141 output = self.command("p/x %s" % obj)
142 value = int(output.split('=')[-1].strip(), 0)
143 return value
144
145 def stepi(self):
146 return self.command("stepi")
147
148 def load(self, binary):
149 return self.command("load %s" % binary)
150
151 def b(self, location):
152 output = self.command("b %s" % location)
153 assert "not defined" not in output
154 assert "Breakpoint" in output
155 return output