15 MSTATUS_UIE
= 0x00000001
16 MSTATUS_SIE
= 0x00000002
17 MSTATUS_HIE
= 0x00000004
18 MSTATUS_MIE
= 0x00000008
19 MSTATUS_UPIE
= 0x00000010
20 MSTATUS_SPIE
= 0x00000020
21 MSTATUS_HPIE
= 0x00000040
22 MSTATUS_MPIE
= 0x00000080
23 MSTATUS_SPP
= 0x00000100
24 MSTATUS_HPP
= 0x00000600
25 MSTATUS_MPP
= 0x00001800
26 MSTATUS_FS
= 0x00006000
27 MSTATUS_XS
= 0x00018000
28 MSTATUS_MPRV
= 0x00020000
29 MSTATUS_PUM
= 0x00040000
30 MSTATUS_MXR
= 0x00080000
31 MSTATUS_VM
= 0x1F000000
32 MSTATUS32_SD
= 0x80000000
33 MSTATUS64_SD
= 0x8000000000000000
43 gdb
= testlib
.Gdb(parsed
.gdb
)
48 gdb
.command("file %s" % binary
)
50 gdb
.command("set arch riscv:rv%d" % target
.xlen
)
51 gdb
.command("set remotetimeout %d" % target
.timeout_sec
)
53 gdb
.command("target extended-remote localhost:%d" % port
)
60 def ihex_line(address
, record_type
, data
):
61 assert len(data
) < 128
62 line
= ":%02X%04X%02X" % (len(data
), address
, record_type
)
64 check
+= address
% 256
70 line
+= "%02X" % value
71 line
+= "%02X\n" % ((256-check
)%256)
75 assert line
.startswith(":")
77 data_len
= int(line
[:2], 16)
78 address
= int(line
[2:6], 16)
79 record_type
= int(line
[6:8], 16)
81 for i
in range(data_len
):
82 data
+= "%c" % int(line
[8+2*i
:10+2*i
], 16)
83 return record_type
, address
, data
85 def readable_binary_string(s
):
86 return "".join("%02x" % ord(c
) for c
in s
)
88 class DeleteServer(unittest
.TestCase
):
92 class SimpleRegisterTest(DeleteServer
):
94 self
.server
= target
.server()
95 self
.gdb
= gdb(target
, self
.server
.port
)
98 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
99 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
100 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
101 self
.gdb
.p("$pc=0x%x" % target
.ram
)
103 def check_reg(self
, name
):
104 a
= random
.randrange(1<<target
.xlen
)
105 b
= random
.randrange(1<<target
.xlen
)
106 self
.gdb
.p("$%s=0x%x" % (name
, a
))
108 self
.assertEqual(self
.gdb
.p("$%s" % name
), a
)
109 self
.gdb
.p("$%s=0x%x" % (name
, b
))
111 self
.assertEqual(self
.gdb
.p("$%s" % name
), b
)
114 # S0 is saved/restored in DSCRATCH
118 # S1 is saved/restored in Debug RAM
122 # T0 is not saved/restored at all
126 # T2 is not saved/restored at all
129 class SimpleMemoryTest(DeleteServer
):
131 self
.server
= target
.server()
132 self
.gdb
= gdb(target
, self
.server
.port
)
134 def access_test(self
, size
, data_type
):
135 self
.assertEqual(self
.gdb
.p("sizeof(%s)" % data_type
),
137 a
= 0x86753095555aaaa & ((1<<(size
*8))-1)
138 b
= 0xdeadbeef12345678 & ((1<<(size
*8))-1)
139 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
, a
))
140 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
+ size
, b
))
141 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
)), a
)
142 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
+ size
)), b
)
145 self
.access_test(1, 'char')
148 self
.access_test(2, 'short')
151 self
.access_test(4, 'int')
154 self
.access_test(8, 'long long')
156 def test_block(self
):
159 a
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
161 for i
in range(length
/ line_length
):
162 line_data
= "".join(["%c" % random
.randrange(256) for _
in range(line_length
)])
164 a
.write(ihex_line(i
* line_length
, 0, line_data
))
167 self
.gdb
.command("restore %s 0x%x" % (a
.name
, target
.ram
))
168 for offset
in range(0, length
, 19*4) + [length
-4]:
169 value
= self
.gdb
.p("*((int*)0x%x)" % (target
.ram
+ offset
))
170 written
= ord(data
[offset
]) | \
171 (ord(data
[offset
+1]) << 8) | \
172 (ord(data
[offset
+2]) << 16) | \
173 (ord(data
[offset
+3]) << 24)
174 self
.assertEqual(value
, written
)
176 b
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
177 self
.gdb
.command("dump ihex memory %s 0x%x 0x%x" % (b
.name
, target
.ram
,
178 target
.ram
+ length
))
180 record_type
, address
, line_data
= ihex_parse(line
)
181 if (record_type
== 0):
182 self
.assertEqual(readable_binary_string(line_data
),
183 readable_binary_string(data
[address
:address
+len(line_data
)]))
185 class InstantHaltTest(DeleteServer
):
187 self
.server
= target
.server()
188 self
.gdb
= gdb(target
, self
.server
.port
)
190 def test_instant_halt(self
):
191 self
.assertEqual(target
.reset_vector
, self
.gdb
.p("$pc"))
192 # mcycle and minstret have no defined reset value.
193 mstatus
= self
.gdb
.p("$mstatus")
194 self
.assertEqual(mstatus
& (MSTATUS_MIE | MSTATUS_MPRV |
197 def test_change_pc(self
):
198 """Change the PC right as we come out of reset."""
200 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
201 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
202 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
203 self
.gdb
.p("$pc=0x%x" % target
.ram
)
205 self
.assertEqual((target
.ram
+ 4), self
.gdb
.p("$pc"))
207 self
.assertEqual((target
.ram
+ 8), self
.gdb
.p("$pc"))
209 class DebugTest(DeleteServer
):
211 # Include malloc so that gdb can make function calls. I suspect this
212 # malloc will silently blow through the memory set aside for it, so be
214 self
.binary
= target
.compile("programs/debug.c", "programs/checksum.c",
215 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
216 self
.server
= target
.server()
217 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
221 def exit(self
, expected_result
= 0xc86455d4):
222 output
= self
.gdb
.c()
223 self
.assertIn("Breakpoint", output
)
224 self
.assertIn("_exit", output
)
225 self
.assertEqual(self
.gdb
.p("status"), expected_result
)
227 def test_function_call(self
):
228 self
.gdb
.b("main:start")
230 self
.assertEqual(self
.gdb
.p('fib(6)'), 8)
231 self
.assertEqual(self
.gdb
.p('fib(7)'), 13)
234 def test_change_string(self
):
235 text
= "This little piggy went to the market."
236 self
.gdb
.b("main:start")
238 self
.gdb
.p('fox = "%s"' % text
)
239 self
.exit(0x43b497b8)
241 def test_turbostep(self
):
242 """Single step a bunch of times."""
243 self
.gdb
.b("main:start")
245 self
.gdb
.command("p i=0");
251 pc
= self
.gdb
.p("$pc")
252 self
.assertNotEqual(last_pc
, pc
)
253 if (last_pc
and pc
> last_pc
and pc
- last_pc
<= 4):
258 # Some basic sanity that we're not running between breakpoints or
260 self
.assertGreater(jumps
, 10)
261 self
.assertGreater(advances
, 50)
266 def test_symbols(self
):
269 output
= self
.gdb
.c()
270 self
.assertIn(", main ", output
)
271 output
= self
.gdb
.c()
272 self
.assertIn(", rot13 ", output
)
274 def test_breakpoint(self
):
276 # The breakpoint should be hit exactly 2 times.
278 output
= self
.gdb
.c()
280 self
.assertIn("Breakpoint ", output
)
281 #TODO self.assertIn("rot13 ", output)
284 def test_hwbp_1(self
):
285 if target
.instruction_hardware_breakpoint_count
< 1:
288 self
.gdb
.hbreak("rot13")
289 # The breakpoint should be hit exactly 2 times.
291 output
= self
.gdb
.c()
293 self
.assertIn("Breakpoint ", output
)
294 #TODO self.assertIn("rot13 ", output)
297 def test_hwbp_2(self
):
298 if target
.instruction_hardware_breakpoint_count
< 2:
301 self
.gdb
.hbreak("main")
302 self
.gdb
.hbreak("rot13")
303 # We should hit 3 breakpoints.
305 output
= self
.gdb
.c()
307 self
.assertIn("Breakpoint ", output
)
308 #TODO self.assertIn("rot13 ", output)
311 def test_too_many_hwbp(self
):
313 self
.gdb
.hbreak("*rot13 + %d" % (i
* 4))
315 output
= self
.gdb
.c()
316 self
.assertIn("Cannot insert hardware breakpoint", output
)
317 # Clean up, otherwise the hardware breakpoints stay set and future
319 self
.gdb
.command("D")
321 def test_registers(self
):
322 # Get to a point in the code where some registers have actually been
327 # Try both forms to test gdb.
328 for cmd
in ("info all-registers", "info registers all"):
329 output
= self
.gdb
.command(cmd
)
330 self
.assertNotIn("Could not", output
)
331 for reg
in ('zero', 'ra', 'sp', 'gp', 'tp'):
332 self
.assertIn(reg
, output
)
335 # mcpuid is one of the few registers that should have the high bit set
337 # Leave this commented out until gdb and spike agree on the encoding of
338 # mcpuid (which is going to be renamed to misa in any case).
339 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
342 # The instret register should always be changing.
345 # instret = self.gdb.p("$instret")
346 # self.assertNotEqual(instret, last_instret)
347 # last_instret = instret
352 def test_interrupt(self
):
353 """Sending gdb ^C while the program is running should cause it to halt."""
354 self
.gdb
.b("main:start")
357 self
.gdb
.c(wait
=False)
359 output
= self
.gdb
.interrupt()
360 #TODO: assert "main" in output
361 self
.assertGreater(self
.gdb
.p("j"), 10)
365 class StepTest(DeleteServer
):
367 self
.binary
= target
.compile("programs/step.S")
368 self
.server
= target
.server()
369 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
375 main
= self
.gdb
.p("$pc")
376 for expected
in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
378 pc
= self
.gdb
.p("$pc")
379 self
.assertEqual("%x" % pc
, "%x" % (expected
+ main
))
381 class TriggerTest(DeleteServer
):
383 self
.binary
= target
.compile("programs/trigger.S")
384 self
.server
= target
.server()
385 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
392 output
= self
.gdb
.c()
393 self
.assertIn("Breakpoint", output
)
394 self
.assertIn("_exit", output
)
396 def test_execute_instant(self
):
397 """Test an execute breakpoint on the first instruction executed out of
399 main
= self
.gdb
.p("$pc")
400 self
.gdb
.command("hbreak *0x%x" % (main
+ 4))
402 self
.assertEqual(self
.gdb
.p("$pc"), main
+4)
404 def test_load_address(self
):
405 self
.gdb
.command("rwatch *((&data)+1)");
406 output
= self
.gdb
.c()
407 self
.assertIn("read_loop", output
)
408 self
.assertEqual(self
.gdb
.p("$a0"),
409 self
.gdb
.p("(&data)+1"))
412 def test_load_address_instant(self
):
413 """Test a load address breakpoint on the first instruction executed out
415 self
.gdb
.command("b just_before_read_loop")
417 read_loop
= self
.gdb
.p("&read_loop")
418 self
.gdb
.command("rwatch data");
420 # Accept hitting the breakpoint before or after the load instruction.
421 self
.assertIn(self
.gdb
.p("$pc"), [read_loop
, read_loop
+ 4])
422 self
.assertEqual(self
.gdb
.p("$a0"), self
.gdb
.p("&data"))
424 def test_store_address(self
):
425 self
.gdb
.command("watch *((&data)+3)");
426 output
= self
.gdb
.c()
427 self
.assertIn("write_loop", output
)
428 self
.assertEqual(self
.gdb
.p("$a0"),
429 self
.gdb
.p("(&data)+3"))
432 def test_store_address_instant(self
):
433 """Test a store address breakpoint on the first instruction executed out
435 self
.gdb
.command("b just_before_write_loop")
437 write_loop
= self
.gdb
.p("&write_loop")
438 self
.gdb
.command("watch data");
440 # Accept hitting the breakpoint before or after the store instruction.
441 self
.assertIn(self
.gdb
.p("$pc"), [write_loop
, write_loop
+ 4])
442 self
.assertEqual(self
.gdb
.p("$a0"), self
.gdb
.p("&data"))
444 def test_dmode(self
):
445 self
.gdb
.command("hbreak handle_trap")
446 self
.gdb
.p("$pc=write_valid")
447 output
= self
.gdb
.c()
448 self
.assertIn("handle_trap", output
)
449 self
.assertIn("mcause=2", output
)
450 self
.assertIn("mepc=%d" % self
.gdb
.p("&write_invalid_illegal"), output
)
452 class RegsTest(DeleteServer
):
454 self
.binary
= target
.compile("programs/regs.S")
455 self
.server
= target
.server()
456 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
459 self
.gdb
.b("handle_trap")
462 def test_write_gprs(self
):
463 regs
= [("x%d" % n
) for n
in range(2, 32)]
465 self
.gdb
.p("$pc=write_regs")
466 for i
, r
in enumerate(regs
):
467 self
.gdb
.p("$%s=%d" % (r
, (0xdeadbeef<<i
)+17))
468 self
.gdb
.p("$x1=data")
469 self
.gdb
.command("b all_done")
470 output
= self
.gdb
.c()
471 self
.assertIn("Breakpoint ", output
)
473 # Just to get this data in the log.
474 self
.gdb
.command("x/30gx data")
475 self
.gdb
.command("info registers")
476 for n
in range(len(regs
)):
477 self
.assertEqual(self
.gdb
.x("data+%d" % (8*n
), 'g'),
478 ((0xdeadbeef<<n
)+17) & ((1<<target
.xlen
)-1))
480 def test_write_csrs(self
):
481 # As much a test of gdb as of the simulator.
482 self
.gdb
.p("$mscratch=0")
484 self
.assertEqual(self
.gdb
.p("$mscratch"), 0)
485 self
.gdb
.p("$mscratch=123")
487 self
.assertEqual(self
.gdb
.p("$mscratch"), 123)
489 self
.gdb
.command("p $pc=write_regs")
490 self
.gdb
.command("p $a0=data")
491 self
.gdb
.command("b all_done")
492 self
.gdb
.command("c")
494 self
.assertEqual(123, self
.gdb
.p("$mscratch"))
495 self
.assertEqual(123, self
.gdb
.p("$x1"))
496 self
.assertEqual(123, self
.gdb
.p("$csr832"))
498 class DownloadTest(DeleteServer
):
500 length
= min(2**20, target
.ram_size
- 2048)
501 download_c
= tempfile
.NamedTemporaryFile(prefix
="download_", suffix
=".c")
502 download_c
.write("#include <stdint.h>\n")
503 download_c
.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
504 download_c
.write("uint32_t length = %d;\n" % length
)
505 download_c
.write("uint8_t d[%d] = {\n" % length
)
507 for i
in range(length
/ 16):
508 download_c
.write(" /* 0x%04x */ " % (i
* 16));
510 value
= random
.randrange(1<<8)
511 download_c
.write("%d, " % value
)
512 self
.crc
= binascii
.crc32("%c" % value
, self
.crc
)
513 download_c
.write("\n");
514 download_c
.write("};\n");
515 download_c
.write("uint8_t *data = &d[0];\n");
516 download_c
.write("uint32_t main() { return crc32a(data, length); }\n")
522 self
.binary
= target
.compile(download_c
.name
, "programs/checksum.c")
523 self
.server
= target
.server()
524 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
526 def test_download(self
):
527 output
= self
.gdb
.load()
528 self
.gdb
.command("b _exit")
530 self
.assertEqual(self
.gdb
.p("status"), self
.crc
)
532 class MprvTest(DeleteServer
):
534 self
.binary
= target
.compile("programs/mprv.S")
535 self
.server
= target
.server()
536 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
540 """Test that the debugger can access memory when MPRV is set."""
541 self
.gdb
.c(wait
=False)
544 output
= self
.gdb
.command("p/x *(int*)(((char*)&data)-0x80000000)")
545 self
.assertIn("0xbead", output
)
547 class PrivTest(DeleteServer
):
549 self
.binary
= target
.compile("programs/priv.S")
550 self
.server
= target
.server()
551 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
554 misa
= self
.gdb
.p("$misa")
555 self
.supported
= set()
557 self
.supported
.add(0)
559 self
.supported
.add(1)
561 self
.supported
.add(2)
562 self
.supported
.add(3)
565 """Test reading/writing priv."""
566 for privilege
in range(4):
567 self
.gdb
.p("$priv=%d" % privilege
)
569 actual
= self
.gdb
.p("$priv")
570 self
.assertIn(actual
, self
.supported
)
571 if privilege
in self
.supported
:
572 self
.assertEqual(actual
, privilege
)
574 def test_change(self
):
575 """Test that the core's privilege level actually changes."""
577 if 0 not in self
.supported
:
578 # TODO: return not applicable
585 self
.gdb
.p("$priv=3")
586 main
= self
.gdb
.p("$pc")
588 self
.assertEqual("%x" % self
.gdb
.p("$pc"), "%x" % (main
+4))
591 self
.gdb
.p("$priv=0")
593 # Should have taken an exception, so be nowhere near main.
594 pc
= self
.gdb
.p("$pc")
595 self
.assertTrue(pc
< main
or pc
> main
+ 0x100)
597 class Target(object):
602 raise NotImplementedError
604 def compile(self
, *sources
):
605 binary_name
= "%s_%s-%d" % (
607 os
.path
.basename(os
.path
.splitext(sources
[0])[0]),
610 self
.temporary_binary
= tempfile
.NamedTemporaryFile(
611 prefix
=binary_name
+ "_")
612 binary_name
= self
.temporary_binary
.name
613 testlib
.compile(sources
+
614 ("programs/entry.S", "programs/init.c",
616 "-T", "targets/%s/link.lds" % (self
.directory
or self
.name
),
623 class SpikeTarget(Target
):
626 ram_size
= 5 * 1024 * 1024
627 instruction_hardware_breakpoint_count
= 4
628 reset_vector
= 0x1000
630 class Spike64Target(SpikeTarget
):
635 return testlib
.Spike(parsed
.cmd
, halted
=True)
637 class Spike32Target(SpikeTarget
):
642 return testlib
.Spike(parsed
.cmd
, halted
=True, xlen
=32)
644 class FreedomE300Target(Target
):
645 name
= "freedom-e300"
649 instruction_hardware_breakpoint_count
= 2
652 return testlib
.Openocd(cmd
=parsed
.cmd
,
653 config
="targets/%s/openocd.cfg" % self
.name
)
655 class FreedomE300SimTarget(Target
):
656 name
= "freedom-e300-sim"
660 ram_size
= 256 * 1024 * 1024
661 instruction_hardware_breakpoint_count
= 2
664 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
665 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
666 config
="targets/%s/openocd.cfg" % self
.name
,
671 class FreedomU500Target(Target
):
672 name
= "freedom-u500"
676 instruction_hardware_breakpoint_count
= 2
679 return testlib
.Openocd(cmd
=parsed
.cmd
,
680 config
="targets/%s/openocd.cfg" % self
.name
)
682 class FreedomU500SimTarget(Target
):
683 name
= "freedom-u500-sim"
687 ram_size
= 256 * 1024 * 1024
688 instruction_hardware_breakpoint_count
= 2
691 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
692 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
693 config
="targets/%s/openocd.cfg" % self
.name
,
703 FreedomE300SimTarget
,
704 FreedomU500SimTarget
]
707 parser
= argparse
.ArgumentParser(
709 Example command line from the real world:
710 Run all RegsTest cases against a physical FPGA, with custom openocd command:
711 ./gdbserver.py --freedom-e-300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
713 group
= parser
.add_mutually_exclusive_group(required
=True)
715 group
.add_argument("--%s" % t
.name
, action
="store_const", const
=t
,
717 parser
.add_argument("--run",
718 help="The command to use to start the actual target (e.g. simulation)")
719 parser
.add_argument("--cmd",
720 help="The command to use to start the debug server.")
721 parser
.add_argument("--gdb",
722 help="The command to use to start gdb.")
724 xlen_group
= parser
.add_mutually_exclusive_group()
725 xlen_group
.add_argument("--32", action
="store_const", const
=32, dest
="xlen",
726 help="Force the target to be 32-bit.")
727 xlen_group
.add_argument("--64", action
="store_const", const
=64, dest
="xlen",
728 help="Force the target to be 64-bit.")
730 parser
.add_argument("--isolate", action
="store_true",
731 help="Try to run in such a way that multiple instances can run at "
732 "the same time. This may make it harder to debug a failure if it "
735 parser
.add_argument("unittest", nargs
="*")
737 parsed
= parser
.parse_args()
740 target
= parsed
.target()
743 target
.xlen
= parsed
.xlen
745 unittest
.main(argv
=[sys
.argv
[0]] + parsed
.unittest
)
747 # TROUBLESHOOTING TIPS
748 # If a particular test fails, run just that one test, eg.:
749 # ./gdbserver.py MprvTest.test_mprv
750 # Then inspect gdb.log and spike.log to see what happened in more detail.
752 if __name__
== '__main__':