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 self
.assertEqual(self
.gdb
.p('fib(6)'), 8)
228 self
.assertEqual(self
.gdb
.p('fib(7)'), 13)
231 def test_change_string(self
):
232 text
= "This little piggy went to the market."
233 self
.gdb
.b("main:start")
235 self
.gdb
.p('fox = "%s"' % text
)
236 self
.exit(0x43b497b8)
238 def test_turbostep(self
):
239 """Single step a bunch of times."""
240 self
.gdb
.b("main:start")
242 self
.gdb
.command("p i=0");
248 pc
= self
.gdb
.p("$pc")
249 self
.assertNotEqual(last_pc
, pc
)
250 if (last_pc
and pc
> last_pc
and pc
- last_pc
<= 4):
255 # Some basic sanity that we're not running between breakpoints or
257 self
.assertGreater(jumps
, 10)
258 self
.assertGreater(advances
, 50)
263 def test_symbols(self
):
266 output
= self
.gdb
.c()
267 self
.assertIn(", main ", output
)
268 output
= self
.gdb
.c()
269 self
.assertIn(", rot13 ", output
)
271 def test_breakpoint(self
):
273 # The breakpoint should be hit exactly 2 times.
275 output
= self
.gdb
.c()
277 self
.assertIn("Breakpoint ", output
)
278 #TODO self.assertIn("rot13 ", output)
281 def test_hwbp_1(self
):
282 if target
.instruction_hardware_breakpoint_count
< 1:
285 self
.gdb
.hbreak("rot13")
286 # The breakpoint should be hit exactly 2 times.
288 output
= self
.gdb
.c()
290 self
.assertIn("Breakpoint ", output
)
291 #TODO self.assertIn("rot13 ", output)
294 def test_hwbp_2(self
):
295 if target
.instruction_hardware_breakpoint_count
< 2:
298 self
.gdb
.hbreak("main")
299 self
.gdb
.hbreak("rot13")
300 # We should hit 3 breakpoints.
302 output
= self
.gdb
.c()
304 self
.assertIn("Breakpoint ", output
)
305 #TODO self.assertIn("rot13 ", output)
308 def test_too_many_hwbp(self
):
310 self
.gdb
.hbreak("*rot13 + %d" % (i
* 4))
312 output
= self
.gdb
.c()
313 self
.assertIn("Cannot insert hardware breakpoint", output
)
314 # Clean up, otherwise the hardware breakpoints stay set and future
316 self
.gdb
.command("D")
318 def test_registers(self
):
319 # Get to a point in the code where some registers have actually been
324 # Try both forms to test gdb.
325 for cmd
in ("info all-registers", "info registers all"):
326 output
= self
.gdb
.command(cmd
)
327 self
.assertNotIn("Could not", output
)
328 for reg
in ('zero', 'ra', 'sp', 'gp', 'tp'):
329 self
.assertIn(reg
, output
)
332 # mcpuid is one of the few registers that should have the high bit set
334 # Leave this commented out until gdb and spike agree on the encoding of
335 # mcpuid (which is going to be renamed to misa in any case).
336 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
339 # The instret register should always be changing.
342 # instret = self.gdb.p("$instret")
343 # self.assertNotEqual(instret, last_instret)
344 # last_instret = instret
349 def test_interrupt(self
):
350 """Sending gdb ^C while the program is running should cause it to halt."""
351 self
.gdb
.b("main:start")
354 self
.gdb
.c(wait
=False)
356 output
= self
.gdb
.interrupt()
357 #TODO: assert "main" in output
358 self
.assertGreater(self
.gdb
.p("j"), 10)
362 class StepTest(DeleteServer
):
364 self
.binary
= target
.compile("programs/step.S")
365 self
.server
= target
.server()
366 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
372 main
= self
.gdb
.p("$pc")
373 for expected
in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
375 pc
= self
.gdb
.p("$pc")
376 self
.assertEqual("%x" % pc
, "%x" % (expected
+ main
))
378 class RegsTest(DeleteServer
):
380 self
.binary
= target
.compile("programs/regs.S")
381 self
.server
= target
.server()
382 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
385 self
.gdb
.b("handle_trap")
388 def test_write_gprs(self
):
389 regs
= [("x%d" % n
) for n
in range(2, 32)]
391 self
.gdb
.p("$pc=write_regs")
392 for i
, r
in enumerate(regs
):
393 self
.gdb
.p("$%s=%d" % (r
, (0xdeadbeef<<i
)+17))
394 self
.gdb
.p("$x1=data")
395 self
.gdb
.command("b all_done")
396 output
= self
.gdb
.c()
397 self
.assertIn("Breakpoint ", output
)
399 # Just to get this data in the log.
400 self
.gdb
.command("x/30gx data")
401 self
.gdb
.command("info registers")
402 for n
in range(len(regs
)):
403 self
.assertEqual(self
.gdb
.x("data+%d" % (8*n
), 'g'),
404 ((0xdeadbeef<<n
)+17) & ((1<<target
.xlen
)-1))
406 def test_write_csrs(self
):
407 # As much a test of gdb as of the simulator.
408 self
.gdb
.p("$mscratch=0")
410 self
.assertEqual(self
.gdb
.p("$mscratch"), 0)
411 self
.gdb
.p("$mscratch=123")
413 self
.assertEqual(self
.gdb
.p("$mscratch"), 123)
415 self
.gdb
.command("p $pc=write_regs")
416 self
.gdb
.command("p $a0=data")
417 self
.gdb
.command("b all_done")
418 self
.gdb
.command("c")
420 self
.assertEqual(123, self
.gdb
.p("$mscratch"))
421 self
.assertEqual(123, self
.gdb
.p("$x1"))
422 self
.assertEqual(123, self
.gdb
.p("$csr832"))
424 class DownloadTest(DeleteServer
):
426 length
= min(2**20, target
.ram_size
- 2048)
427 download_c
= tempfile
.NamedTemporaryFile(prefix
="download_", suffix
=".c")
428 download_c
.write("#include <stdint.h>\n")
429 download_c
.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
430 download_c
.write("uint32_t length = %d;\n" % length
)
431 download_c
.write("uint8_t d[%d] = {\n" % length
)
433 for i
in range(length
/ 16):
434 download_c
.write(" /* 0x%04x */ " % (i
* 16));
436 value
= random
.randrange(1<<8)
437 download_c
.write("%d, " % value
)
438 self
.crc
= binascii
.crc32("%c" % value
, self
.crc
)
439 download_c
.write("\n");
440 download_c
.write("};\n");
441 download_c
.write("uint8_t *data = &d[0];\n");
442 download_c
.write("uint32_t main() { return crc32a(data, length); }\n")
448 self
.binary
= target
.compile(download_c
.name
, "programs/checksum.c")
449 self
.server
= target
.server()
450 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
452 def test_download(self
):
453 output
= self
.gdb
.load()
454 self
.gdb
.command("b _exit")
456 self
.assertEqual(self
.gdb
.p("status"), self
.crc
)
458 class MprvTest(DeleteServer
):
460 self
.binary
= target
.compile("programs/mprv.S")
461 self
.server
= target
.server()
462 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
466 """Test that the debugger can access memory when MPRV is set."""
467 self
.gdb
.c(wait
=False)
470 output
= self
.gdb
.command("p/x *(int*)(((char*)&data)-0x80000000)")
471 self
.assertIn("0xbead", output
)
473 class PrivTest(DeleteServer
):
475 self
.binary
= target
.compile("programs/priv.S")
476 self
.server
= target
.server()
477 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
480 misa
= self
.gdb
.p("$misa")
481 self
.supported
= set()
483 self
.supported
.add(0)
485 self
.supported
.add(1)
487 self
.supported
.add(2)
488 self
.supported
.add(3)
491 """Test reading/writing priv."""
492 for privilege
in range(4):
493 self
.gdb
.p("$priv=%d" % privilege
)
495 actual
= self
.gdb
.p("$priv")
496 self
.assertIn(actual
, self
.supported
)
497 if privilege
in self
.supported
:
498 self
.assertEqual(actual
, privilege
)
500 def test_change(self
):
501 """Test that the core's privilege level actually changes."""
503 if 0 not in self
.supported
:
504 # TODO: return not applicable
511 self
.gdb
.p("$priv=3")
512 main
= self
.gdb
.p("$pc")
514 self
.assertEqual("%x" % self
.gdb
.p("$pc"), "%x" % (main
+4))
517 self
.gdb
.p("$priv=0")
519 # Should have taken an exception, so be nowhere near main.
520 pc
= self
.gdb
.p("$pc")
521 self
.assertTrue(pc
< main
or pc
> main
+ 0x100)
523 class Target(object):
528 raise NotImplementedError
530 def compile(self
, *sources
):
531 binary_name
= "%s_%s-%d" % (
533 os
.path
.basename(os
.path
.splitext(sources
[0])[0]),
536 self
.temporary_binary
= tempfile
.NamedTemporaryFile(
537 prefix
=binary_name
+ "_")
538 binary_name
= self
.temporary_binary
.name
539 testlib
.compile(sources
+
540 ("programs/entry.S", "programs/init.c",
542 "-T", "targets/%s/link.lds" % (self
.directory
or self
.name
),
549 class SpikeTarget(Target
):
552 ram_size
= 5 * 1024 * 1024
553 instruction_hardware_breakpoint_count
= 0
554 reset_vector
= 0x1000
556 class Spike64Target(SpikeTarget
):
561 return testlib
.Spike(parsed
.cmd
, halted
=True)
563 class Spike32Target(SpikeTarget
):
568 return testlib
.Spike(parsed
.cmd
, halted
=True, xlen
=32)
570 class FreedomE300Target(Target
):
571 name
= "freedom-e300"
575 instruction_hardware_breakpoint_count
= 2
578 return testlib
.Openocd(cmd
=parsed
.cmd
,
579 config
="targets/%s/openocd.cfg" % self
.name
)
581 class FreedomE300SimTarget(Target
):
582 name
= "freedom-e300-sim"
586 ram_size
= 256 * 1024 * 1024
587 instruction_hardware_breakpoint_count
= 2
590 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
591 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
592 config
="targets/%s/openocd.cfg" % self
.name
,
597 class FreedomU500Target(Target
):
598 name
= "freedom-u500"
602 instruction_hardware_breakpoint_count
= 2
605 return testlib
.Openocd(cmd
=parsed
.cmd
,
606 config
="targets/%s/openocd.cfg" % self
.name
)
608 class FreedomU500SimTarget(Target
):
609 name
= "freedom-u500-sim"
613 ram_size
= 256 * 1024 * 1024
614 instruction_hardware_breakpoint_count
= 2
617 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
618 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
619 config
="targets/%s/openocd.cfg" % self
.name
,
629 FreedomE300SimTarget
,
630 FreedomU500SimTarget
]
633 parser
= argparse
.ArgumentParser(
635 Example command line from the real world:
636 Run all RegsTest cases against a physical FPGA, with custom openocd command:
637 ./gdbserver.py --freedom-e-300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
639 group
= parser
.add_mutually_exclusive_group(required
=True)
641 group
.add_argument("--%s" % t
.name
, action
="store_const", const
=t
,
643 parser
.add_argument("--run",
644 help="The command to use to start the actual target (e.g. simulation)")
645 parser
.add_argument("--cmd",
646 help="The command to use to start the debug server.")
647 parser
.add_argument("--gdb",
648 help="The command to use to start gdb.")
650 xlen_group
= parser
.add_mutually_exclusive_group()
651 xlen_group
.add_argument("--32", action
="store_const", const
=32, dest
="xlen",
652 help="Force the target to be 32-bit.")
653 xlen_group
.add_argument("--64", action
="store_const", const
=64, dest
="xlen",
654 help="Force the target to be 64-bit.")
656 parser
.add_argument("--isolate", action
="store_true",
657 help="Try to run in such a way that multiple instances can run at "
658 "the same time. This may make it harder to debug a failure if it "
661 parser
.add_argument("unittest", nargs
="*")
663 parsed
= parser
.parse_args()
666 target
= parsed
.target()
669 target
.xlen
= parsed
.xlen
671 unittest
.main(argv
=[sys
.argv
[0]] + parsed
.unittest
)
673 # TROUBLESHOOTING TIPS
674 # If a particular test fails, run just that one test, eg.:
675 # ./gdbserver.py MprvTest.test_mprv
676 # Then inspect gdb.log and spike.log to see what happened in more detail.
678 if __name__
== '__main__':