14 MSTATUS_UIE
= 0x00000001
15 MSTATUS_SIE
= 0x00000002
16 MSTATUS_HIE
= 0x00000004
17 MSTATUS_MIE
= 0x00000008
18 MSTATUS_UPIE
= 0x00000010
19 MSTATUS_SPIE
= 0x00000020
20 MSTATUS_HPIE
= 0x00000040
21 MSTATUS_MPIE
= 0x00000080
22 MSTATUS_SPP
= 0x00000100
23 MSTATUS_HPP
= 0x00000600
24 MSTATUS_MPP
= 0x00001800
25 MSTATUS_FS
= 0x00006000
26 MSTATUS_XS
= 0x00018000
27 MSTATUS_MPRV
= 0x00020000
28 MSTATUS_PUM
= 0x00040000
29 MSTATUS_MXR
= 0x00080000
30 MSTATUS_VM
= 0x1F000000
31 MSTATUS32_SD
= 0x80000000
32 MSTATUS64_SD
= 0x8000000000000000
42 gdb
= testlib
.Gdb(parsed
.gdb
)
47 gdb
.command("file %s" % binary
)
49 gdb
.command("set arch riscv:rv%d" % target
.xlen
)
50 gdb
.command("set remotetimeout %d" % target
.timeout_sec
)
52 gdb
.command("target extended-remote localhost:%d" % port
)
57 def ihex_line(address
, record_type
, data
):
58 assert len(data
) < 128
59 line
= ":%02X%04X%02X" % (len(data
), address
, record_type
)
61 check
+= address
% 256
67 line
+= "%02X" % value
68 line
+= "%02X\n" % ((256-check
)%256)
72 assert line
.startswith(":")
74 data_len
= int(line
[:2], 16)
75 address
= int(line
[2:6], 16)
76 record_type
= int(line
[6:8], 16)
78 for i
in range(data_len
):
79 data
+= "%c" % int(line
[8+2*i
:10+2*i
], 16)
80 return record_type
, address
, data
82 def readable_binary_string(s
):
83 return "".join("%02x" % ord(c
) for c
in s
)
85 class DeleteServer(unittest
.TestCase
):
89 class SimpleRegisterTest(DeleteServer
):
91 self
.server
= target
.server()
92 self
.gdb
= gdb(target
, self
.server
.port
)
95 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
96 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
97 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
98 self
.gdb
.p("$pc=0x%x" % target
.ram
)
100 def check_reg(self
, name
):
101 a
= random
.randrange(1<<target
.xlen
)
102 b
= random
.randrange(1<<target
.xlen
)
103 self
.gdb
.p("$%s=0x%x" % (name
, a
))
105 self
.assertEqual(self
.gdb
.p("$%s" % name
), a
)
106 self
.gdb
.p("$%s=0x%x" % (name
, b
))
108 self
.assertEqual(self
.gdb
.p("$%s" % name
), b
)
111 # S0 is saved/restored in DSCRATCH
115 # S1 is saved/restored in Debug RAM
119 # T0 is not saved/restored at all
123 # T2 is not saved/restored at all
126 class SimpleMemoryTest(DeleteServer
):
128 self
.server
= target
.server()
129 self
.gdb
= gdb(target
, self
.server
.port
)
131 def access_test(self
, size
, data_type
):
132 self
.assertEqual(self
.gdb
.p("sizeof(%s)" % data_type
),
134 a
= 0x86753095555aaaa & ((1<<(size
*8))-1)
135 b
= 0xdeadbeef12345678 & ((1<<(size
*8))-1)
136 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
, a
))
137 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
+ size
, b
))
138 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
)), a
)
139 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
+ size
)), b
)
142 self
.access_test(1, 'char')
145 self
.access_test(2, 'short')
148 self
.access_test(4, 'int')
151 self
.access_test(8, 'long long')
153 def test_block(self
):
156 a
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
158 for i
in range(length
/ line_length
):
159 line_data
= "".join(["%c" % random
.randrange(256) for _
in range(line_length
)])
161 a
.write(ihex_line(i
* line_length
, 0, line_data
))
164 self
.gdb
.command("restore %s 0x%x" % (a
.name
, target
.ram
))
165 for offset
in range(0, length
, 19*4) + [length
-4]:
166 value
= self
.gdb
.p("*((int*)0x%x)" % (target
.ram
+ offset
))
167 written
= ord(data
[offset
]) | \
168 (ord(data
[offset
+1]) << 8) | \
169 (ord(data
[offset
+2]) << 16) | \
170 (ord(data
[offset
+3]) << 24)
171 self
.assertEqual(value
, written
)
173 b
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
174 self
.gdb
.command("dump ihex memory %s 0x%x 0x%x" % (b
.name
, target
.ram
,
175 target
.ram
+ length
))
177 record_type
, address
, line_data
= ihex_parse(line
)
178 if (record_type
== 0):
179 self
.assertEqual(readable_binary_string(line_data
),
180 readable_binary_string(data
[address
:address
+len(line_data
)]))
182 class InstantHaltTest(DeleteServer
):
184 self
.server
= target
.server()
185 self
.gdb
= gdb(target
, self
.server
.port
)
187 def test_instant_halt(self
):
188 self
.assertEqual(target
.reset_vector
, self
.gdb
.p("$pc"))
189 # mcycle and minstret have no defined reset value.
190 mstatus
= self
.gdb
.p("$mstatus")
191 self
.assertEqual(mstatus
& (MSTATUS_MIE | MSTATUS_MPRV |
194 def test_change_pc(self
):
195 """Change the PC right as we come out of reset."""
197 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
198 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
199 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
200 self
.gdb
.p("$pc=0x%x" % target
.ram
)
202 self
.assertEqual((target
.ram
+ 4), self
.gdb
.p("$pc"))
204 self
.assertEqual((target
.ram
+ 8), self
.gdb
.p("$pc"))
206 class DebugTest(DeleteServer
):
208 # Include malloc so that gdb can make function calls. I suspect this
209 # malloc will silently blow through the memory set aside for it, so be
211 self
.binary
= target
.compile("programs/debug.c", "programs/checksum.c",
212 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
213 self
.server
= target
.server()
214 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
218 def exit(self
, expected_result
= 0xc86455d4):
219 output
= self
.gdb
.c()
220 self
.assertIn("Breakpoint", output
)
221 self
.assertIn("_exit", output
)
222 self
.assertEqual(self
.gdb
.p("status"), expected_result
)
224 def test_function_call(self
):
225 self
.gdb
.b("main:start")
227 text
= "Howdy, Earth!"
228 gdb_length
= self
.gdb
.p('strlen("%s")' % text
)
229 self
.assertEqual(gdb_length
, len(text
))
232 def test_change_string(self
):
233 text
= "This little piggy went to the market."
234 self
.gdb
.b("main:start")
236 self
.gdb
.p('fox = "%s"' % text
)
237 self
.exit(0x43b497b8)
239 def test_turbostep(self
):
240 """Single step a bunch of times."""
241 self
.gdb
.command("p i=0");
247 pc
= self
.gdb
.p("$pc")
248 self
.assertNotEqual(last_pc
, pc
)
249 if (last_pc
and pc
> last_pc
and pc
- last_pc
<= 4):
254 # Some basic sanity that we're not running between breakpoints or
256 self
.assertGreater(jumps
, 10)
257 self
.assertGreater(advances
, 50)
262 def test_symbols(self
):
265 output
= self
.gdb
.c()
266 self
.assertIn(", main ", output
)
267 output
= self
.gdb
.c()
268 self
.assertIn(", rot13 ", output
)
270 def test_breakpoint(self
):
272 # The breakpoint should be hit exactly 2 times.
274 output
= self
.gdb
.c()
276 self
.assertIn("Breakpoint ", output
)
277 #TODO self.assertIn("rot13 ", output)
280 def test_hwbp_1(self
):
281 if target
.instruction_hardware_breakpoint_count
< 1:
284 self
.gdb
.hbreak("rot13")
285 # The breakpoint should be hit exactly 2 times.
287 output
= self
.gdb
.c()
289 self
.assertIn("Breakpoint ", output
)
290 #TODO self.assertIn("rot13 ", output)
293 def test_hwbp_2(self
):
294 if target
.instruction_hardware_breakpoint_count
< 2:
297 self
.gdb
.hbreak("main")
298 self
.gdb
.hbreak("rot13")
299 # We should hit 3 breakpoints.
301 output
= self
.gdb
.c()
303 self
.assertIn("Breakpoint ", output
)
304 #TODO self.assertIn("rot13 ", output)
307 def test_too_many_hwbp(self
):
309 self
.gdb
.hbreak("*rot13 + %d" % (i
* 4))
311 output
= self
.gdb
.c()
312 self
.assertIn("Cannot insert hardware breakpoint", output
)
313 # Clean up, otherwise the hardware breakpoints stay set and future
315 self
.gdb
.command("D")
317 def test_registers(self
):
318 # Get to a point in the code where some registers have actually been
323 # Try both forms to test gdb.
324 for cmd
in ("info all-registers", "info registers all"):
325 output
= self
.gdb
.command(cmd
)
326 self
.assertNotIn("Could not", output
)
327 for reg
in ('zero', 'ra', 'sp', 'gp', 'tp'):
328 self
.assertIn(reg
, output
)
331 # mcpuid is one of the few registers that should have the high bit set
333 # Leave this commented out until gdb and spike agree on the encoding of
334 # mcpuid (which is going to be renamed to misa in any case).
335 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
338 # The instret register should always be changing.
341 # instret = self.gdb.p("$instret")
342 # self.assertNotEqual(instret, last_instret)
343 # last_instret = instret
348 def test_interrupt(self
):
349 """Sending gdb ^C while the program is running should cause it to halt."""
350 self
.gdb
.b("main:start")
353 self
.gdb
.c(wait
=False)
355 output
= self
.gdb
.interrupt()
356 #TODO: assert "main" in output
357 self
.assertGreater(self
.gdb
.p("j"), 10)
361 class StepTest(DeleteServer
):
363 self
.binary
= target
.compile("programs/step.S")
364 self
.server
= target
.server()
365 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
371 main
= self
.gdb
.p("$pc")
372 for expected
in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
374 pc
= self
.gdb
.p("$pc")
375 self
.assertEqual("%x" % pc
, "%x" % (expected
+ main
))
377 class RegsTest(DeleteServer
):
379 self
.binary
= target
.compile("programs/regs.S")
380 self
.server
= target
.server()
381 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
384 self
.gdb
.b("handle_trap")
387 def test_write_gprs(self
):
388 regs
= [("x%d" % n
) for n
in range(2, 32)]
390 self
.gdb
.p("$pc=write_regs")
391 for i
, r
in enumerate(regs
):
392 self
.gdb
.p("$%s=%d" % (r
, (0xdeadbeef<<i
)+17))
393 self
.gdb
.p("$x1=data")
394 self
.gdb
.command("b all_done")
395 output
= self
.gdb
.c()
396 self
.assertIn("Breakpoint ", output
)
398 # Just to get this data in the log.
399 self
.gdb
.command("x/30gx data")
400 self
.gdb
.command("info registers")
401 for n
in range(len(regs
)):
402 self
.assertEqual(self
.gdb
.x("data+%d" % (8*n
), 'g'),
403 ((0xdeadbeef<<n
)+17) & ((1<<target
.xlen
)-1))
405 def test_write_csrs(self
):
406 # As much a test of gdb as of the simulator.
407 self
.gdb
.p("$mscratch=0")
409 self
.assertEqual(self
.gdb
.p("$mscratch"), 0)
410 self
.gdb
.p("$mscratch=123")
412 self
.assertEqual(self
.gdb
.p("$mscratch"), 123)
414 self
.gdb
.command("p $pc=write_regs")
415 self
.gdb
.command("p $a0=data")
416 self
.gdb
.command("b all_done")
417 self
.gdb
.command("c")
419 self
.assertEqual(123, self
.gdb
.p("$mscratch"))
420 self
.assertEqual(123, self
.gdb
.p("$x1"))
421 self
.assertEqual(123, self
.gdb
.p("$csr832"))
423 class DownloadTest(DeleteServer
):
425 length
= min(2**20, target
.ram_size
- 2048)
426 download_c
= tempfile
.NamedTemporaryFile(prefix
="download_", suffix
=".c")
427 download_c
.write("#include <stdint.h>\n")
428 download_c
.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
429 download_c
.write("uint32_t length = %d;\n" % length
)
430 download_c
.write("uint8_t d[%d] = {\n" % length
)
432 for i
in range(length
/ 16):
433 download_c
.write(" /* 0x%04x */ " % (i
* 16));
435 value
= random
.randrange(1<<8)
436 download_c
.write("%d, " % value
)
437 self
.crc
= binascii
.crc32("%c" % value
, self
.crc
)
438 download_c
.write("\n");
439 download_c
.write("};\n");
440 download_c
.write("uint8_t *data = &d[0];\n");
441 download_c
.write("uint32_t main() { return crc32a(data, length); }\n")
447 self
.binary
= target
.compile(download_c
.name
, "programs/checksum.c")
448 self
.server
= target
.server()
449 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
451 def test_download(self
):
452 output
= self
.gdb
.load()
453 self
.gdb
.command("b _exit")
455 self
.assertEqual(self
.gdb
.p("status"), self
.crc
)
457 class MprvTest(DeleteServer
):
459 self
.binary
= target
.compile("programs/mprv.S")
460 self
.server
= target
.server()
461 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
465 """Test that the debugger can access memory when MPRV is set."""
466 self
.gdb
.c(wait
=False)
469 output
= self
.gdb
.command("p/x *(int*)(((char*)&data)-0x80000000)")
470 self
.assertIn("0xbead", output
)
472 class PrivTest(DeleteServer
):
474 self
.binary
= target
.compile("programs/priv.S")
475 self
.server
= target
.server()
476 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
479 misa
= self
.gdb
.p("$misa")
480 self
.supported
= set()
482 self
.supported
.add(0)
484 self
.supported
.add(1)
486 self
.supported
.add(2)
487 self
.supported
.add(3)
490 """Test reading/writing priv."""
491 for privilege
in range(4):
492 self
.gdb
.p("$priv=%d" % privilege
)
494 actual
= self
.gdb
.p("$priv")
495 self
.assertIn(actual
, self
.supported
)
496 if privilege
in self
.supported
:
497 self
.assertEqual(actual
, privilege
)
499 def test_change(self
):
500 """Test that the core's privilege level actually changes."""
502 if 0 not in self
.supported
:
503 # TODO: return not applicable
510 self
.gdb
.p("$priv=3")
511 main
= self
.gdb
.p("$pc")
513 self
.assertEqual("%x" % self
.gdb
.p("$pc"), "%x" % (main
+4))
516 self
.gdb
.p("$priv=0")
518 # Should have taken an exception, so be nowhere near main.
519 pc
= self
.gdb
.p("$pc")
520 self
.assertTrue(pc
< main
or pc
> main
+ 0x100)
522 class Target(object):
527 raise NotImplementedError
529 def compile(self
, *sources
):
530 binary_name
= "%s_%s-%d" % (
532 os
.path
.basename(os
.path
.splitext(sources
[0])[0]),
535 self
.temporary_binary
= tempfile
.NamedTemporaryFile(
536 prefix
=binary_name
+ "_")
537 binary_name
= self
.temporary_binary
.name
538 testlib
.compile(sources
+
539 ("programs/entry.S", "programs/init.c",
541 "-T", "targets/%s/link.lds" % (self
.directory
or self
.name
),
548 class SpikeTarget(Target
):
551 ram_size
= 5 * 1024 * 1024
552 instruction_hardware_breakpoint_count
= 0
553 reset_vector
= 0x1000
555 class Spike64Target(SpikeTarget
):
560 return testlib
.Spike(parsed
.cmd
, halted
=True)
562 class Spike32Target(SpikeTarget
):
567 return testlib
.Spike(parsed
.cmd
, halted
=True, xlen
=32)
569 class FreedomE300Target(Target
):
570 name
= "freedom-e300"
574 instruction_hardware_breakpoint_count
= 2
577 return testlib
.Openocd(cmd
=parsed
.cmd
,
578 config
="targets/%s/openocd.cfg" % self
.name
)
580 class FreedomE300SimTarget(Target
):
581 name
= "freedom-e300-sim"
585 ram_size
= 256 * 1024 * 1024
586 instruction_hardware_breakpoint_count
= 2
589 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
590 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
591 config
="targets/%s/openocd.cfg" % self
.name
,
596 class FreedomU500Target(Target
):
597 name
= "freedom-u500"
601 instruction_hardware_breakpoint_count
= 2
604 return testlib
.Openocd(cmd
=parsed
.cmd
,
605 config
="targets/%s/openocd.cfg" % self
.name
)
607 class FreedomU500SimTarget(Target
):
608 name
= "freedom-u500-sim"
612 ram_size
= 256 * 1024 * 1024
613 instruction_hardware_breakpoint_count
= 2
616 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
617 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
618 config
="targets/%s/openocd.cfg" % self
.name
,
628 FreedomE300SimTarget
,
629 FreedomU500SimTarget
]
632 parser
= argparse
.ArgumentParser(
634 Example command line from the real world:
635 Run all RegsTest cases against a physical FPGA, with custom openocd command:
636 ./gdbserver.py --freedom-e-300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
638 group
= parser
.add_mutually_exclusive_group(required
=True)
640 group
.add_argument("--%s" % t
.name
, action
="store_const", const
=t
,
642 parser
.add_argument("--run",
643 help="The command to use to start the actual target (e.g. simulation)")
644 parser
.add_argument("--cmd",
645 help="The command to use to start the debug server.")
646 parser
.add_argument("--gdb",
647 help="The command to use to start gdb.")
649 xlen_group
= parser
.add_mutually_exclusive_group()
650 xlen_group
.add_argument("--32", action
="store_const", const
=32, dest
="xlen",
651 help="Force the target to be 32-bit.")
652 xlen_group
.add_argument("--64", action
="store_const", const
=64, dest
="xlen",
653 help="Force the target to be 64-bit.")
655 parser
.add_argument("--isolate", action
="store_true",
656 help="Try to run in such a way that multiple instances can run at "
657 "the same time. This may make it harder to debug a failure if it "
660 parser
.add_argument("unittest", nargs
="*")
662 parsed
= parser
.parse_args()
665 target
= parsed
.target()
668 target
.xlen
= parsed
.xlen
670 unittest
.main(argv
=[sys
.argv
[0]] + parsed
.unittest
)
672 # TROUBLESHOOTING TIPS
673 # If a particular test fails, run just that one test, eg.:
674 # ./gdbserver.py MprvTest.test_mprv
675 # Then inspect gdb.log and spike.log to see what happened in more detail.
677 if __name__
== '__main__':