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", "RV32"]
73 cmd
= ["timeout", str(timeout
)] + cmd
78 cmd
+= ['--rbb-port', '0']
79 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
80 cmd
.append('programs/infinite_loop')
83 logfile
= open(self
.logname
, "w")
84 logfile
.write("+ %s\n" % " ".join(cmd
))
86 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
87 stdout
=logfile
, stderr
=logfile
)
92 m
= re
.search(r
"Listening for remote bitbang connection on "
93 r
"port (\d+).", open(self
.logname
).read())
95 self
.port
= int(m
.group(1))
96 os
.environ
['REMOTE_BITBANG_PORT'] = m
.group(1)
99 assert self
.port
, "Didn't get spike message about bitbang " \
109 def wait(self
, *args
, **kwargs
):
110 return self
.process
.wait(*args
, **kwargs
)
112 class VcsSim(object):
113 def __init__(self
, sim_cmd
=None, debug
=False):
115 cmd
= shlex
.split(sim_cmd
)
118 cmd
+= ["+jtag_vpi_enable"]
120 cmd
[0] = cmd
[0] + "-debug"
121 cmd
+= ["+vcdplusfile=output/gdbserver.vpd"]
122 logfile
= open("simv.log", "w")
123 logfile
.write("+ %s\n" % " ".join(cmd
))
125 listenfile
= open("simv.log", "r")
126 listenfile
.seek(0, 2)
127 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
128 stdout
=logfile
, stderr
=logfile
)
131 line
= listenfile
.readline()
134 match
= re
.match(r
"^Listening on port (\d+)$", line
)
137 self
.port
= int(match
.group(1))
138 os
.environ
['JTAG_VPI_PORT'] = str(self
.port
)
147 class Openocd(object):
148 logname
= "openocd.log"
150 def __init__(self
, server_cmd
=None, config
=None, debug
=False):
152 cmd
= shlex
.split(server_cmd
)
154 openocd
= os
.path
.expandvars("$RISCV/bin/riscv-openocd")
159 # This command needs to come before any config scripts on the command
160 # line, since they are executed in order.
162 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
165 # Disable tcl and telnet servers, since they are unused and because
166 # the port numbers will conflict if multiple OpenOCD processes are
167 # running on the same server.
171 "telnet_port disabled",
175 f
= find_file(config
)
177 print("Unable to read file " + config
)
184 logfile
= open(Openocd
.logname
, "w")
185 logfile
.write("+ %s\n" % " ".join(cmd
))
187 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
188 stdout
=logfile
, stderr
=logfile
)
190 # Wait for OpenOCD to have made it through riscv_examine(). When using
191 # OpenOCD to communicate with a simulator this may take a long time,
192 # and gdb will time out when trying to connect if we attempt too early.
196 log
= open(Openocd
.logname
).read()
197 if "Ready for Remote Connections" in log
:
199 if not self
.process
.poll() is None:
201 "OpenOCD exited before completing riscv_examine()")
202 if not messaged
and time
.time() - start
> 1:
204 print "Waiting for OpenOCD to examine RISCV core..."
206 self
.port
= self
._get
_gdb
_server
_port
()
208 def _get_gdb_server_port(self
):
209 """Get port that OpenOCD's gdb server is listening on."""
211 PORT_REGEX
= re
.compile(r
'(?P<port>\d+) \(LISTEN\)')
212 for _
in range(MAX_ATTEMPTS
):
213 with
open(os
.devnull
, 'w') as devnull
:
215 output
= subprocess
.check_output([
217 '-a', # Take the AND of the following selectors
218 '-p{}'.format(self
.process
.pid
), # Filter on PID
219 '-iTCP', # Filter only TCP sockets
221 except subprocess
.CalledProcessError
:
223 matches
= list(PORT_REGEX
.finditer(output
))
224 matches
= [m
for m
in matches
225 if m
.group('port') not in ('6666', '4444')]
229 "OpenOCD listening on multiple ports. Cannot uniquely "
230 "identify gdb server port.")
233 return int(match
.group('port'))
235 raise Exception("Timed out waiting for gdb server to obtain port.")
244 class OpenocdCli(object):
245 def __init__(self
, port
=4444):
246 self
.child
= pexpect
.spawn(
247 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
248 self
.child
.expect("> ")
250 def command(self
, cmd
):
251 self
.child
.sendline(cmd
)
252 self
.child
.expect(cmd
)
253 self
.child
.expect("\n")
254 self
.child
.expect("> ")
255 return self
.child
.before
.strip("\t\r\n \0")
257 def reg(self
, reg
=''):
258 output
= self
.command("reg %s" % reg
)
259 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
260 values
= {r
: int(v
, 0) for r
, v
in matches
}
265 def load_image(self
, image
):
266 output
= self
.command("load_image %s" % image
)
267 if 'invalid ELF file, only 32bits files are supported' in output
:
268 raise TestNotApplicable(output
)
270 class CannotAccess(Exception):
271 def __init__(self
, address
):
272 Exception.__init
__(self
)
273 self
.address
= address
277 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
278 self
.child
= pexpect
.spawn(cmd
)
279 self
.child
.logfile
= open("gdb.log", "w")
280 self
.child
.logfile
.write("+ %s\n" % cmd
)
282 self
.command("set confirm off")
283 self
.command("set width 0")
284 self
.command("set height 0")
286 self
.command("set print entry-values no")
289 """Wait for prompt."""
290 self
.child
.expect(r
"\(gdb\)")
292 def command(self
, command
, timeout
=6000):
293 self
.child
.sendline(command
)
294 self
.child
.expect("\n", timeout
=timeout
)
295 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
296 return self
.child
.before
.strip()
298 def c(self
, wait
=True, timeout
=-1):
300 output
= self
.command("c", timeout
=timeout
)
301 assert "Continuing" in output
304 self
.child
.sendline("c")
305 self
.child
.expect("Continuing")
308 self
.child
.send("\003")
309 self
.child
.expect(r
"\(gdb\)", timeout
=6000)
310 return self
.child
.before
.strip()
312 def x(self
, address
, size
='w'):
313 output
= self
.command("x/%s %s" % (size
, address
))
314 value
= int(output
.split(':')[1].strip(), 0)
317 def p_raw(self
, obj
):
318 output
= self
.command("p %s" % obj
)
319 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
321 raise CannotAccess(int(m
.group(1), 0))
322 return output
.split('=')[-1].strip()
325 output
= self
.command("p/x %s" % obj
)
326 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
328 raise CannotAccess(int(m
.group(1), 0))
329 value
= int(output
.split('=')[-1].strip(), 0)
332 def p_string(self
, obj
):
333 output
= self
.command("p %s" % obj
)
334 value
= shlex
.split(output
.split('=')[-1].strip())[1]
338 output
= self
.command("stepi")
342 output
= self
.command("load", timeout
=6000)
343 assert "failed" not in output
344 assert "Transfer rate" in output
346 def b(self
, location
):
347 output
= self
.command("b %s" % location
)
348 assert "not defined" not in output
349 assert "Breakpoint" in output
352 def hbreak(self
, location
):
353 output
= self
.command("hbreak %s" % location
)
354 assert "not defined" not in output
355 assert "Hardware assisted breakpoint" in output
358 def run_all_tests(module
, target
, parsed
):
359 good_results
= set(('pass', 'not_applicable'))
366 global gdb_cmd
# pylint: disable=global-statement
369 todo
= [("ExamineTarget", ExamineTarget
)]
370 for name
in dir(module
):
371 definition
= getattr(module
, name
)
372 if type(definition
) == type and hasattr(definition
, 'test') and \
373 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
374 todo
.append((name
, definition
))
376 for name
, definition
in todo
:
377 instance
= definition(target
)
378 result
= instance
.run()
379 results
.setdefault(result
, []).append(name
)
381 if result
not in good_results
and parsed
.fail_fast
:
384 header("ran %d tests in %.0fs" % (count
, time
.time() - start
), dash
=':')
387 for key
, value
in results
.iteritems():
388 print "%d tests returned %s" % (len(value
), key
)
389 if key
not in good_results
:
396 def add_test_run_options(parser
):
397 parser
.add_argument("--fail-fast", "-f", action
="store_true",
398 help="Exit as soon as any test fails.")
399 parser
.add_argument("test", nargs
='*',
400 help="Run only tests that are named here.")
401 parser
.add_argument("--gdb",
402 help="The command to use to start gdb.")
404 def header(title
, dash
='-'):
406 dashes
= dash
* (36 - len(title
))
407 before
= dashes
[:len(dashes
)/2]
408 after
= dashes
[len(dashes
)/2:]
409 print "%s[ %s ]%s" % (before
, title
, after
)
415 lines
= open(path
, "r").readlines()
416 if len(lines
) > 1000:
417 for l
in lines
[:500]:
420 for l
in lines
[-500:]:
426 class BaseTest(object):
429 def __init__(self
, target
):
432 self
.target_process
= None
437 def early_applicable(self
):
438 """Return a false value if the test has determined it cannot run
439 without ever needing to talk to the target or server."""
440 # pylint: disable=no-self-use
447 compile_args
= getattr(self
, 'compile_args', None)
449 if compile_args
not in BaseTest
.compiled
:
450 # pylint: disable=star-args
451 BaseTest
.compiled
[compile_args
] = \
452 self
.target
.compile(*compile_args
)
453 self
.binary
= BaseTest
.compiled
.get(compile_args
)
455 def classSetup(self
):
457 self
.target_process
= self
.target
.target()
458 self
.server
= self
.target
.server()
459 self
.logs
.append(self
.server
.logname
)
461 def classTeardown(self
):
463 del self
.target_process
467 If compile_args is set, compile a program and set self.binary.
471 Then call test() and return the result, displaying relevant information
472 if an exception is raised.
475 print "Running", type(self
).__name
__, "...",
478 if not self
.early_applicable():
479 print "not_applicable"
480 return "not_applicable"
482 self
.start
= time
.time()
488 result
= self
.test() # pylint: disable=no-member
489 except TestNotApplicable
:
490 result
= "not_applicable"
491 except Exception as e
: # pylint: disable=broad-except
492 if isinstance(e
, TestFailed
):
496 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
498 if isinstance(e
, TestFailed
):
502 traceback
.print_exc(file=sys
.stdout
)
503 for log
in self
.logs
:
513 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
517 class GdbTest(BaseTest
):
518 def __init__(self
, target
):
519 BaseTest
.__init
__(self
, target
)
522 def classSetup(self
):
523 BaseTest
.classSetup(self
)
524 self
.logs
.append("gdb.log")
527 self
.gdb
= Gdb(gdb_cmd
)
532 self
.gdb
.command("file %s" % self
.binary
)
534 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
535 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
538 "target extended-remote localhost:%d" % self
.server
.port
)
540 self
.gdb
.p("$priv=3")
542 def classTeardown(self
):
544 BaseTest
.classTeardown(self
)
546 class ExamineTarget(GdbTest
):
548 self
.target
.misa
= self
.gdb
.p("$misa")
551 if (self
.target
.misa
>> 30) == 1:
553 elif (self
.target
.misa
>> 62) == 2:
555 elif (self
.target
.misa
>> 126) == 3:
561 if self
.target
.misa
& (1<<i
):
562 txt
+= chr(i
+ ord('A'))
565 class TestFailed(Exception):
566 def __init__(self
, message
):
567 Exception.__init
__(self
)
568 self
.message
= message
570 class TestNotApplicable(Exception):
571 def __init__(self
, message
):
572 Exception.__init
__(self
)
573 self
.message
= message
575 def assertEqual(a
, b
):
577 raise TestFailed("%r != %r" % (a
, b
))
579 def assertNotEqual(a
, b
):
581 raise TestFailed("%r == %r" % (a
, b
))
585 raise TestFailed("%r not in %r" % (a
, b
))
587 def assertNotIn(a
, b
):
589 raise TestFailed("%r in %r" % (a
, b
))
591 def assertGreater(a
, b
):
593 raise TestFailed("%r not greater than %r" % (a
, b
))
595 def assertLess(a
, b
):
597 raise TestFailed("%r not less than %r" % (a
, b
))
601 raise TestFailed("%r is not True" % a
)
603 def assertRegexpMatches(text
, regexp
):
604 if not re
.search(regexp
, text
):
605 raise TestFailed("can't find %r in %r" % (regexp
, text
))