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
, 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(cmd
)
69 cmd
+= ["--isa", "RV32"]
72 cmd
= ["timeout", str(timeout
)] + cmd
77 cmd
+= ['--rbb-port', '0']
78 os
.environ
['REMOTE_BITBANG_HOST'] = 'localhost'
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
, simv
=None, debug
=False):
115 cmd
= shlex
.split(simv
)
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
, cmd
=None, config
=None, debug
=False):
152 cmd
= shlex
.split(cmd
)
154 cmd
= ["openocd", "-d"]
156 # This command needs to come before any config scripts on the command
157 # line, since they are executed in order.
159 # Tell OpenOCD to bind gdb to an unused, ephemeral port.
162 # Disable tcl and telnet servers, since they are unused and because
163 # the port numbers will conflict if multiple OpenOCD processes are
164 # running on the same server.
168 "telnet_port disabled",
172 f
= find_file(config
)
174 print("Unable to read file " + config
)
181 logfile
= open(Openocd
.logname
, "w")
182 logfile
.write("+ %s\n" % " ".join(cmd
))
184 self
.process
= subprocess
.Popen(cmd
, stdin
=subprocess
.PIPE
,
185 stdout
=logfile
, stderr
=logfile
)
187 # Wait for OpenOCD to have made it through riscv_examine(). When using
188 # OpenOCD to communicate with a simulator this may take a long time,
189 # and gdb will time out when trying to connect if we attempt too early.
193 log
= open(Openocd
.logname
).read()
194 if "OK GO NOW" in log
:
196 if not self
.process
.poll() is None:
198 "OpenOCD exited before completing riscv_examine()")
199 if not messaged
and time
.time() - start
> 1:
201 print "Waiting for OpenOCD to examine RISCV core..."
203 self
.port
= self
._get
_gdb
_server
_port
()
205 def _get_gdb_server_port(self
):
206 """Get port that OpenOCD's gdb server is listening on."""
208 PORT_REGEX
= re
.compile(r
'(?P<port>\d+) \(LISTEN\)')
209 for _
in range(MAX_ATTEMPTS
):
210 with
open(os
.devnull
, 'w') as devnull
:
212 output
= subprocess
.check_output([
214 '-a', # Take the AND of the following selectors
215 '-p{}'.format(self
.process
.pid
), # Filter on PID
216 '-iTCP', # Filter only TCP sockets
218 except subprocess
.CalledProcessError
:
220 matches
= list(PORT_REGEX
.finditer(output
))
221 matches
= [m
for m
in matches
222 if m
.group('port') not in ('6666', '4444')]
226 "OpenOCD listening on multiple ports. Cannot uniquely "
227 "identify gdb server port.")
230 return int(match
.group('port'))
232 raise Exception("Timed out waiting for gdb server to obtain port.")
241 class OpenocdCli(object):
242 def __init__(self
, port
=4444):
243 self
.child
= pexpect
.spawn(
244 "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port
)
245 self
.child
.expect("> ")
247 def command(self
, cmd
):
248 self
.child
.sendline(cmd
)
249 self
.child
.expect(cmd
)
250 self
.child
.expect("\n")
251 self
.child
.expect("> ")
252 return self
.child
.before
.strip("\t\r\n \0")
254 def reg(self
, reg
=''):
255 output
= self
.command("reg %s" % reg
)
256 matches
= re
.findall(r
"(\w+) \(/\d+\): (0x[0-9A-F]+)", output
)
257 values
= {r
: int(v
, 0) for r
, v
in matches
}
262 def load_image(self
, image
):
263 output
= self
.command("load_image %s" % image
)
264 if 'invalid ELF file, only 32bits files are supported' in output
:
265 raise TestNotApplicable(output
)
267 class CannotAccess(Exception):
268 def __init__(self
, address
):
269 Exception.__init
__(self
)
270 self
.address
= address
274 cmd
=os
.path
.expandvars("$RISCV/bin/riscv64-unknown-elf-gdb")):
275 self
.child
= pexpect
.spawn(cmd
)
276 self
.child
.logfile
= open("gdb.log", "w")
277 self
.child
.logfile
.write("+ %s\n" % cmd
)
279 self
.command("set confirm off")
280 self
.command("set width 0")
281 self
.command("set height 0")
283 self
.command("set print entry-values no")
286 """Wait for prompt."""
287 self
.child
.expect(r
"\(gdb\)")
289 def command(self
, command
, timeout
=6000):
290 self
.child
.sendline(command
)
291 self
.child
.expect("\n", timeout
=timeout
)
292 self
.child
.expect(r
"\(gdb\)", timeout
=timeout
)
293 return self
.child
.before
.strip()
295 def c(self
, wait
=True, timeout
=-1):
297 output
= self
.command("c", timeout
=timeout
)
298 assert "Continuing" in output
301 self
.child
.sendline("c")
302 self
.child
.expect("Continuing")
305 self
.child
.send("\003")
306 self
.child
.expect(r
"\(gdb\)", timeout
=6000)
307 return self
.child
.before
.strip()
309 def x(self
, address
, size
='w'):
310 output
= self
.command("x/%s %s" % (size
, address
))
311 value
= int(output
.split(':')[1].strip(), 0)
314 def p_raw(self
, obj
):
315 output
= self
.command("p %s" % obj
)
316 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
318 raise CannotAccess(int(m
.group(1), 0))
319 return output
.split('=')[-1].strip()
322 output
= self
.command("p/x %s" % obj
)
323 m
= re
.search("Cannot access memory at address (0x[0-9a-f]+)", output
)
325 raise CannotAccess(int(m
.group(1), 0))
326 value
= int(output
.split('=')[-1].strip(), 0)
329 def p_string(self
, obj
):
330 output
= self
.command("p %s" % obj
)
331 value
= shlex
.split(output
.split('=')[-1].strip())[1]
335 output
= self
.command("stepi")
339 output
= self
.command("load", timeout
=6000)
340 assert "failed" not in output
341 assert "Transfer rate" in output
343 def b(self
, location
):
344 output
= self
.command("b %s" % location
)
345 assert "not defined" not in output
346 assert "Breakpoint" in output
349 def hbreak(self
, location
):
350 output
= self
.command("hbreak %s" % location
)
351 assert "not defined" not in output
352 assert "Hardware assisted breakpoint" in output
355 def run_all_tests(module
, target
, parsed
):
356 good_results
= set(('pass', 'not_applicable'))
363 global gdb_cmd
# pylint: disable=global-statement
366 todo
= [("ExamineTarget", ExamineTarget
)]
367 for name
in dir(module
):
368 definition
= getattr(module
, name
)
369 if type(definition
) == type and hasattr(definition
, 'test') and \
370 (not parsed
.test
or any(test
in name
for test
in parsed
.test
)):
371 todo
.append((name
, definition
))
373 for name
, definition
in todo
:
374 instance
= definition(target
)
375 result
= instance
.run()
376 results
.setdefault(result
, []).append(name
)
378 if result
not in good_results
and parsed
.fail_fast
:
381 header("ran %d tests in %.0fs" % (count
, time
.time() - start
), dash
=':')
384 for key
, value
in results
.iteritems():
385 print "%d tests returned %s" % (len(value
), key
)
386 if key
not in good_results
:
393 def add_test_run_options(parser
):
394 parser
.add_argument("--fail-fast", "-f", action
="store_true",
395 help="Exit as soon as any test fails.")
396 parser
.add_argument("test", nargs
='*',
397 help="Run only tests that are named here.")
398 parser
.add_argument("--gdb",
399 help="The command to use to start gdb.")
401 def header(title
, dash
='-'):
403 dashes
= dash
* (36 - len(title
))
404 before
= dashes
[:len(dashes
)/2]
405 after
= dashes
[len(dashes
)/2:]
406 print "%s[ %s ]%s" % (before
, title
, after
)
412 lines
= open(path
, "r").readlines()
413 if len(lines
) > 1000:
414 for l
in lines
[:500]:
417 for l
in lines
[-500:]:
423 class BaseTest(object):
426 def __init__(self
, target
):
429 self
.target_process
= None
434 def early_applicable(self
):
435 """Return a false value if the test has determined it cannot run
436 without ever needing to talk to the target or server."""
437 # pylint: disable=no-self-use
444 compile_args
= getattr(self
, 'compile_args', None)
446 if compile_args
not in BaseTest
.compiled
:
447 # pylint: disable=star-args
448 BaseTest
.compiled
[compile_args
] = \
449 self
.target
.compile(*compile_args
)
450 self
.binary
= BaseTest
.compiled
.get(compile_args
)
452 def classSetup(self
):
454 self
.target_process
= self
.target
.target()
455 self
.server
= self
.target
.server()
456 self
.logs
.append(self
.server
.logname
)
458 def classTeardown(self
):
460 del self
.target_process
464 If compile_args is set, compile a program and set self.binary.
468 Then call test() and return the result, displaying relevant information
469 if an exception is raised.
472 print "Running", type(self
).__name
__, "...",
475 if not self
.early_applicable():
476 print "not_applicable"
477 return "not_applicable"
479 self
.start
= time
.time()
485 result
= self
.test() # pylint: disable=no-member
486 except TestNotApplicable
:
487 result
= "not_applicable"
488 except Exception as e
: # pylint: disable=broad-except
489 if isinstance(e
, TestFailed
):
493 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
495 if isinstance(e
, TestFailed
):
499 traceback
.print_exc(file=sys
.stdout
)
500 for log
in self
.logs
:
510 print "%s in %.2fs" % (result
, time
.time() - self
.start
)
514 class GdbTest(BaseTest
):
515 def __init__(self
, target
):
516 BaseTest
.__init
__(self
, target
)
519 def classSetup(self
):
520 BaseTest
.classSetup(self
)
521 self
.logs
.append("gdb.log")
524 self
.gdb
= Gdb(gdb_cmd
)
529 self
.gdb
.command("file %s" % self
.binary
)
531 self
.gdb
.command("set arch riscv:rv%d" % self
.target
.xlen
)
532 self
.gdb
.command("set remotetimeout %d" % self
.target
.timeout_sec
)
535 "target extended-remote localhost:%d" % self
.server
.port
)
537 self
.gdb
.p("$priv=3")
539 def classTeardown(self
):
541 BaseTest
.classTeardown(self
)
543 class ExamineTarget(GdbTest
):
545 self
.target
.misa
= self
.gdb
.p("$misa")
548 if (self
.target
.misa
>> 30) == 1:
550 elif (self
.target
.misa
>> 62) == 2:
552 elif (self
.target
.misa
>> 126) == 3:
558 if self
.target
.misa
& (1<<i
):
559 txt
+= chr(i
+ ord('A'))
562 class TestFailed(Exception):
563 def __init__(self
, message
):
564 Exception.__init
__(self
)
565 self
.message
= message
567 class TestNotApplicable(Exception):
568 def __init__(self
, message
):
569 Exception.__init
__(self
)
570 self
.message
= message
572 def assertEqual(a
, b
):
574 raise TestFailed("%r != %r" % (a
, b
))
576 def assertNotEqual(a
, b
):
578 raise TestFailed("%r == %r" % (a
, b
))
582 raise TestFailed("%r not in %r" % (a
, b
))
584 def assertNotIn(a
, b
):
586 raise TestFailed("%r in %r" % (a
, b
))
588 def assertGreater(a
, b
):
590 raise TestFailed("%r not greater than %r" % (a
, b
))
592 def assertLess(a
, b
):
594 raise TestFailed("%r not less than %r" % (a
, b
))
598 raise TestFailed("%r is not True" % a
)
600 def assertRegexpMatches(text
, regexp
):
601 if not re
.search(regexp
, text
):
602 raise TestFailed("can't find %r in %r" % (regexp
, text
))