11 # Note that gdb comes with its own testsuite. I was unable to figure out how to
12 # run that testsuite against the spike simulator.
15 for directory
in (os
.getcwd(), os
.path
.dirname(__file__
)):
16 fullpath
= os
.path
.join(directory
, path
)
17 if os
.path
.exists(fullpath
):
21 def compile(args
, xlen
=32): # pylint: disable=redefined-builtin
22 cc
= os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gcc")
25 cmd
.append("-march=rv32imac")
26 cmd
.append("-mabi=ilp32")
28 cmd
.append("-march=rv64imac")
29 cmd
.append("-mabi=lp64")
31 found
= find_file(arg
)
36 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
,
37 stderr
=subprocess
.PIPE
)
38 stdout
, stderr
= process
.communicate()
39 if process
.returncode
:
41 header("Compile failed")
42 print "+", " ".join(cmd
)
46 raise Exception("Compile failed!")
49 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
51 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
53 port
= s
.getsockname()[1]
60 def __init__(self
, sim_cmd
, binary
=None, halted
=False, with_jtag_gdb
=True,
61 timeout
=None, xlen
=64):
62 """Launch spike. Return tuple of its process and the port it's running
65 cmd
= shlex
.split(sim_cmd
)
67 spike
= os
.path
.expandvars("$RISCV/bin/spike")
70 cmd
+= ["--isa", "RV32G"]
72 cmd
+= ["--isa", "RV64G"]
75 cmd
= ["timeout", str(timeout
)] + cmd
77 cmd
+= ["-m0x10000000:0x10000000"]
82 cmd
+= ['--rbb-port', '0']
83 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
84 cmd
.append('programs/infinite_loop')
87 logfile
= open(self
.logname
, "w")
88 logfile
.write("+ %s\n" % " ".join(cmd
))
90 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
91 stdout
=logfile
, stderr
=logfile
)
96 m
= re
.search(r
"Listening for remote bitbang connection on "
97 r
"port (\d+).", open(self
.logname
).read())
99 self
.port
= int(m
.group(1))
100 os
.environ
['REMOTE_BITBANG_PORT'] = m
.group(1)
103 assert self
.port
, "Didn't get spike message about bitbang " \
113 def wait(self
, *args
, **kwargs
):
114 return self
.process
.wait(*args
, **kwargs
)
116 class VcsSim(object):
117 def __init__(self
, sim_cmd
=None, debug
=False):
119 cmd
= shlex
.split(sim_cmd
)
122 cmd
+= ["+jtag_vpi_enable"]
124 cmd
[0] = cmd
[0] + "-debug"
125 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
126 logfile
= open("simv.log", "w")
127 logfile
.write("+ %s\n" % " ".join(cmd
))
129 listenfile
= open("simv.log", "r")
130 listenfile
.seek(0, 2)
131 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
132 stdout
=logfile
, stderr
=logfile
)
135 # Fail if VCS exits early
136 exit_code
= self
.process
.poll()
137 if exit_code
is not None:
138 raise RuntimeError('VCS simulator exited early with status %d'
141 line
= listenfile
.readline()
144 match
= re
.match(r
"^Listening on port (\d+)$", line
)
147 self
.port
= int(match
.group(1))
148 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
157 class Openocd(object):
158 logname
= "openocd.log"
160 def __init__(self
, server_cmd
=None, config
=None, debug
=False):
162 cmd
= shlex
.split(server_cmd
)
164 openocd
= os
.path
.expandvars("$RISCV/bin/riscv-openocd")
169 # This command needs to come before any config scripts on the command
170 # line, since they are executed in order.
172 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
175 # Disable tcl and telnet servers, since they are unused and because
176 # the port numbers will conflict if multiple OpenOCD processes are
177 # running on the same server.
181 "telnet_port disabled",
185 f
= find_file(config
)
187 print("Unable to read file " + config
)
194 logfile
= open(Openocd
.logname
, "w")
195 logfile
.write("+ %s\n" % " ".join(cmd
))
197 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
198 stdout
=logfile
, stderr
=logfile
)
200 # Wait for OpenOCD to have made it through riscv_examine(). When using
201 # OpenOCD to communicate with a simulator this may take a long time,
202 # and gdb will time out when trying to connect if we attempt too early.
206 log
= open(Openocd
.logname
).read()
207 if "Ready for Remote Connections" in log
:
209 if not self
.process
.poll() is None:
211 "OpenOCD exited before completing riscv_examine()")
212 if not messaged
and time
.time() - start
> 1:
214 print "Waiting for OpenOCD to examine RISCV core..."
216 self
.port
= self
._get
_gdb
_server
_port
()
218 def _get_gdb_server_port(self
):
219 """Get port that OpenOCD's gdb server is listening on."""
221 PORT_REGEX
= re
.compile(r
'(?P<port>\d+) \(LISTEN\)')
222 for _
in range(MAX_ATTEMPTS
):
223 with
open(os
.devnull
, 'w') as devnull
:
225 output
= subprocess
.check_output([
227 '-a', # Take the AND of the following selectors
228 '-p{}'.format(self
.process
.pid
), # Filter on PID
229 '-iTCP', # Filter only TCP sockets
231 except subprocess
.CalledProcessError
:
233 matches
= list(PORT_REGEX
.finditer(output
))
234 matches
= [m
for m
in matches
235 if m
.group('port') not in ('6666', '4444')]
239 "OpenOCD listening on multiple ports. Cannot uniquely "
240 "identify gdb server port.")
243 return int(match
.group('port'))
245 raise Exception("Timed out waiting for gdb server to obtain port.")
254 class OpenocdCli(object):
255 def __init__(self
, port
=4444):
256 self
.child
= pexpect
.spawn(
257 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
258 self
.child
.expect("> ")
260 def command(self
, cmd
):
261 self
.child
.sendline(cmd
)
262 self
.child
.expect(cmd
)
263 self
.child
.expect("\n")
264 self
.child
.expect("> ")
265 return self
.child
.before
.strip("\t\r\n \0")
267 def reg(self
, reg
=''):
268 output
= self
.command("reg %s" % reg
)
269 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
270 values
= {r
: int(v
, 0) for r
, v
in matches
}
275 def load_image(self
, image
):
276 output
= self
.command("load_image %s" % image
)
277 if 'invalid ELF file, only 32bits files are supported' in output
:
278 raise TestNotApplicable(output
)
280 class CannotAccess(Exception):
281 def __init__(self
, address
):
282 Exception.__init
__(self
)
283 self
.address
= address
287 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
288 self
.child
= pexpect
.spawn(cmd
)
289 self
.child
.logfile
= open("gdb.log", "w")
290 self
.child
.logfile
.write("+ %s\n" % cmd
)
292 self
.command("set confirm off")
293 self
.command("set width 0")
294 self
.command("set height 0")
296 self
.command("set print entry-values no")
299 """Wait for prompt."""
300 self
.child
.expect(r
"\(gdb\)")
302 def command(self
, command
, timeout
=6000):
303 self
.child
.sendline(command
)
304 self
.child
.expect("\n", timeout
=timeout
)
305 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
306 return self
.child
.before
.strip()
308 def c(self
, wait
=True, timeout
=-1):
310 output
= self
.command("c", timeout
=timeout
)
311 assert "Continuing" in output
314 self
.child
.sendline("c")
315 self
.child
.expect("Continuing")
318 self
.child
.send("\003")
319 self
.child
.expect(r
"\(gdb\)", timeout
=6000)
320 return self
.child
.before
.strip()
322 def x(self
, address
, size
='w'):
323 output
= self
.command("x/%s %s" % (size
, address
))
324 value
= int(output
.split(':')[1].strip(), 0)
327 def p_raw(self
, obj
):
328 output
= self
.command("p %s" % obj
)
329 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
331 raise CannotAccess(int(m
.group(1), 0))
332 return output
.split('=')[-1].strip()
335 output
= self
.command("p/x %s" % obj
)
336 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
338 raise CannotAccess(int(m
.group(1), 0))
339 value
= int(output
.split('=')[-1].strip(), 0)
342 def p_string(self
, obj
):
343 output
= self
.command("p %s" % obj
)
344 value
= shlex
.split(output
.split('=')[-1].strip())[1]
348 output
= self
.command("stepi")
352 output
= self
.command("load", timeout
=6000)
353 assert "failed" not in output
354 assert "Transfer rate" in output
356 def b(self
, location
):
357 output
= self
.command("b %s" % location
)
358 assert "not defined" not in output
359 assert "Breakpoint" in output
362 def hbreak(self
, location
):
363 output
= self
.command("hbreak %s" % location
)
364 assert "not defined" not in output
365 assert "Hardware assisted breakpoint" in output
368 def run_all_tests(module
, target
, parsed
):
369 good_results
= set(('pass', 'not_applicable'))
376 global gdb_cmd
# pylint: disable=global-statement
381 target
.misa
= int(parsed
.misaval
, 16)
382 print "Assuming $MISA value of 0x%x. Skipping ExamineTarget." % target
.misa
384 todo
.append(("ExamineTarget", ExamineTarget
))
386 for name
in dir(module
):
387 definition
= getattr(module
, name
)
388 if type(definition
) == type and hasattr(definition
, 'test') and \
389 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
390 todo
.append((name
, definition
))
392 for name
, definition
in todo
:
393 instance
= definition(target
)
394 result
= instance
.run()
395 results
.setdefault(result
, []).append(name
)
397 if result
not in good_results
and parsed
.fail_fast
:
400 header("ran %d tests in %.0fs" % (count
, time
.time() - start
), dash
=':')
403 for key
, value
in results
.iteritems():
404 print "%d tests returned %s" % (len(value
), key
)
405 if key
not in good_results
:
412 def add_test_run_options(parser
):
414 parser
.add_argument("--fail-fast", "-f", action
="store_true",
415 help="Exit as soon as any test fails.")
416 parser
.add_argument("test", nargs
='*',
417 help="Run only tests that are named here.")
418 parser
.add_argument("--gdb",
419 help="The command to use to start gdb.")
420 parser
.add_argument("--misaval",
421 help="Don't run ExamineTarget, just assume the misa value which is specified.")
423 def header(title
, dash
='-'):
425 dashes
= dash
* (36 - len(title
))
426 before
= dashes
[:len(dashes
)/2]
427 after
= dashes
[len(dashes
)/2:]
428 print "%s[ %s ]%s" % (before
, title
, after
)
434 lines
= open(path
, "r").readlines()
435 if len(lines
) > 1000:
436 for l
in lines
[:500]:
439 for l
in lines
[-500:]:
445 class BaseTest(object):
448 def __init__(self
, target
):
451 self
.target_process
= None
456 def early_applicable(self
):
457 """Return a false value if the test has determined it cannot run
458 without ever needing to talk to the target or server."""
459 # pylint: disable=no-self-use
466 compile_args
= getattr(self
, 'compile_args', None)
468 if compile_args
not in BaseTest
.compiled
:
469 # pylint: disable=star-args
470 BaseTest
.compiled
[compile_args
] = \
471 self
.target
.compile(*compile_args
)
472 self
.binary
= BaseTest
.compiled
.get(compile_args
)
474 def classSetup(self
):
476 self
.target_process
= self
.target
.target()
477 self
.server
= self
.target
.server()
478 self
.logs
.append(self
.server
.logname
)
480 def classTeardown(self
):
482 del self
.target_process
486 If compile_args is set, compile a program and set self.binary.
490 Then call test() and return the result, displaying relevant information
491 if an exception is raised.
494 print "Running", type(self
).__name
__, "...",
497 if not self
.early_applicable():
498 print "not_applicable"
499 return "not_applicable"
501 self
.start
= time
.time()
507 result
= self
.test() # pylint: disable=no-member
508 except TestNotApplicable
:
509 result
= "not_applicable"
510 except Exception as e
: # pylint: disable=broad-except
511 if isinstance(e
, TestFailed
):
515 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
517 if isinstance(e
, TestFailed
):
521 traceback
.print_exc(file=sys
.stdout
)
522 for log
in self
.logs
:
532 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
536 class GdbTest(BaseTest
):
537 def __init__(self
, target
):
538 BaseTest
.__init
__(self
, target
)
541 def classSetup(self
):
542 BaseTest
.classSetup(self
)
543 self
.logs
.append("gdb.log")
546 self
.gdb
= Gdb(gdb_cmd
)
551 self
.gdb
.command("file %s" % self
.binary
)
553 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
554 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
557 "target extended-remote localhost:%d" % self
.server
.port
)
559 # FIXME: OpenOCD doesn't handle PRIV now
560 #self.gdb.p("$priv=3")
562 def classTeardown(self
):
564 BaseTest
.classTeardown(self
)
566 class ExamineTarget(GdbTest
):
568 self
.target
.misa
= self
.gdb
.p("$misa")
571 if (self
.target
.misa
>> 30) == 1:
573 elif (self
.target
.misa
>> 62) == 2:
575 elif (self
.target
.misa
>> 126) == 3:
581 if self
.target
.misa
& (1<<i
):
582 txt
+= chr(i
+ ord('A'))
585 class TestFailed(Exception):
586 def __init__(self
, message
):
587 Exception.__init
__(self
)
588 self
.message
= message
590 class TestNotApplicable(Exception):
591 def __init__(self
, message
):
592 Exception.__init
__(self
)
593 self
.message
= message
595 def assertEqual(a
, b
):
597 raise TestFailed("%r != %r" % (a
, b
))
599 def assertNotEqual(a
, b
):
601 raise TestFailed("%r == %r" % (a
, b
))
605 raise TestFailed("%r not in %r" % (a
, b
))
607 def assertNotIn(a
, b
):
609 raise TestFailed("%r in %r" % (a
, b
))
611 def assertGreater(a
, b
):
613 raise TestFailed("%r not greater than %r" % (a
, b
))
615 def assertLess(a
, b
):
617 raise TestFailed("%r not less than %r" % (a
, b
))
621 raise TestFailed("%r is not True" % a
)
623 def assertRegexpMatches(text
, regexp
):
624 if not re
.search(regexp
, text
):
625 raise TestFailed("can't find %r in %r" % (regexp
, text
))