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/riscv%d-unknown-elf-gcc" % xlen
)
25 found
= find_file(arg
)
30 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
,
31 stderr
=subprocess
.PIPE
)
32 stdout
, stderr
= process
.communicate()
33 if process
.returncode
:
35 header("Compile failed")
36 print "+", " ".join(cmd
)
40 raise Exception("Compile failed!")
43 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
45 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
47 port
= s
.getsockname()[1]
54 def __init__(self
, cmd
, binary
=None, halted
=False, with_jtag_gdb
=True,
55 timeout
=None, xlen
=64):
56 """Launch spike. Return tuple of its process and the port it's running
59 cmd
= shlex
.split(cmd
)
63 cmd
+= ["--isa", "RV32"]
66 cmd
= ["timeout", str(timeout
)] + cmd
71 cmd
+= ['--rbb-port', '0']
72 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
77 logfile
= open(self
.logname
, "w")
78 logfile
.write("+ %s\n" % " ".join(cmd
))
80 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
81 stdout
=logfile
, stderr
=logfile
)
86 m
= re
.search(r
"Listening for remote bitbang connection on port (\d+).",
87 file(self
.logname
).read())
89 self
.port
= int(m
.group(1))
90 os
.environ
['REMOTE_BITBANG_PORT'] = m
.group(1)
93 assert self
.port
, "Didn't get spike message about bitbang connection"
102 def wait(self
, *args
, **kwargs
):
103 return self
.process
.wait(*args
, **kwargs
)
105 class VcsSim(object):
106 def __init__(self
, simv
=None, debug
=False):
108 cmd
= shlex
.split(simv
)
111 cmd
+= ["+jtag_vpi_enable"]
113 cmd
[0] = cmd
[0] + "-debug"
114 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
115 logfile
= open("simv.log", "w")
116 logfile
.write("+ %s\n" % " ".join(cmd
))
118 listenfile
= open("simv.log", "r")
119 listenfile
.seek(0, 2)
120 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
121 stdout
=logfile
, stderr
=logfile
)
124 line
= listenfile
.readline()
127 match
= re
.match(r
"^Listening on port (\d+)$", line
)
130 self
.port
= int(match
.group(1))
131 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
140 class Openocd(object):
141 logname
= "openocd.log"
143 def __init__(self
, cmd
=None, config
=None, debug
=False):
145 cmd
= shlex
.split(cmd
)
147 cmd
= ["openocd", "-d"]
149 # This command needs to come before any config scripts on the command
150 # line, since they are executed in order.
152 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
155 # Disable tcl and telnet servers, since they are unused and because
156 # the port numbers will conflict if multiple OpenOCD processes are
157 # running on the same server.
161 "telnet_port disabled",
165 cmd
+= ["-f", find_file(config
)]
169 logfile
= open(Openocd
.logname
, "w")
170 logfile
.write("+ %s\n" % " ".join(cmd
))
172 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
173 stdout
=logfile
, stderr
=logfile
)
175 # Wait for OpenOCD to have made it through riscv_examine(). When using
176 # OpenOCD to communicate with a simulator this may take a long time,
177 # and gdb will time out when trying to connect if we attempt too early.
181 log
= open(Openocd
.logname
).read()
182 if "Examined RISCV core" in log
:
184 if not self
.process
.poll() is None:
186 "OpenOCD exited before completing riscv_examine()")
187 if not messaged
and time
.time() - start
> 1:
189 print "Waiting for OpenOCD to examine RISCV core..."
191 self
.port
= self
._get
_gdb
_server
_port
()
193 def _get_gdb_server_port(self
):
194 """Get port that OpenOCD's gdb server is listening on."""
196 PORT_REGEX
= re
.compile(r
'(?P<port>\d+) \(LISTEN\)')
197 for _
in range(MAX_ATTEMPTS
):
198 with
open(os
.devnull
, 'w') as devnull
:
200 output
= subprocess
.check_output([
202 '-a', # Take the AND of the following selectors
203 '-p{}'.format(self
.process
.pid
), # Filter on PID
204 '-iTCP', # Filter only TCP sockets
206 except subprocess
.CalledProcessError
:
208 matches
= list(PORT_REGEX
.finditer(output
))
209 matches
= [m
for m
in matches
210 if m
.group('port') not in ('6666', '4444')]
214 "OpenOCD listening on multiple ports. Cannot uniquely "
215 "identify gdb server port.")
218 return int(match
.group('port'))
220 raise Exception("Timed out waiting for gdb server to obtain port.")
229 class OpenocdCli(object):
230 def __init__(self
, port
=4444):
231 self
.child
= pexpect
.spawn(
232 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
233 self
.child
.expect("> ")
235 def command(self
, cmd
):
236 self
.child
.sendline(cmd
)
237 self
.child
.expect(cmd
)
238 self
.child
.expect("\n")
239 self
.child
.expect("> ")
240 return self
.child
.before
.strip("\t\r\n \0")
242 def reg(self
, reg
=''):
243 output
= self
.command("reg %s" % reg
)
244 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
245 values
= {r
: int(v
, 0) for r
, v
in matches
}
250 def load_image(self
, image
):
251 output
= self
.command("load_image %s" % image
)
252 if 'invalid ELF file, only 32bits files are supported' in output
:
253 raise TestNotApplicable(output
)
255 class CannotAccess(Exception):
256 def __init__(self
, address
):
257 Exception.__init
__(self
)
258 self
.address
= address
262 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
263 self
.child
= pexpect
.spawn(cmd
)
264 self
.child
.logfile
= open("gdb.log", "w")
265 self
.child
.logfile
.write("+ %s\n" % cmd
)
267 self
.command("set confirm off")
268 self
.command("set width 0")
269 self
.command("set height 0")
271 self
.command("set print entry-values no")
274 """Wait for prompt."""
275 self
.child
.expect(r
"\(gdb\)")
277 def command(self
, command
, timeout
=-1):
278 self
.child
.sendline(command
)
279 self
.child
.expect("\n", timeout
=timeout
)
280 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
281 return self
.child
.before
.strip()
283 def c(self
, wait
=True):
285 output
= self
.command("c")
286 assert "Continuing" in output
289 self
.child
.sendline("c")
290 self
.child
.expect("Continuing")
293 self
.child
.send("\003")
294 self
.child
.expect(r
"\(gdb\)", timeout
=60)
295 return self
.child
.before
.strip()
297 def x(self
, address
, size
='w'):
298 output
= self
.command("x/%s %s" % (size
, address
))
299 value
= int(output
.split(':')[1].strip(), 0)
302 def p_raw(self
, obj
):
303 output
= self
.command("p %s" % obj
)
304 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
306 raise CannotAccess(int(m
.group(1), 0))
307 return output
.split('=')[-1].strip()
310 output
= self
.command("p/x %s" % obj
)
311 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
313 raise CannotAccess(int(m
.group(1), 0))
314 value
= int(output
.split('=')[-1].strip(), 0)
317 def p_string(self
, obj
):
318 output
= self
.command("p %s" % obj
)
319 value
= shlex
.split(output
.split('=')[-1].strip())[1]
323 output
= self
.command("stepi")
327 output
= self
.command("load", timeout
=60)
328 assert "failed" not in output
329 assert "Transfer rate" in output
331 def b(self
, location
):
332 output
= self
.command("b %s" % location
)
333 assert "not defined" not in output
334 assert "Breakpoint" in output
337 def hbreak(self
, location
):
338 output
= self
.command("hbreak %s" % location
)
339 assert "not defined" not in output
340 assert "Hardware assisted breakpoint" in output
343 def run_all_tests(module
, target
, parsed
):
344 good_results
= set(('pass', 'not_applicable'))
351 global gdb_cmd
# pylint: disable=global-statement
354 todo
= [("ExamineTarget", ExamineTarget
)]
355 for name
in dir(module
):
356 definition
= getattr(module
, name
)
357 if type(definition
) == type and hasattr(definition
, 'test') and \
358 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
359 todo
.append((name
, definition
))
361 for name
, definition
in todo
:
362 instance
= definition(target
)
363 result
= instance
.run()
364 results
.setdefault(result
, []).append(name
)
366 if result
not in good_results
and parsed
.fail_fast
:
369 header("ran %d tests in %.0fs" % (count
, time
.time() - start
), dash
=':')
372 for key
, value
in results
.iteritems():
373 print "%d tests returned %s" % (len(value
), key
)
374 if key
not in good_results
:
381 def add_test_run_options(parser
):
382 parser
.add_argument("--fail-fast", "-f", action
="store_true",
383 help="Exit as soon as any test fails.")
384 parser
.add_argument("test", nargs
='*',
385 help="Run only tests that are named here.")
386 parser
.add_argument("--gdb",
387 help="The command to use to start gdb.")
389 def header(title
, dash
='-'):
391 dashes
= dash
* (36 - len(title
))
392 before
= dashes
[:len(dashes
)/2]
393 after
= dashes
[len(dashes
)/2:]
394 print "%s[ %s ]%s" % (before
, title
, after
)
400 lines
= open(path
, "r").readlines()
401 if len(lines
) > 1000:
402 for l
in lines
[:500]:
405 for l
in lines
[-500:]:
411 class BaseTest(object):
414 def __init__(self
, target
):
417 self
.target_process
= None
422 def early_applicable(self
):
423 """Return a false value if the test has determined it cannot run
424 without ever needing to talk to the target or server."""
425 # pylint: disable=no-self-use
432 compile_args
= getattr(self
, 'compile_args', None)
434 if compile_args
not in BaseTest
.compiled
:
435 # pylint: disable=star-args
436 BaseTest
.compiled
[compile_args
] = \
437 self
.target
.compile(*compile_args
)
438 self
.binary
= BaseTest
.compiled
.get(compile_args
)
440 def classSetup(self
):
442 self
.target_process
= self
.target
.target()
443 self
.server
= self
.target
.server()
444 self
.logs
.append(self
.server
.logname
)
446 def classTeardown(self
):
448 del self
.target_process
452 If compile_args is set, compile a program and set self.binary.
456 Then call test() and return the result, displaying relevant information
457 if an exception is raised.
460 print "Running", type(self
).__name
__, "...",
463 if not self
.early_applicable():
464 print "not_applicable"
465 return "not_applicable"
467 self
.start
= time
.time()
473 result
= self
.test() # pylint: disable=no-member
474 except TestNotApplicable
:
475 result
= "not_applicable"
476 except Exception as e
: # pylint: disable=broad-except
477 if isinstance(e
, TestFailed
):
481 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
483 if isinstance(e
, TestFailed
):
487 traceback
.print_exc(file=sys
.stdout
)
488 for log
in self
.logs
:
498 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
502 class GdbTest(BaseTest
):
503 def __init__(self
, target
):
504 BaseTest
.__init
__(self
, target
)
507 def classSetup(self
):
508 BaseTest
.classSetup(self
)
509 self
.logs
.append("gdb.log")
512 self
.gdb
= Gdb(gdb_cmd
)
517 self
.gdb
.command("file %s" % self
.binary
)
519 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
520 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
523 "target extended-remote localhost:%d" % self
.server
.port
)
525 self
.gdb
.p("$priv=3")
527 def classTeardown(self
):
529 BaseTest
.classTeardown(self
)
531 class ExamineTarget(GdbTest
):
533 self
.target
.misa
= self
.gdb
.p("$misa")
536 if (self
.target
.misa
>> 30) == 1:
538 elif (self
.target
.misa
>> 62) == 2:
540 elif (self
.target
.misa
>> 126) == 3:
546 if self
.target
.misa
& (1<<i
):
547 txt
+= chr(i
+ ord('A'))
550 class TestFailed(Exception):
551 def __init__(self
, message
):
552 Exception.__init
__(self
)
553 self
.message
= message
555 class TestNotApplicable(Exception):
556 def __init__(self
, message
):
557 Exception.__init
__(self
)
558 self
.message
= message
560 def assertEqual(a
, b
):
562 raise TestFailed("%r != %r" % (a
, b
))
564 def assertNotEqual(a
, b
):
566 raise TestFailed("%r == %r" % (a
, b
))
570 raise TestFailed("%r not in %r" % (a
, b
))
572 def assertNotIn(a
, b
):
574 raise TestFailed("%r in %r" % (a
, b
))
576 def assertGreater(a
, b
):
578 raise TestFailed("%r not greater than %r" % (a
, b
))
580 def assertLess(a
, b
):
582 raise TestFailed("%r not less than %r" % (a
, b
))
586 raise TestFailed("%r is not True" % a
)
588 def assertRegexpMatches(text
, regexp
):
589 if not re
.search(regexp
, text
):
590 raise TestFailed("can't find %r in %r" % (regexp
, text
))