WIP on debug testing.
[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):
20 """Compile a single .c file into a binary."""
21 dst = os.path.splitext(args[0])[0]
22 cc = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gcc")
23 cmd = [cc, "-g", "-O", "-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, binary, halted=False, with_gdb=True, timeout=None):
46 """Launch spike. Return tuple of its process and the port it's running on."""
47 cmd = []
48 if timeout:
49 cmd += ["timeout", str(timeout)]
50
51 cmd += [find_file("spike")]
52 if halted:
53 cmd.append('-H')
54 if with_gdb:
55 self.port = unused_port()
56 cmd += ['--gdb-port', str(self.port)]
57 cmd.append('pk')
58 if binary:
59 cmd.append(binary)
60 logfile = open("spike.log", "w")
61 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
62 stderr=logfile)
63
64 def __del__(self):
65 try:
66 self.process.kill()
67 self.process.wait()
68 except OSError:
69 pass
70
71 def wait(self, *args, **kwargs):
72 return self.process.wait(*args, **kwargs)
73
74 class Openocd(object):
75 def __init__(self, cmd=None, config=None, debug=True):
76 if cmd:
77 cmd = shlex.split(cmd)
78 else:
79 cmd = ["openocd"]
80 if config:
81 cmd += ["-f", find_file(config)]
82 if debug:
83 cmd.append("-d")
84 logfile = open("openocd.log", "w")
85 self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
86 stderr=logfile)
87 # TODO: Pick a random port
88 self.port = 3333
89
90 def __del__(self):
91 try:
92 self.process.kill()
93 self.process.wait()
94 except OSError:
95 pass
96
97 class Gdb(object):
98 def __init__(self):
99 path = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")
100 self.child = pexpect.spawn(path)
101 self.child.logfile = file("gdb.log", "w")
102 self.wait()
103 self.command("set width 0")
104 self.command("set height 0")
105 # Force consistency.
106 self.command("set print entry-values no")
107
108 def wait(self):
109 """Wait for prompt."""
110 self.child.expect("\(gdb\)")
111
112 def command(self, command, timeout=-1):
113 self.child.sendline(command)
114 self.child.expect("\n", timeout=timeout)
115 self.child.expect("\(gdb\)", timeout=timeout)
116 return self.child.before.strip()
117
118 def c(self, wait=True):
119 if wait:
120 return self.command("c")
121 else:
122 self.child.sendline("c")
123 self.child.expect("Continuing")
124
125 def interrupt(self):
126 self.child.send("\003");
127 self.child.expect("\(gdb\)")
128
129 def x(self, address, size='w'):
130 output = self.command("x/%s %s" % (size, address))
131 value = int(output.split(':')[1].strip(), 0)
132 return value
133
134 def p(self, obj):
135 output = self.command("p %s" % obj)
136 value = int(output.split('=')[-1].strip())
137 return value
138
139 def stepi(self):
140 return self.command("stepi")