3b439b1dd2ccb5c225880937c8738fa45cf4d82d
[riscv-isa-sim.git] / tests / testlib.py
1 import os.path
2 import pexpect
3 import subprocess
4 import tempfile
5 import testlib
6 import unittest
7
8 # Note that gdb comes with its own testsuite. I was unable to figure out how to
9 # run that testsuite against the spike simulator.
10
11 def find_file(path):
12 for directory in (os.getcwd(), os.path.dirname(testlib.__file__)):
13 fullpath = os.path.join(directory, path)
14 if os.path.exists(fullpath):
15 return fullpath
16 return None
17
18 def compile(*args):
19 """Compile a single .c file into a binary."""
20 dst = os.path.splitext(args[0])[0]
21 cc = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gcc")
22 cmd = [cc, "-g", "-O", "-o", dst]
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 return dst
33
34 def unused_port():
35 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
36 import socket
37 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
38 s.bind(("",0))
39 port = s.getsockname()[1]
40 s.close()
41 return port
42
43 def spike(binary, halted=False, with_gdb=True, timeout=None):
44 """Launch spike. Return tuple of its process and the port it's running on."""
45 cmd = []
46 if timeout:
47 cmd += ["timeout", str(timeout)]
48
49 cmd += [find_file("spike")]
50 if halted:
51 cmd.append('-H')
52 if with_gdb:
53 port = unused_port()
54 cmd += ['--gdb-port', str(port)]
55 cmd.append('pk')
56 if binary:
57 cmd.append(binary)
58 logfile = open("spike.log", "w")
59 process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile,
60 stderr=logfile)
61 if with_gdb:
62 return process, port
63 else:
64 return process
65
66 class Gdb(object):
67 def __init__(self):
68 path = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")
69 self.child = pexpect.spawn(path)
70 self.child.logfile = file("gdb.log", "w")
71 self.wait()
72 self.command("set width 0")
73 self.command("set height 0")
74
75 def wait(self):
76 """Wait for prompt."""
77 self.child.expect("\(gdb\)")
78
79 def command(self, command):
80 self.child.sendline(command)
81 self.child.expect("\n")
82 self.child.expect("\(gdb\)")
83 return self.child.before.strip()
84
85 def c(self, wait=True):
86 if wait:
87 return self.command("c")
88 else:
89 self.child.sendline("c")
90 self.child.expect("Continuing")
91
92 def interrupt(self):
93 self.child.send("\003");
94 self.child.expect("\(gdb\)")
95
96 def x(self, address, size='w'):
97 output = self.command("x/%s %s" % (size, address))
98 value = int(output.split(':')[1].strip(), 0)
99 return value
100
101 def p(self, obj):
102 output = self.command("p %s" % obj)
103 value = int(output.split('=')[-1].strip())
104 return value
105
106 def stepi(self):
107 return self.command("stepi")