2590f4643f6a9373ada16d2fe92353f0410471b4
[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 raise ValueError("Couldn't find %r." % path)
17
18 def compile(src):
19 """Compile a single .c file into a binary."""
20 src = find_file(src)
21 dst = os.path.splitext(src)[0]
22 cc = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gcc")
23 cmd = "%s -g -o %s %s" % (cc, dst, src)
24 result = os.system(cmd)
25 assert result == 0, "%r failed" % cmd
26 return dst
27
28 def spike(binary, halted=False):
29 cmd = [find_file("spike")]
30 if halted:
31 cmd.append('-H')
32 cmd += ['pk', binary]
33 logfile = open("spike.log", "w")
34 return subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile, stderr=logfile)
35
36 class Gdb(object):
37 def __init__(self):
38 path = os.path.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")
39 self.child = pexpect.spawn(path)
40 self.child.logfile = file("gdb.log", "w")
41 self.wait()
42 self.command("set width 0")
43 self.command("set height 0")
44
45 def wait(self):
46 """Wait for prompt."""
47 self.child.expect("\(gdb\)")
48
49 def command(self, command):
50 self.child.sendline(command)
51 self.child.expect("\n")
52 self.child.expect("\(gdb\)")
53 return self.child.before.strip()
54
55 def x(self, address, size='w'):
56 output = self.command("x/%s %s" % (size, address))
57 value = int(output.split(':')[1].strip(), 0)
58 return value
59
60 def p(self, obj):
61 output = self.command("p %s" % obj)
62 value = int(output.split('=')[-1].strip())
63 return value
64
65 def stepi(self):
66 return self.command("stepi")