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 "
87 r
"port (\d+).", open(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 " \
103 def wait(self
, *args
, **kwargs
):
104 return self
.process
.wait(*args
, **kwargs
)
106 class VcsSim(object):
107 def __init__(self
, simv
=None, debug
=False):
109 cmd
= shlex
.split(simv
)
112 cmd
+= ["+jtag_vpi_enable"]
114 cmd
[0] = cmd
[0] + "-debug"
115 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
116 logfile
= open("simv.log", "w")
117 logfile
.write("+ %s\n" % " ".join(cmd
))
119 listenfile
= open("simv.log", "r")
120 listenfile
.seek(0, 2)
121 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
122 stdout
=logfile
, stderr
=logfile
)
125 line
= listenfile
.readline()
128 match
= re
.match(r
"^Listening on port (\d+)$", line
)
131 self
.port
= int(match
.group(1))
132 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
141 class Openocd(object):
142 logname
= "openocd.log"
144 def __init__(self
, cmd
=None, config
=None, debug
=False):
146 cmd
= shlex
.split(cmd
)
148 cmd
= ["openocd", "-d"]
150 # This command needs to come before any config scripts on the command
151 # line, since they are executed in order.
153 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
156 # Disable tcl and telnet servers, since they are unused and because
157 # the port numbers will conflict if multiple OpenOCD processes are
158 # running on the same server.
162 "telnet_port disabled",
166 f
= find_file(config
)
168 print("Unable to read file " + config
)
175 logfile
= open(Openocd
.logname
, "w")
176 logfile
.write("+ %s\n" % " ".join(cmd
))
178 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
179 stdout
=logfile
, stderr
=logfile
)
181 # Wait for OpenOCD to have made it through riscv_examine(). When using
182 # OpenOCD to communicate with a simulator this may take a long time,
183 # and gdb will time out when trying to connect if we attempt too early.
187 log
= open(Openocd
.logname
).read()
188 if "Examined RISCV core" in log
:
190 if not self
.process
.poll() is None:
192 "OpenOCD exited before completing riscv_examine()")
193 if not messaged
and time
.time() - start
> 1:
195 print "Waiting for OpenOCD to examine RISCV core..."
197 self
.port
= self
._get
_gdb
_server
_port
()
199 def _get_gdb_server_port(self
):
200 """Get port that OpenOCD's gdb server is listening on."""
202 PORT_REGEX
= re
.compile(r
'(?P<port>\d+) \(LISTEN\)')
203 for _
in range(MAX_ATTEMPTS
):
204 with
open(os
.devnull
, 'w') as devnull
:
206 output
= subprocess
.check_output([
208 '-a', # Take the AND of the following selectors
209 '-p{}'.format(self
.process
.pid
), # Filter on PID
210 '-iTCP', # Filter only TCP sockets
212 except subprocess
.CalledProcessError
:
214 matches
= list(PORT_REGEX
.finditer(output
))
215 matches
= [m
for m
in matches
216 if m
.group('port') not in ('6666', '4444')]
220 "OpenOCD listening on multiple ports. Cannot uniquely "
221 "identify gdb server port.")
224 return int(match
.group('port'))
226 raise Exception("Timed out waiting for gdb server to obtain port.")
235 class OpenocdCli(object):
236 def __init__(self
, port
=4444):
237 self
.child
= pexpect
.spawn(
238 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
239 self
.child
.expect("> ")
241 def command(self
, cmd
):
242 self
.child
.sendline(cmd
)
243 self
.child
.expect(cmd
)
244 self
.child
.expect("\n")
245 self
.child
.expect("> ")
246 return self
.child
.before
.strip("\t\r\n \0")
248 def reg(self
, reg
=''):
249 output
= self
.command("reg %s" % reg
)
250 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
251 values
= {r
: int(v
, 0) for r
, v
in matches
}
256 def load_image(self
, image
):
257 output
= self
.command("load_image %s" % image
)
258 if 'invalid ELF file, only 32bits files are supported' in output
:
259 raise TestNotApplicable(output
)
261 class CannotAccess(Exception):
262 def __init__(self
, address
):
263 Exception.__init
__(self
)
264 self
.address
= address
268 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
269 self
.child
= pexpect
.spawn(cmd
)
270 self
.child
.logfile
= open("gdb.log", "w")
271 self
.child
.logfile
.write("+ %s\n" % cmd
)
273 self
.command("set confirm off")
274 self
.command("set width 0")
275 self
.command("set height 0")
277 self
.command("set print entry-values no")
280 """Wait for prompt."""
281 self
.child
.expect(r
"\(gdb\)")
283 def command(self
, command
, timeout
=-1):
284 self
.child
.sendline(command
)
285 self
.child
.expect("\n", timeout
=timeout
)
286 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
287 return self
.child
.before
.strip()
289 def c(self
, wait
=True, timeout
=-1):
291 output
= self
.command("c", timeout
=timeout
)
292 assert "Continuing" in output
295 self
.child
.sendline("c")
296 self
.child
.expect("Continuing")
299 self
.child
.send("\003")
300 self
.child
.expect(r
"\(gdb\)", timeout
=60)
301 return self
.child
.before
.strip()
303 def x(self
, address
, size
='w'):
304 output
= self
.command("x/%s %s" % (size
, address
))
305 value
= int(output
.split(':')[1].strip(), 0)
308 def p_raw(self
, obj
):
309 output
= self
.command("p %s" % obj
)
310 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
312 raise CannotAccess(int(m
.group(1), 0))
313 return output
.split('=')[-1].strip()
316 output
= self
.command("p/x %s" % obj
)
317 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
319 raise CannotAccess(int(m
.group(1), 0))
320 value
= int(output
.split('=')[-1].strip(), 0)
323 def p_string(self
, obj
):
324 output
= self
.command("p %s" % obj
)
325 value
= shlex
.split(output
.split('=')[-1].strip())[1]
329 output
= self
.command("stepi")
333 output
= self
.command("load", timeout
=60)
334 assert "failed" not in output
335 assert "Transfer rate" in output
337 def b(self
, location
):
338 output
= self
.command("b %s" % location
)
339 assert "not defined" not in output
340 assert "Breakpoint" in output
343 def hbreak(self
, location
):
344 output
= self
.command("hbreak %s" % location
)
345 assert "not defined" not in output
346 assert "Hardware assisted breakpoint" in output
349 def run_all_tests(module
, target
, parsed
):
350 good_results
= set(('pass', 'not_applicable'))
357 global gdb_cmd
# pylint: disable=global-statement
360 todo
= [("ExamineTarget", ExamineTarget
)]
361 for name
in dir(module
):
362 definition
= getattr(module
, name
)
363 if type(definition
) == type and hasattr(definition
, 'test') and \
364 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
365 todo
.append((name
, definition
))
367 for name
, definition
in todo
:
368 instance
= definition(target
)
369 result
= instance
.run()
370 results
.setdefault(result
, []).append(name
)
372 if result
not in good_results
and parsed
.fail_fast
:
375 header("ran %d tests in %.0fs" % (count
, time
.time() - start
), dash
=':')
378 for key
, value
in results
.iteritems():
379 print "%d tests returned %s" % (len(value
), key
)
380 if key
not in good_results
:
387 def add_test_run_options(parser
):
388 parser
.add_argument("--fail-fast", "-f", action
="store_true",
389 help="Exit as soon as any test fails.")
390 parser
.add_argument("test", nargs
='*',
391 help="Run only tests that are named here.")
392 parser
.add_argument("--gdb",
393 help="The command to use to start gdb.")
395 def header(title
, dash
='-'):
397 dashes
= dash
* (36 - len(title
))
398 before
= dashes
[:len(dashes
)/2]
399 after
= dashes
[len(dashes
)/2:]
400 print "%s[ %s ]%s" % (before
, title
, after
)
406 lines
= open(path
, "r").readlines()
407 if len(lines
) > 1000:
408 for l
in lines
[:500]:
411 for l
in lines
[-500:]:
417 class BaseTest(object):
420 def __init__(self
, target
):
423 self
.target_process
= None
428 def early_applicable(self
):
429 """Return a false value if the test has determined it cannot run
430 without ever needing to talk to the target or server."""
431 # pylint: disable=no-self-use
438 compile_args
= getattr(self
, 'compile_args', None)
440 if compile_args
not in BaseTest
.compiled
:
441 # pylint: disable=star-args
442 BaseTest
.compiled
[compile_args
] = \
443 self
.target
.compile(*compile_args
)
444 self
.binary
= BaseTest
.compiled
.get(compile_args
)
446 def classSetup(self
):
448 self
.target_process
= self
.target
.target()
449 self
.server
= self
.target
.server()
450 self
.logs
.append(self
.server
.logname
)
452 def classTeardown(self
):
454 del self
.target_process
458 If compile_args is set, compile a program and set self.binary.
462 Then call test() and return the result, displaying relevant information
463 if an exception is raised.
466 print "Running", type(self
).__name
__, "...",
469 if not self
.early_applicable():
470 print "not_applicable"
471 return "not_applicable"
473 self
.start
= time
.time()
479 result
= self
.test() # pylint: disable=no-member
480 except TestNotApplicable
:
481 result
= "not_applicable"
482 except Exception as e
: # pylint: disable=broad-except
483 if isinstance(e
, TestFailed
):
487 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
489 if isinstance(e
, TestFailed
):
493 traceback
.print_exc(file=sys
.stdout
)
494 for log
in self
.logs
:
504 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
508 class GdbTest(BaseTest
):
509 def __init__(self
, target
):
510 BaseTest
.__init
__(self
, target
)
513 def classSetup(self
):
514 BaseTest
.classSetup(self
)
515 self
.logs
.append("gdb.log")
518 self
.gdb
= Gdb(gdb_cmd
)
523 self
.gdb
.command("file %s" % self
.binary
)
525 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
526 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
529 "target extended-remote localhost:%d" % self
.server
.port
)
531 self
.gdb
.p("$priv=3")
533 def classTeardown(self
):
535 BaseTest
.classTeardown(self
)
537 class ExamineTarget(GdbTest
):
539 self
.target
.misa
= self
.gdb
.p("$misa")
542 if (self
.target
.misa
>> 30) == 1:
544 elif (self
.target
.misa
>> 62) == 2:
546 elif (self
.target
.misa
>> 126) == 3:
552 if self
.target
.misa
& (1<<i
):
553 txt
+= chr(i
+ ord('A'))
556 class TestFailed(Exception):
557 def __init__(self
, message
):
558 Exception.__init
__(self
)
559 self
.message
= message
561 class TestNotApplicable(Exception):
562 def __init__(self
, message
):
563 Exception.__init
__(self
)
564 self
.message
= message
566 def assertEqual(a
, b
):
568 raise TestFailed("%r != %r" % (a
, b
))
570 def assertNotEqual(a
, b
):
572 raise TestFailed("%r == %r" % (a
, b
))
576 raise TestFailed("%r not in %r" % (a
, b
))
578 def assertNotIn(a
, b
):
580 raise TestFailed("%r in %r" % (a
, b
))
582 def assertGreater(a
, b
):
584 raise TestFailed("%r not greater than %r" % (a
, b
))
586 def assertLess(a
, b
):
588 raise TestFailed("%r not less than %r" % (a
, b
))
592 raise TestFailed("%r is not True" % a
)
594 def assertRegexpMatches(text
, regexp
):
595 if not re
.search(regexp
, text
):
596 raise TestFailed("can't find %r in %r" % (regexp
, text
))