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
)
58 def ihex_line(address
, record_type
, data
):
59 assert len(data
) < 128
60 line
= ":%02X%04X%02X" % (len(data
), address
, record_type
)
62 check
+= address
% 256
68 line
+= "%02X" % value
69 line
+= "%02X\n" % ((256-check
)%256)
73 assert line
.startswith(":")
75 data_len
= int(line
[:2], 16)
76 address
= int(line
[2:6], 16)
77 record_type
= int(line
[6:8], 16)
79 for i
in range(data_len
):
80 data
+= "%c" % int(line
[8+2*i
:10+2*i
], 16)
81 return record_type
, address
, data
83 def readable_binary_string(s
):
84 return "".join("%02x" % ord(c
) for c
in s
)
86 class DeleteServer(unittest
.TestCase
):
90 class SimpleRegisterTest(DeleteServer
):
92 self
.server
= target
.server()
93 self
.gdb
= gdb(target
, self
.server
.port
)
96 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
97 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
98 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
99 self
.gdb
.p("$pc=0x%x" % target
.ram
)
101 def check_reg(self
, name
):
102 a
= random
.randrange(1<<target
.xlen
)
103 b
= random
.randrange(1<<target
.xlen
)
104 self
.gdb
.p("$%s=0x%x" % (name
, a
))
106 self
.assertEqual(self
.gdb
.p("$%s" % name
), a
)
107 self
.gdb
.p("$%s=0x%x" % (name
, b
))
109 self
.assertEqual(self
.gdb
.p("$%s" % name
), b
)
112 # S0 is saved/restored in DSCRATCH
116 # S1 is saved/restored in Debug RAM
120 # T0 is not saved/restored at all
124 # T2 is not saved/restored at all
127 class SimpleMemoryTest(DeleteServer
):
129 self
.server
= target
.server()
130 self
.gdb
= gdb(target
, self
.server
.port
)
132 def access_test(self
, size
, data_type
):
133 self
.assertEqual(self
.gdb
.p("sizeof(%s)" % data_type
),
135 a
= 0x86753095555aaaa & ((1<<(size
*8))-1)
136 b
= 0xdeadbeef12345678 & ((1<<(size
*8))-1)
137 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
, a
))
138 self
.gdb
.p("*((%s*)0x%x) = 0x%x" % (data_type
, target
.ram
+ size
, b
))
139 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
)), a
)
140 self
.assertEqual(self
.gdb
.p("*((%s*)0x%x)" % (data_type
, target
.ram
+ size
)), b
)
143 self
.access_test(1, 'char')
146 self
.access_test(2, 'short')
149 self
.access_test(4, 'int')
152 self
.access_test(8, 'long long')
154 def test_block(self
):
157 a
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
159 for i
in range(length
/ line_length
):
160 line_data
= "".join(["%c" % random
.randrange(256) for _
in range(line_length
)])
162 a
.write(ihex_line(i
* line_length
, 0, line_data
))
165 self
.gdb
.command("restore %s 0x%x" % (a
.name
, target
.ram
))
166 for offset
in range(0, length
, 19*4) + [length
-4]:
167 value
= self
.gdb
.p("*((int*)0x%x)" % (target
.ram
+ offset
))
168 written
= ord(data
[offset
]) | \
169 (ord(data
[offset
+1]) << 8) | \
170 (ord(data
[offset
+2]) << 16) | \
171 (ord(data
[offset
+3]) << 24)
172 self
.assertEqual(value
, written
)
174 b
= tempfile
.NamedTemporaryFile(suffix
=".ihex")
175 self
.gdb
.command("dump ihex memory %s 0x%x 0x%x" % (b
.name
, target
.ram
,
176 target
.ram
+ length
))
178 record_type
, address
, line_data
= ihex_parse(line
)
179 if (record_type
== 0):
180 self
.assertEqual(readable_binary_string(line_data
),
181 readable_binary_string(data
[address
:address
+len(line_data
)]))
183 class InstantHaltTest(DeleteServer
):
185 self
.server
= target
.server()
186 self
.gdb
= gdb(target
, self
.server
.port
)
188 def test_instant_halt(self
):
189 self
.assertEqual(target
.reset_vector
, self
.gdb
.p("$pc"))
190 # mcycle and minstret have no defined reset value.
191 mstatus
= self
.gdb
.p("$mstatus")
192 self
.assertEqual(mstatus
& (MSTATUS_MIE | MSTATUS_MPRV |
195 def test_change_pc(self
):
196 """Change the PC right as we come out of reset."""
198 self
.gdb
.command("p *((int*) 0x%x)=0x13" % target
.ram
)
199 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 4))
200 self
.gdb
.command("p *((int*) 0x%x)=0x13" % (target
.ram
+ 8))
201 self
.gdb
.p("$pc=0x%x" % target
.ram
)
203 self
.assertEqual((target
.ram
+ 4), self
.gdb
.p("$pc"))
205 self
.assertEqual((target
.ram
+ 8), self
.gdb
.p("$pc"))
207 class DebugTest(DeleteServer
):
209 # Include malloc so that gdb can make function calls. I suspect this
210 # malloc will silently blow through the memory set aside for it, so be
212 self
.binary
= target
.compile("programs/debug.c", "programs/checksum.c",
213 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
214 self
.server
= target
.server()
215 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
219 def exit(self
, expected_result
= 0xc86455d4):
220 output
= self
.gdb
.c()
221 self
.assertIn("Breakpoint", output
)
222 self
.assertIn("_exit", output
)
223 self
.assertEqual(self
.gdb
.p("status"), expected_result
)
225 def test_function_call(self
):
226 self
.gdb
.b("main:start")
228 self
.assertEqual(self
.gdb
.p('fib(6)'), 8)
229 self
.assertEqual(self
.gdb
.p('fib(7)'), 13)
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
.b("main:start")
243 self
.gdb
.command("p i=0");
249 pc
= self
.gdb
.p("$pc")
250 self
.assertNotEqual(last_pc
, pc
)
251 if (last_pc
and pc
> last_pc
and pc
- last_pc
<= 4):
256 # Some basic sanity that we're not running between breakpoints or
258 self
.assertGreater(jumps
, 10)
259 self
.assertGreater(advances
, 50)
264 def test_symbols(self
):
267 output
= self
.gdb
.c()
268 self
.assertIn(", main ", output
)
269 output
= self
.gdb
.c()
270 self
.assertIn(", rot13 ", output
)
272 def test_breakpoint(self
):
274 # The breakpoint should be hit exactly 2 times.
276 output
= self
.gdb
.c()
278 self
.assertIn("Breakpoint ", output
)
279 #TODO self.assertIn("rot13 ", output)
282 def test_hwbp_1(self
):
283 if target
.instruction_hardware_breakpoint_count
< 1:
286 self
.gdb
.hbreak("rot13")
287 # The breakpoint should be hit exactly 2 times.
289 output
= self
.gdb
.c()
291 self
.assertIn("Breakpoint ", output
)
292 #TODO self.assertIn("rot13 ", output)
295 def test_hwbp_2(self
):
296 if target
.instruction_hardware_breakpoint_count
< 2:
299 self
.gdb
.hbreak("main")
300 self
.gdb
.hbreak("rot13")
301 # We should hit 3 breakpoints.
303 output
= self
.gdb
.c()
305 self
.assertIn("Breakpoint ", output
)
306 #TODO self.assertIn("rot13 ", output)
309 def test_too_many_hwbp(self
):
311 self
.gdb
.hbreak("*rot13 + %d" % (i
* 4))
313 output
= self
.gdb
.c()
314 self
.assertIn("Cannot insert hardware breakpoint", output
)
315 # Clean up, otherwise the hardware breakpoints stay set and future
317 self
.gdb
.command("D")
319 def test_registers(self
):
320 # Get to a point in the code where some registers have actually been
325 # Try both forms to test gdb.
326 for cmd
in ("info all-registers", "info registers all"):
327 output
= self
.gdb
.command(cmd
)
328 self
.assertNotIn("Could not", output
)
329 for reg
in ('zero', 'ra', 'sp', 'gp', 'tp'):
330 self
.assertIn(reg
, output
)
333 # mcpuid is one of the few registers that should have the high bit set
335 # Leave this commented out until gdb and spike agree on the encoding of
336 # mcpuid (which is going to be renamed to misa in any case).
337 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
340 # The instret register should always be changing.
343 # instret = self.gdb.p("$instret")
344 # self.assertNotEqual(instret, last_instret)
345 # last_instret = instret
350 def test_interrupt(self
):
351 """Sending gdb ^C while the program is running should cause it to halt."""
352 self
.gdb
.b("main:start")
355 self
.gdb
.c(wait
=False)
357 output
= self
.gdb
.interrupt()
358 #TODO: assert "main" in output
359 self
.assertGreater(self
.gdb
.p("j"), 10)
363 class StepTest(DeleteServer
):
365 self
.binary
= target
.compile("programs/step.S")
366 self
.server
= target
.server()
367 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
373 main
= self
.gdb
.p("$pc")
374 for expected
in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
376 pc
= self
.gdb
.p("$pc")
377 self
.assertEqual("%x" % pc
, "%x" % (expected
+ main
))
379 class RegsTest(DeleteServer
):
381 self
.binary
= target
.compile("programs/regs.S")
382 self
.server
= target
.server()
383 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
386 self
.gdb
.b("handle_trap")
389 def test_write_gprs(self
):
390 regs
= [("x%d" % n
) for n
in range(2, 32)]
392 self
.gdb
.p("$pc=write_regs")
393 for i
, r
in enumerate(regs
):
394 self
.gdb
.p("$%s=%d" % (r
, (0xdeadbeef<<i
)+17))
395 self
.gdb
.p("$x1=data")
396 self
.gdb
.command("b all_done")
397 output
= self
.gdb
.c()
398 self
.assertIn("Breakpoint ", output
)
400 # Just to get this data in the log.
401 self
.gdb
.command("x/30gx data")
402 self
.gdb
.command("info registers")
403 for n
in range(len(regs
)):
404 self
.assertEqual(self
.gdb
.x("data+%d" % (8*n
), 'g'),
405 ((0xdeadbeef<<n
)+17) & ((1<<target
.xlen
)-1))
407 def test_write_csrs(self
):
408 # As much a test of gdb as of the simulator.
409 self
.gdb
.p("$mscratch=0")
411 self
.assertEqual(self
.gdb
.p("$mscratch"), 0)
412 self
.gdb
.p("$mscratch=123")
414 self
.assertEqual(self
.gdb
.p("$mscratch"), 123)
416 self
.gdb
.command("p $pc=write_regs")
417 self
.gdb
.command("p $a0=data")
418 self
.gdb
.command("b all_done")
419 self
.gdb
.command("c")
421 self
.assertEqual(123, self
.gdb
.p("$mscratch"))
422 self
.assertEqual(123, self
.gdb
.p("$x1"))
423 self
.assertEqual(123, self
.gdb
.p("$csr832"))
425 class DownloadTest(DeleteServer
):
427 length
= min(2**20, target
.ram_size
- 2048)
428 download_c
= tempfile
.NamedTemporaryFile(prefix
="download_", suffix
=".c")
429 download_c
.write("#include <stdint.h>\n")
430 download_c
.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
431 download_c
.write("uint32_t length = %d;\n" % length
)
432 download_c
.write("uint8_t d[%d] = {\n" % length
)
434 for i
in range(length
/ 16):
435 download_c
.write(" /* 0x%04x */ " % (i
* 16));
437 value
= random
.randrange(1<<8)
438 download_c
.write("%d, " % value
)
439 self
.crc
= binascii
.crc32("%c" % value
, self
.crc
)
440 download_c
.write("\n");
441 download_c
.write("};\n");
442 download_c
.write("uint8_t *data = &d[0];\n");
443 download_c
.write("uint32_t main() { return crc32a(data, length); }\n")
449 self
.binary
= target
.compile(download_c
.name
, "programs/checksum.c")
450 self
.server
= target
.server()
451 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
453 def test_download(self
):
454 output
= self
.gdb
.load()
455 self
.gdb
.command("b _exit")
457 self
.assertEqual(self
.gdb
.p("status"), self
.crc
)
459 class MprvTest(DeleteServer
):
461 self
.binary
= target
.compile("programs/mprv.S")
462 self
.server
= target
.server()
463 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
467 """Test that the debugger can access memory when MPRV is set."""
468 self
.gdb
.c(wait
=False)
471 output
= self
.gdb
.command("p/x *(int*)(((char*)&data)-0x80000000)")
472 self
.assertIn("0xbead", output
)
474 class PrivTest(DeleteServer
):
476 self
.binary
= target
.compile("programs/priv.S")
477 self
.server
= target
.server()
478 self
.gdb
= gdb(target
, self
.server
.port
, self
.binary
)
481 misa
= self
.gdb
.p("$misa")
482 self
.supported
= set()
484 self
.supported
.add(0)
486 self
.supported
.add(1)
488 self
.supported
.add(2)
489 self
.supported
.add(3)
492 """Test reading/writing priv."""
493 for privilege
in range(4):
494 self
.gdb
.p("$priv=%d" % privilege
)
496 actual
= self
.gdb
.p("$priv")
497 self
.assertIn(actual
, self
.supported
)
498 if privilege
in self
.supported
:
499 self
.assertEqual(actual
, privilege
)
501 def test_change(self
):
502 """Test that the core's privilege level actually changes."""
504 if 0 not in self
.supported
:
505 # TODO: return not applicable
512 self
.gdb
.p("$priv=3")
513 main
= self
.gdb
.p("$pc")
515 self
.assertEqual("%x" % self
.gdb
.p("$pc"), "%x" % (main
+4))
518 self
.gdb
.p("$priv=0")
520 # Should have taken an exception, so be nowhere near main.
521 pc
= self
.gdb
.p("$pc")
522 self
.assertTrue(pc
< main
or pc
> main
+ 0x100)
524 class Target(object):
529 raise NotImplementedError
531 def compile(self
, *sources
):
532 binary_name
= "%s_%s-%d" % (
534 os
.path
.basename(os
.path
.splitext(sources
[0])[0]),
537 self
.temporary_binary
= tempfile
.NamedTemporaryFile(
538 prefix
=binary_name
+ "_")
539 binary_name
= self
.temporary_binary
.name
540 testlib
.compile(sources
+
541 ("programs/entry.S", "programs/init.c",
543 "-T", "targets/%s/link.lds" % (self
.directory
or self
.name
),
550 class SpikeTarget(Target
):
553 ram_size
= 5 * 1024 * 1024
554 instruction_hardware_breakpoint_count
= 0
555 reset_vector
= 0x1000
557 class Spike64Target(SpikeTarget
):
562 return testlib
.Spike(parsed
.cmd
, halted
=True)
564 class Spike32Target(SpikeTarget
):
569 return testlib
.Spike(parsed
.cmd
, halted
=True, xlen
=32)
571 class FreedomE300Target(Target
):
572 name
= "freedom-e300"
576 instruction_hardware_breakpoint_count
= 2
579 return testlib
.Openocd(cmd
=parsed
.cmd
,
580 config
="targets/%s/openocd.cfg" % self
.name
)
582 class FreedomE300SimTarget(Target
):
583 name
= "freedom-e300-sim"
587 ram_size
= 256 * 1024 * 1024
588 instruction_hardware_breakpoint_count
= 2
591 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
592 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
593 config
="targets/%s/openocd.cfg" % self
.name
,
598 class FreedomU500Target(Target
):
599 name
= "freedom-u500"
603 instruction_hardware_breakpoint_count
= 2
606 return testlib
.Openocd(cmd
=parsed
.cmd
,
607 config
="targets/%s/openocd.cfg" % self
.name
)
609 class FreedomU500SimTarget(Target
):
610 name
= "freedom-u500-sim"
614 ram_size
= 256 * 1024 * 1024
615 instruction_hardware_breakpoint_count
= 2
618 sim
= testlib
.VcsSim(simv
=parsed
.run
, debug
=False)
619 openocd
= testlib
.Openocd(cmd
=parsed
.cmd
,
620 config
="targets/%s/openocd.cfg" % self
.name
,
630 FreedomE300SimTarget
,
631 FreedomU500SimTarget
]
634 parser
= argparse
.ArgumentParser(
636 Example command line from the real world:
637 Run all RegsTest cases against a physical FPGA, with custom openocd command:
638 ./gdbserver.py --freedom-e-300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
640 group
= parser
.add_mutually_exclusive_group(required
=True)
642 group
.add_argument("--%s" % t
.name
, action
="store_const", const
=t
,
644 parser
.add_argument("--run",
645 help="The command to use to start the actual target (e.g. simulation)")
646 parser
.add_argument("--cmd",
647 help="The command to use to start the debug server.")
648 parser
.add_argument("--gdb",
649 help="The command to use to start gdb.")
651 xlen_group
= parser
.add_mutually_exclusive_group()
652 xlen_group
.add_argument("--32", action
="store_const", const
=32, dest
="xlen",
653 help="Force the target to be 32-bit.")
654 xlen_group
.add_argument("--64", action
="store_const", const
=64, dest
="xlen",
655 help="Force the target to be 64-bit.")
657 parser
.add_argument("--isolate", action
="store_true",
658 help="Try to run in such a way that multiple instances can run at "
659 "the same time. This may make it harder to debug a failure if it "
662 parser
.add_argument("unittest", nargs
="*")
664 parsed
= parser
.parse_args()
667 target
= parsed
.target()
670 target
.xlen
= parsed
.xlen
672 unittest
.main(argv
=[sys
.argv
[0]] + parsed
.unittest
)
674 # TROUBLESHOOTING TIPS
675 # If a particular test fails, run just that one test, eg.:
676 # ./gdbserver.py MprvTest.test_mprv
677 # Then inspect gdb.log and spike.log to see what happened in more detail.
679 if __name__
== '__main__':