14 # Note that gdb comes with its own testsuite. I was unable to figure out how to
15 # run that testsuite against the spike simulator.
18 for directory
in (os
.getcwd(), os
.path
.dirname(__file__
)):
19 fullpath
= os
.path
.join(directory
, path
)
20 if os
.path
.exists(fullpath
):
24 def compile(args
, xlen
=32): # pylint: disable=redefined-builtin
25 cc
= os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gcc")
28 cmd
.append("-march=rv32imac")
29 cmd
.append("-mabi=ilp32")
31 cmd
.append("-march=rv64imac")
32 cmd
.append("-mabi=lp64")
34 found
= find_file(arg
)
40 print "+", " ".join(cmd
)
41 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
,
42 stderr
=subprocess
.PIPE
)
43 stdout
, stderr
= process
.communicate()
44 if process
.returncode
:
48 raise Exception("Compile failed!")
51 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
53 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
55 port
= s
.getsockname()[1]
60 logname
= "spike-%d.log" % os
.getpid()
62 def __init__(self
, target
, halted
=False, timeout
=None, with_jtag_gdb
=True):
63 """Launch spike. Return tuple of its process and the port it's running
73 cmd
= shlex
.split(target
.sim_cmd
)
75 spike
= os
.path
.expandvars("$RISCV/bin/spike")
78 cmd
+= ["-p%d" % len(harts
)]
80 assert len(set(t
.xlen
for t
in harts
)) == 1, \
81 "All spike harts must have the same XLEN"
83 if harts
[0].xlen
== 32:
84 cmd
+= ["--isa", "RV32G"]
86 cmd
+= ["--isa", "RV64G"]
88 assert len(set(t
.ram
for t
in harts
)) == 1, \
89 "All spike harts must have the same RAM layout"
90 assert len(set(t
.ram_size
for t
in harts
)) == 1, \
91 "All spike harts must have the same RAM layout"
92 cmd
+= ["-m0x%x:0x%x" % (harts
[0].ram
, harts
[0].ram_size
)]
95 cmd
= ["timeout", str(timeout
)] + cmd
100 cmd
+= ['--rbb-port', '0']
101 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
102 self
.infinite_loop
= harts
[0].compile(
103 "programs/checksum.c", "programs/tiny-malloc.c",
104 "programs/infinite_loop.S", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
105 cmd
.append(self
.infinite_loop
)
106 logfile
= open(self
.logname
, "w")
107 logfile
.write("+ %s\n" % " ".join(cmd
))
109 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
110 stdout
=logfile
, stderr
=logfile
)
115 m
= re
.search(r
"Listening for remote bitbang connection on "
116 r
"port (\d+).", open(self
.logname
).read())
118 self
.port
= int(m
.group(1))
119 os
.environ
['REMOTE_BITBANG_PORT'] = m
.group(1)
122 assert self
.port
, "Didn't get spike message about bitbang " \
133 def wait(self
, *args
, **kwargs
):
134 return self
.process
.wait(*args
, **kwargs
)
136 class VcsSim(object):
139 def __init__(self
, sim_cmd
=None, debug
=False):
141 cmd
= shlex
.split(sim_cmd
)
144 cmd
+= ["+jtag_vpi_enable"]
146 cmd
[0] = cmd
[0] + "-debug"
147 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
148 logfile
= open(self
.logname
, "w")
149 logfile
.write("+ %s\n" % " ".join(cmd
))
151 listenfile
= open(self
.logname
, "r")
152 listenfile
.seek(0, 2)
153 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
154 stdout
=logfile
, stderr
=logfile
)
157 # Fail if VCS exits early
158 exit_code
= self
.process
.poll()
159 if exit_code
is not None:
160 raise RuntimeError('VCS simulator exited early with status %d'
163 line
= listenfile
.readline()
166 match
= re
.match(r
"^Listening on port (\d+)$", line
)
169 self
.port
= int(match
.group(1))
170 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
179 class Openocd(object):
180 logfile
= tempfile
.NamedTemporaryFile(prefix
='openocd', suffix
='.log')
181 logname
= logfile
.name
182 print "OpenOCD Temporary Log File: %s" % logname
184 def __init__(self
, server_cmd
=None, config
=None, debug
=False, timeout
=60):
186 cmd
= shlex
.split(server_cmd
)
188 openocd
= os
.path
.expandvars("$RISCV/bin/openocd")
193 # This command needs to come before any config scripts on the command
194 # line, since they are executed in order.
196 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
199 # Disable tcl and telnet servers, since they are unused and because
200 # the port numbers will conflict if multiple OpenOCD processes are
201 # running on the same server.
205 "telnet_port disabled",
209 f
= find_file(config
)
211 print "Unable to read file " + config
218 logfile
= open(Openocd
.logname
, "w")
219 logfile
.write("+ %s\n" % " ".join(cmd
))
221 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
222 stdout
=logfile
, stderr
=logfile
)
225 # Wait for OpenOCD to have made it through riscv_examine(). When
226 # using OpenOCD to communicate with a simulator this may take a
227 # long time, and gdb will time out when trying to connect if we
232 log
= open(Openocd
.logname
).read()
233 m
= re
.search(r
"Listening on port (\d+) for gdb connections",
236 self
.port
= int(m
.group(1))
239 if not self
.process
.poll() is None:
241 "OpenOCD exited before completing riscv_examine()")
242 if not messaged
and time
.time() - start
> 1:
244 print "Waiting for OpenOCD to start..."
245 if (time
.time() - start
) > timeout
:
246 raise Exception("ERROR: Timed out waiting for OpenOCD to "
250 header("OpenOCD log")
251 sys
.stdout
.write(log
)
258 except (OSError, AttributeError):
261 class OpenocdCli(object):
262 def __init__(self
, port
=4444):
263 self
.child
= pexpect
.spawn(
264 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
265 self
.child
.expect("> ")
267 def command(self
, cmd
):
268 self
.child
.sendline(cmd
)
269 self
.child
.expect(cmd
)
270 self
.child
.expect("\n")
271 self
.child
.expect("> ")
272 return self
.child
.before
.strip("\t\r\n \0")
274 def reg(self
, reg
=''):
275 output
= self
.command("reg %s" % reg
)
276 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
277 values
= {r
: int(v
, 0) for r
, v
in matches
}
282 def load_image(self
, image
):
283 output
= self
.command("load_image %s" % image
)
284 if 'invalid ELF file, only 32bits files are supported' in output
:
285 raise TestNotApplicable(output
)
287 class CannotAccess(Exception):
288 def __init__(self
, address
):
289 Exception.__init
__(self
)
290 self
.address
= address
292 Thread
= collections
.namedtuple('Thread', ('id', 'target_id', 'name',
296 logfile
= tempfile
.NamedTemporaryFile(prefix
="gdb", suffix
=".log")
297 logname
= logfile
.name
298 print "GDB Temporary Log File: %s" % logname
301 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
302 self
.child
= pexpect
.spawn(cmd
)
303 self
.child
.logfile
= open(self
.logname
, "w")
304 self
.child
.logfile
.write("+ %s\n" % cmd
)
306 self
.command("set confirm off")
307 self
.command("set width 0")
308 self
.command("set height 0")
310 self
.command("set print entry-values no")
312 def select_hart(self
, hart
):
313 output
= self
.command("thread %d" % (hart
.index
+ 1))
314 assert "Unknown" not in output
317 """Wait for prompt."""
318 self
.child
.expect(r
"\(gdb\)")
320 def command(self
, command
, timeout
=6000):
321 self
.child
.sendline(command
)
322 self
.child
.expect("\n", timeout
=timeout
)
323 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
324 return self
.child
.before
.strip()
326 def c(self
, wait
=True, timeout
=-1, async=False):
332 output
= self
.command("c%s" % async, timeout
=timeout
)
333 assert "Continuing" in output
336 self
.child
.sendline("c%s" % async)
337 self
.child
.expect("Continuing")
340 self
.child
.send("\003")
341 self
.child
.expect(r
"\(gdb\)", timeout
=6000)
342 return self
.child
.before
.strip()
344 def x(self
, address
, size
='w'):
345 output
= self
.command("x/%s %s" % (size
, address
))
346 value
= int(output
.split(':')[1].strip(), 0)
349 def p_raw(self
, obj
):
350 output
= self
.command("p %s" % obj
)
351 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
353 raise CannotAccess(int(m
.group(1), 0))
354 return output
.split('=')[-1].strip()
357 output
= self
.command("p/x %s" % obj
)
358 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
360 raise CannotAccess(int(m
.group(1), 0))
361 value
= int(output
.split('=')[-1].strip(), 0)
364 def p_string(self
, obj
):
365 output
= self
.command("p %s" % obj
)
366 value
= shlex
.split(output
.split('=')[-1].strip())[1]
370 output
= self
.command("stepi", timeout
=60)
374 output
= self
.command("load", timeout
=6000)
375 assert "failed" not in output
376 assert "Transfer rate" in output
378 def b(self
, location
):
379 output
= self
.command("b %s" % location
)
380 assert "not defined" not in output
381 assert "Breakpoint" in output
384 def hbreak(self
, location
):
385 output
= self
.command("hbreak %s" % location
)
386 assert "not defined" not in output
387 assert "Hardware assisted breakpoint" in output
391 output
= self
.command("info threads")
393 for line
in output
.splitlines():
395 r
"[\s\*]*(\d+)\s*Thread (\d+)\s*\(Name: ([^\)]+)\s*(.*)",
398 threads
.append(Thread(*m
.groups()))
400 threads
.append(Thread('1', '1', 'Default', '???'))
403 def thread(self
, thread
):
404 return self
.command("thread %s" % thread
.id)
406 def run_all_tests(module
, target
, parsed
):
407 if not os
.path
.exists(parsed
.logs
):
408 os
.makedirs(parsed
.logs
)
410 overall_start
= time
.time()
412 global gdb_cmd
# pylint: disable=global-statement
416 for hart
in target
.harts
:
418 hart
.misa
= int(parsed
.misaval
, 16)
419 print "Using $misa from command line: 0x%x" % hart
.misa
421 print "Using $misa from hart definition: 0x%x" % hart
.misa
423 todo
.append(("ExamineTarget", ExamineTarget
, hart
))
425 for name
in dir(module
):
426 definition
= getattr(module
, name
)
427 if type(definition
) == type and hasattr(definition
, 'test') and \
428 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
429 todo
.append((name
, definition
, None))
431 results
, count
= run_tests(parsed
, target
, todo
)
433 header("ran %d tests in %.0fs" % (count
, time
.time() - overall_start
),
436 return print_results(results
)
438 good_results
= set(('pass', 'not_applicable'))
439 def run_tests(parsed
, target
, todo
):
443 for name
, definition
, hart
in todo
:
444 log_name
= os
.path
.join(parsed
.logs
, "%s-%s-%s.log" %
445 (time
.strftime("%Y%m%d-%H%M%S"), type(target
).__name
__, name
))
446 log_fd
= open(log_name
, 'w')
447 print "Running %s > %s ..." % (name
, log_name
),
448 instance
= definition(target
, hart
)
450 log_fd
.write("Test: %s\n" % name
)
451 log_fd
.write("Target: %s\n" % type(target
).__name
__)
453 real_stdout
= sys
.stdout
456 result
= instance
.run()
457 log_fd
.write("Result: %s\n" % result
)
459 sys
.stdout
= real_stdout
460 log_fd
.write("Time elapsed: %.2fs\n" % (time
.time() - start
))
461 print "%s in %.2fs" % (result
, time
.time() - start
)
462 if result
not in good_results
and parsed
.print_failures
:
463 sys
.stdout
.write(open(log_name
).read())
465 results
.setdefault(result
, []).append((name
, log_name
))
467 if result
not in good_results
and parsed
.fail_fast
:
470 return results
, count
472 def print_results(results
):
474 for key
, value
in results
.iteritems():
475 print "%d tests returned %s" % (len(value
), key
)
476 if key
not in good_results
:
478 for name
, log_name
in value
:
479 print " %s > %s" % (name
, log_name
)
483 def add_test_run_options(parser
):
484 parser
.add_argument("--logs", default
="logs",
485 help="Store logs in the specified directory.")
486 parser
.add_argument("--fail-fast", "-f", action
="store_true",
487 help="Exit as soon as any test fails.")
488 parser
.add_argument("--print-failures", action
="store_true",
489 help="When a test fails, print the log file to stdout.")
490 parser
.add_argument("test", nargs
='*',
491 help="Run only tests that are named here.")
492 parser
.add_argument("--gdb",
493 help="The command to use to start gdb.")
494 parser
.add_argument("--misaval",
495 help="Don't run ExamineTarget, just assume the misa value which is "
498 def header(title
, dash
='-', length
=78):
500 dashes
= dash
* (length
- 4 - len(title
))
501 before
= dashes
[:len(dashes
)/2]
502 after
= dashes
[len(dashes
)/2:]
503 print "%s[ %s ]%s" % (before
, title
, after
)
509 lines
= open(path
, "r").readlines()
514 class BaseTest(object):
517 def __init__(self
, target
, hart
=None):
522 self
.hart
= random
.choice(target
.harts
)
524 self
.target_process
= None
529 def early_applicable(self
):
530 """Return a false value if the test has determined it cannot run
531 without ever needing to talk to the target or server."""
532 # pylint: disable=no-self-use
539 compile_args
= getattr(self
, 'compile_args', None)
541 if compile_args
not in BaseTest
.compiled
:
542 # pylint: disable=star-args
543 BaseTest
.compiled
[compile_args
] = \
544 self
.hart
.compile(*compile_args
)
545 self
.binary
= BaseTest
.compiled
.get(compile_args
)
547 def classSetup(self
):
549 self
.target_process
= self
.target
.create()
550 if self
.target_process
:
551 self
.logs
.append(self
.target_process
.logname
)
553 self
.server
= self
.target
.server()
554 self
.logs
.append(self
.server
.logname
)
556 for log
in self
.logs
:
560 def classTeardown(self
):
562 del self
.target_process
566 If compile_args is set, compile a program and set self.binary.
570 Then call test() and return the result, displaying relevant information
571 if an exception is raised.
576 if not self
.early_applicable():
577 return "not_applicable"
579 self
.start
= time
.time()
584 result
= self
.test() # pylint: disable=no-member
585 except TestNotApplicable
:
586 result
= "not_applicable"
587 except Exception as e
: # pylint: disable=broad-except
588 if isinstance(e
, TestFailed
):
592 if isinstance(e
, TestFailed
):
596 traceback
.print_exc(file=sys
.stdout
)
600 for log
in self
.logs
:
602 header("End of logs")
610 class GdbTest(BaseTest
):
611 def __init__(self
, target
, hart
=None):
612 BaseTest
.__init
__(self
, target
, hart
=hart
)
615 def classSetup(self
):
616 BaseTest
.classSetup(self
)
619 self
.gdb
= Gdb(gdb_cmd
)
623 self
.logs
.append(self
.gdb
.logname
)
626 self
.gdb
.command("file %s" % self
.binary
)
628 self
.gdb
.command("set arch riscv:rv%d" % self
.hart
.xlen
)
629 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
632 "target extended-remote localhost:%d" % self
.server
.port
)
633 self
.gdb
.select_hart(self
.hart
)
635 for cmd
in self
.target
.gdb_setup
:
636 self
.gdb
.command(cmd
)
638 # FIXME: OpenOCD doesn't handle PRIV now
639 #self.gdb.p("$priv=3")
641 def classTeardown(self
):
643 BaseTest
.classTeardown(self
)
645 class GdbSingleHartTest(GdbTest
):
646 def classSetup(self
):
647 GdbTest
.classSetup(self
)
649 for hart
in self
.target
.harts
:
650 # Park all harts that we're not using in a safe place.
651 if hart
!= self
.hart
:
652 self
.gdb
.select_hart(hart
)
653 self
.gdb
.p("$pc=loop_forever")
654 self
.gdb
.select_hart(self
.hart
)
656 class ExamineTarget(GdbTest
):
658 self
.target
.misa
= self
.gdb
.p("$misa")
661 if (self
.target
.misa
>> 30) == 1:
663 elif (self
.target
.misa
>> 62) == 2:
665 elif (self
.target
.misa
>> 126) == 3:
668 raise TestFailed("Couldn't determine XLEN from $misa (0x%x)" %
672 if self
.target
.misa
& (1<<i
):
673 txt
+= chr(i
+ ord('A'))
676 class TestFailed(Exception):
677 def __init__(self
, message
):
678 Exception.__init
__(self
)
679 self
.message
= message
681 class TestNotApplicable(Exception):
682 def __init__(self
, message
):
683 Exception.__init
__(self
)
684 self
.message
= message
686 def assertEqual(a
, b
):
688 raise TestFailed("%r != %r" % (a
, b
))
690 def assertNotEqual(a
, b
):
692 raise TestFailed("%r == %r" % (a
, b
))
696 raise TestFailed("%r not in %r" % (a
, b
))
698 def assertNotIn(a
, b
):
700 raise TestFailed("%r in %r" % (a
, b
))
702 def assertGreater(a
, b
):
704 raise TestFailed("%r not greater than %r" % (a
, b
))
706 def assertLess(a
, b
):
708 raise TestFailed("%r not less than %r" % (a
, b
))
712 raise TestFailed("%r is not True" % a
)
714 def assertRegexpMatches(text
, regexp
):
715 if not re
.search(regexp
, text
):
716 raise TestFailed("can't find %r in %r" % (regexp
, text
))