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
)
39 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
,
40 stderr
=subprocess
.PIPE
)
41 stdout
, stderr
= process
.communicate()
42 if process
.returncode
:
44 header("Compile failed")
45 print "+", " ".join(cmd
)
49 raise Exception("Compile failed!")
52 # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
54 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
56 port
= s
.getsockname()[1]
61 logname
= "spike-%d.log" % os
.getpid()
63 def __init__(self
, target
, halted
=False, timeout
=None, with_jtag_gdb
=True):
64 """Launch spike. Return tuple of its process and the port it's running
67 cmd
= shlex
.split(target
.sim_cmd
)
69 spike
= os
.path
.expandvars("$RISCV/bin/spike")
72 cmd
+= ["--isa", "RV32G"]
74 cmd
+= ["--isa", "RV64G"]
75 cmd
+= ["-m0x%x:0x%x" % (target
.ram
, target
.ram_size
)]
78 cmd
= ["timeout", str(timeout
)] + cmd
83 cmd
+= ['--rbb-port', '0']
84 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
85 self
.infinite_loop
= target
.compile(
86 "programs/checksum.c", "programs/tiny-malloc.c",
87 "programs/infinite_loop.S", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
88 cmd
.append(self
.infinite_loop
)
89 logfile
= open(self
.logname
, "w")
90 logfile
.write("+ %s\n" % " ".join(cmd
))
92 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
93 stdout
=logfile
, stderr
=logfile
)
98 m
= re
.search(r
"Listening for remote bitbang connection on "
99 r
"port (\d+).", open(self
.logname
).read())
101 self
.port
= int(m
.group(1))
102 os
.environ
['REMOTE_BITBANG_PORT'] = m
.group(1)
105 assert self
.port
, "Didn't get spike message about bitbang " \
115 def wait(self
, *args
, **kwargs
):
116 return self
.process
.wait(*args
, **kwargs
)
118 class VcsSim(object):
121 def __init__(self
, sim_cmd
=None, debug
=False):
123 cmd
= shlex
.split(sim_cmd
)
126 cmd
+= ["+jtag_vpi_enable"]
128 cmd
[0] = cmd
[0] + "-debug"
129 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
130 logfile
= open(self
.logname
, "w")
131 logfile
.write("+ %s\n" % " ".join(cmd
))
133 listenfile
= open(self
.logname
, "r")
134 listenfile
.seek(0, 2)
135 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
136 stdout
=logfile
, stderr
=logfile
)
139 # Fail if VCS exits early
140 exit_code
= self
.process
.poll()
141 if exit_code
is not None:
142 raise RuntimeError('VCS simulator exited early with status %d'
145 line
= listenfile
.readline()
148 match
= re
.match(r
"^Listening on port (\d+)$", line
)
151 self
.port
= int(match
.group(1))
152 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
161 class Openocd(object):
162 logfile
= tempfile
.NamedTemporaryFile(prefix
='openocd', suffix
='.log')
163 logname
= logfile
.name
165 def __init__(self
, server_cmd
=None, config
=None, debug
=False):
167 cmd
= shlex
.split(server_cmd
)
169 openocd
= os
.path
.expandvars("$RISCV/bin/openocd")
174 # This command needs to come before any config scripts on the command
175 # line, since they are executed in order.
177 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
180 # Disable tcl and telnet servers, since they are unused and because
181 # the port numbers will conflict if multiple OpenOCD processes are
182 # running on the same server.
186 "telnet_port disabled",
190 f
= find_file(config
)
192 print "Unable to read file " + config
199 logfile
= open(Openocd
.logname
, "w")
200 logfile
.write("+ %s\n" % " ".join(cmd
))
202 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
203 stdout
=logfile
, stderr
=logfile
)
205 # Wait for OpenOCD to have made it through riscv_examine(). When using
206 # OpenOCD to communicate with a simulator this may take a long time,
207 # and gdb will time out when trying to connect if we attempt too early.
211 log
= open(Openocd
.logname
).read()
212 m
= re
.search(r
"Listening on port (\d+) for gdb connections", log
)
214 self
.port
= int(m
.group(1))
217 if not self
.process
.poll() is None:
218 header("OpenOCD log")
219 sys
.stdout
.write(log
)
221 "OpenOCD exited before completing riscv_examine()")
222 if not messaged
and time
.time() - start
> 1:
224 print "Waiting for OpenOCD to start..."
225 if time
.time() - start
> 60:
226 raise Exception("ERROR: Timed out waiting for OpenOCD to "
233 except (OSError, AttributeError):
236 class OpenocdCli(object):
237 def __init__(self
, port
=4444):
238 self
.child
= pexpect
.spawn(
239 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
240 self
.child
.expect("> ")
242 def command(self
, cmd
):
243 self
.child
.sendline(cmd
)
244 self
.child
.expect(cmd
)
245 self
.child
.expect("\n")
246 self
.child
.expect("> ")
247 return self
.child
.before
.strip("\t\r\n \0")
249 def reg(self
, reg
=''):
250 output
= self
.command("reg %s" % reg
)
251 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
252 values
= {r
: int(v
, 0) for r
, v
in matches
}
257 def load_image(self
, image
):
258 output
= self
.command("load_image %s" % image
)
259 if 'invalid ELF file, only 32bits files are supported' in output
:
260 raise TestNotApplicable(output
)
262 class CannotAccess(Exception):
263 def __init__(self
, address
):
264 Exception.__init
__(self
)
265 self
.address
= address
267 Thread
= collections
.namedtuple('Thread', ('id', 'target_id', 'name',
271 logfile
= tempfile
.NamedTemporaryFile(prefix
="gdb", suffix
=".log")
272 logname
= logfile
.name
275 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
276 self
.child
= pexpect
.spawn(cmd
)
277 self
.child
.logfile
= open(self
.logname
, "w")
278 self
.child
.logfile
.write("+ %s\n" % cmd
)
280 self
.command("set confirm off")
281 self
.command("set width 0")
282 self
.command("set height 0")
284 self
.command("set print entry-values no")
287 """Wait for prompt."""
288 self
.child
.expect(r
"\(gdb\)")
290 def command(self
, command
, timeout
=6000):
291 self
.child
.sendline(command
)
292 self
.child
.expect("\n", timeout
=timeout
)
293 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
294 return self
.child
.before
.strip()
296 def c(self
, wait
=True, timeout
=-1, async=False):
302 output
= self
.command("c%s" % async, timeout
=timeout
)
303 assert "Continuing" in output
306 self
.child
.sendline("c%s" % async)
307 self
.child
.expect("Continuing")
310 self
.child
.send("\003")
311 self
.child
.expect(r
"\(gdb\)", timeout
=6000)
312 return self
.child
.before
.strip()
314 def x(self
, address
, size
='w'):
315 output
= self
.command("x/%s %s" % (size
, address
))
316 value
= int(output
.split(':')[1].strip(), 0)
319 def p_raw(self
, obj
):
320 output
= self
.command("p %s" % obj
)
321 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
323 raise CannotAccess(int(m
.group(1), 0))
324 return output
.split('=')[-1].strip()
327 output
= self
.command("p/x %s" % obj
)
328 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
330 raise CannotAccess(int(m
.group(1), 0))
331 value
= int(output
.split('=')[-1].strip(), 0)
334 def p_string(self
, obj
):
335 output
= self
.command("p %s" % obj
)
336 value
= shlex
.split(output
.split('=')[-1].strip())[1]
340 output
= self
.command("stepi", timeout
=60)
344 output
= self
.command("load", timeout
=6000)
345 assert "failed" not in output
346 assert "Transfer rate" in output
348 def b(self
, location
):
349 output
= self
.command("b %s" % location
)
350 assert "not defined" not in output
351 assert "Breakpoint" in output
354 def hbreak(self
, location
):
355 output
= self
.command("hbreak %s" % location
)
356 assert "not defined" not in output
357 assert "Hardware assisted breakpoint" in output
361 output
= self
.command("info threads")
363 for line
in output
.splitlines():
365 r
"[\s\*]*(\d+)\s*Thread (\d+)\s*\(Name: ([^\)]+)\s*(.*)",
368 threads
.append(Thread(*m
.groups()))
370 threads
.append(Thread('1', '1', 'Default', '???'))
373 def thread(self
, thread
):
374 return self
.command("thread %s" % thread
.id)
376 def run_all_tests(module
, target
, parsed
):
377 if not os
.path
.exists(parsed
.logs
):
378 os
.makedirs(parsed
.logs
)
380 overall_start
= time
.time()
382 global gdb_cmd
# pylint: disable=global-statement
387 target
.misa
= int(parsed
.misaval
, 16)
388 print "Using $misa from command line: 0x%x" % target
.misa
390 print "Using $misa from target definition: 0x%x" % target
.misa
392 todo
.append(("ExamineTarget", ExamineTarget
))
394 for name
in dir(module
):
395 definition
= getattr(module
, name
)
396 if type(definition
) == type and hasattr(definition
, 'test') and \
397 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
398 todo
.append((name
, definition
))
400 results
, count
= run_tests(parsed
, target
, todo
)
402 header("ran %d tests in %.0fs" % (count
, time
.time() - overall_start
),
405 return print_results(results
)
407 good_results
= set(('pass', 'not_applicable'))
408 def run_tests(parsed
, target
, todo
):
412 for name
, definition
in todo
:
413 instance
= definition(target
)
414 log_name
= os
.path
.join(parsed
.logs
, "%s-%s-%s.log" %
415 (time
.strftime("%Y%m%d-%H%M%S"), type(target
).__name
__, name
))
416 log_fd
= open(log_name
, 'w')
417 print "Running", name
, "...",
419 log_fd
.write("Test: %s\n" % name
)
420 log_fd
.write("Target: %s\n" % type(target
).__name
__)
422 real_stdout
= sys
.stdout
425 result
= instance
.run()
426 log_fd
.write("Result: %s\n" % result
)
428 sys
.stdout
= real_stdout
429 log_fd
.write("Time elapsed: %.2fs\n" % (time
.time() - start
))
430 print "%s in %.2fs" % (result
, time
.time() - start
)
431 if result
not in good_results
and parsed
.print_failures
:
432 sys
.stdout
.write(file(log_name
).read())
434 results
.setdefault(result
, []).append(name
)
436 if result
not in good_results
and parsed
.fail_fast
:
439 return results
, count
441 def print_results(results
):
443 for key
, value
in results
.iteritems():
444 print "%d tests returned %s" % (len(value
), key
)
445 if key
not in good_results
:
452 def add_test_run_options(parser
):
453 parser
.add_argument("--logs", default
="logs",
454 help="Store logs in the specified directory.")
455 parser
.add_argument("--fail-fast", "-f", action
="store_true",
456 help="Exit as soon as any test fails.")
457 parser
.add_argument("--print-failures", action
="store_true",
458 help="When a test fails, print the log file to stdout.")
459 parser
.add_argument("test", nargs
='*',
460 help="Run only tests that are named here.")
461 parser
.add_argument("--gdb",
462 help="The command to use to start gdb.")
463 parser
.add_argument("--misaval",
464 help="Don't run ExamineTarget, just assume the misa value which is "
467 def header(title
, dash
='-', length
=78):
469 dashes
= dash
* (length
- 4 - len(title
))
470 before
= dashes
[:len(dashes
)/2]
471 after
= dashes
[len(dashes
)/2:]
472 print "%s[ %s ]%s" % (before
, title
, after
)
478 lines
= open(path
, "r").readlines()
483 class BaseTest(object):
486 def __init__(self
, target
):
489 self
.target_process
= None
494 def early_applicable(self
):
495 """Return a false value if the test has determined it cannot run
496 without ever needing to talk to the target or server."""
497 # pylint: disable=no-self-use
504 compile_args
= getattr(self
, 'compile_args', None)
506 if compile_args
not in BaseTest
.compiled
:
507 # pylint: disable=star-args
508 BaseTest
.compiled
[compile_args
] = \
509 self
.target
.compile(*compile_args
)
510 self
.binary
= BaseTest
.compiled
.get(compile_args
)
512 def classSetup(self
):
514 self
.target_process
= self
.target
.create()
515 if self
.target_process
:
516 self
.logs
.append(self
.target_process
.logname
)
518 self
.server
= self
.target
.server()
519 self
.logs
.append(self
.server
.logname
)
521 for log
in self
.logs
:
525 def classTeardown(self
):
527 del self
.target_process
531 If compile_args is set, compile a program and set self.binary.
535 Then call test() and return the result, displaying relevant information
536 if an exception is raised.
541 if not self
.early_applicable():
542 return "not_applicable"
544 self
.start
= time
.time()
549 result
= self
.test() # pylint: disable=no-member
550 except TestNotApplicable
:
551 result
= "not_applicable"
552 except Exception as e
: # pylint: disable=broad-except
553 if isinstance(e
, TestFailed
):
557 if isinstance(e
, TestFailed
):
561 traceback
.print_exc(file=sys
.stdout
)
565 for log
in self
.logs
:
567 header("End of logs")
575 class GdbTest(BaseTest
):
576 def __init__(self
, target
):
577 BaseTest
.__init
__(self
, target
)
580 def classSetup(self
):
581 BaseTest
.classSetup(self
)
584 self
.gdb
= Gdb(gdb_cmd
)
588 self
.logs
.append(self
.gdb
.logname
)
591 self
.gdb
.command("file %s" % self
.binary
)
593 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
594 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
597 "target extended-remote localhost:%d" % self
.server
.port
)
598 # Select a random thread.
599 # TODO: Allow a command line option to force a specific thread.
600 thread
= random
.choice(self
.gdb
.threads())
601 self
.gdb
.thread(thread
)
603 for cmd
in self
.target
.gdb_setup
:
604 self
.gdb
.command(cmd
)
606 # FIXME: OpenOCD doesn't handle PRIV now
607 #self.gdb.p("$priv=3")
609 def classTeardown(self
):
611 BaseTest
.classTeardown(self
)
613 class ExamineTarget(GdbTest
):
615 self
.target
.misa
= self
.gdb
.p("$misa")
618 if (self
.target
.misa
>> 30) == 1:
620 elif (self
.target
.misa
>> 62) == 2:
622 elif (self
.target
.misa
>> 126) == 3:
625 raise TestFailed("Couldn't determine XLEN from $misa (0x%x)" %
629 if self
.target
.misa
& (1<<i
):
630 txt
+= chr(i
+ ord('A'))
633 class TestFailed(Exception):
634 def __init__(self
, message
):
635 Exception.__init
__(self
)
636 self
.message
= message
638 class TestNotApplicable(Exception):
639 def __init__(self
, message
):
640 Exception.__init
__(self
)
641 self
.message
= message
643 def assertEqual(a
, b
):
645 raise TestFailed("%r != %r" % (a
, b
))
647 def assertNotEqual(a
, b
):
649 raise TestFailed("%r == %r" % (a
, b
))
653 raise TestFailed("%r not in %r" % (a
, b
))
655 def assertNotIn(a
, b
):
657 raise TestFailed("%r in %r" % (a
, b
))
659 def assertGreater(a
, b
):
661 raise TestFailed("%r not greater than %r" % (a
, b
))
663 def assertLess(a
, b
):
665 raise TestFailed("%r not less than %r" % (a
, b
))
669 raise TestFailed("%r is not True" % a
)
671 def assertRegexpMatches(text
, regexp
):
672 if not re
.search(regexp
, text
):
673 raise TestFailed("can't find %r in %r" % (regexp
, text
))