bb604a7dcf4928f55dee37b91642c3c0c3a4faef
[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 #cmd.append("-l") #<<<
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 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
67 stderr=logfile)
68
69 def __del__(self):
70 try:
71 self.process.kill()
72 self.process.wait()
73 except OSError:
74 pass
75
76 def wait(self, *args, **kwargs):
77 return self.process.wait(*args, **kwargs)
78
79 class Openocd(object):
80 def __init__(self, cmd=None, config=None, debug=True):
81 if cmd:
82 cmd = shlex.split(cmd)
83 else:
84 cmd = ["openocd"]
85 if config:
86 cmd += ["-f", find_file(config)]
87 if debug:
88 cmd.append("-d")
89 logfile = open("openocd.log", "w")
90 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
91 stderr=logfile)
92 # TODO: Pick a random port
93 self.port = 3333
94
95 def __del__(self):
96 try:
97 self.process.kill()
98 self.process.wait()
99 except OSError:
100 pass
101
102 class Gdb(object):
103 def __init__(self):
104 path = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")
105 self.child = pexpect.spawn(path)
106 self.child.logfile = file("gdb.log", "w")
107 self.wait()
108 self.command("set width 0")
109 self.command("set height 0")
110 # Force consistency.
111 self.command("set print entry-values no")
112
113 def wait(self):
114 """Wait for prompt."""
115 self.child.expect("\(gdb\)")
116
117 def command(self, command, timeout=-1):
118 self.child.sendline(command)
119 self.child.expect("\n", timeout=timeout)
120 self.child.expect("\(gdb\)", timeout=timeout)
121 return self.child.before.strip()
122
123 def c(self, wait=True):
124 if wait:
125 output = self.command("c")
126 assert "Continuing" in output
127 return output
128 else:
129 self.child.sendline("c")
130 self.child.expect("Continuing")
131
132 def interrupt(self):
133 self.child.send("\003");
134 self.child.expect("\(gdb\)")
135 return self.child.before.strip()
136
137 def x(self, address, size='w'):
138 output = self.command("x/%s %s" % (size, address))
139 value = int(output.split(':')[1].strip(), 0)
140 return value
141
142 def p(self, obj):
143 output = self.command("p/x %s" % obj)
144 value = int(output.split('=')[-1].strip(), 0)
145 return value
146
147 def stepi(self):
148 output = self.command("stepi")
149 assert "Cannot" not in output
150 return output
151
152 def load(self):
153 output = self.command("load", timeout=120)
154 assert "failed" not in output
155 assert "Transfer rate" in output
156
157 def b(self, location):
158 output = self.command("b %s" % location)
159 assert "not defined" not in output
160 assert "Breakpoint" in output
161 return output