f20630e65e7d591e9dd6a9b4226825454224911f
[riscv-tests.git] / debug / gdbserver.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import argparse
6 import testlib
7 import unittest
8 import tempfile
9 import time
10 import random
11 import binascii
12
13 MSTATUS_UIE = 0x00000001
14 MSTATUS_SIE = 0x00000002
15 MSTATUS_HIE = 0x00000004
16 MSTATUS_MIE = 0x00000008
17 MSTATUS_UPIE = 0x00000010
18 MSTATUS_SPIE = 0x00000020
19 MSTATUS_HPIE = 0x00000040
20 MSTATUS_MPIE = 0x00000080
21 MSTATUS_SPP = 0x00000100
22 MSTATUS_HPP = 0x00000600
23 MSTATUS_MPP = 0x00001800
24 MSTATUS_FS = 0x00006000
25 MSTATUS_XS = 0x00018000
26 MSTATUS_MPRV = 0x00020000
27 MSTATUS_PUM = 0x00040000
28 MSTATUS_MXR = 0x00080000
29 MSTATUS_VM = 0x1F000000
30 MSTATUS32_SD = 0x80000000
31 MSTATUS64_SD = 0x8000000000000000
32
33 def gdb():
34 if parsed.gdb:
35 return testlib.Gdb(parsed.gdb)
36 else:
37 return testlib.Gdb()
38
39 def ihex_line(address, record_type, data):
40 assert len(data) < 128
41 line = ":%02X%04X%02X" % (len(data), address, record_type)
42 check = len(data)
43 check += address % 256
44 check += address >> 8
45 check += record_type
46 for char in data:
47 value = ord(char)
48 check += value
49 line += "%02X" % value
50 line += "%02X\n" % ((256-check)%256)
51 return line
52
53 def ihex_parse(line):
54 assert line.startswith(":")
55 line = line[1:]
56 data_len = int(line[:2], 16)
57 address = int(line[2:6], 16)
58 record_type = int(line[6:8], 16)
59 data = ""
60 for i in range(data_len):
61 data += "%c" % int(line[8+2*i:10+2*i], 16)
62 return record_type, address, data
63
64 class DeleteServer(unittest.TestCase):
65 def tearDown(self):
66 del self.server
67
68 class SimpleRegisterTest(DeleteServer):
69 def setUp(self):
70 self.server = target.server()
71 self.gdb = gdb()
72 # For now gdb has to be told what the architecture is when it's not
73 # given an ELF file.
74 self.gdb.command("set arch riscv:rv%d" % target.xlen)
75
76 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
77
78 # 0x13 is nop
79 self.gdb.command("p *((int*) 0x%x)=0x13" % target.ram)
80 self.gdb.command("p *((int*) 0x%x)=0x13" % (target.ram + 4))
81 self.gdb.command("p *((int*) 0x%x)=0x13" % (target.ram + 8))
82 self.gdb.p("$pc=0x%x" % target.ram)
83
84 def check_reg(self, name):
85 a = random.randrange(1<<target.xlen)
86 b = random.randrange(1<<target.xlen)
87 self.gdb.p("$%s=0x%x" % (name, a))
88 self.gdb.stepi()
89 self.assertEqual(self.gdb.p("$%s" % name), a)
90 self.gdb.p("$%s=0x%x" % (name, b))
91 self.gdb.stepi()
92 self.assertEqual(self.gdb.p("$%s" % name), b)
93
94 def test_s0(self):
95 # S0 is saved/restored in DSCRATCH
96 self.check_reg("s0")
97
98 def test_s1(self):
99 # S1 is saved/restored in Debug RAM
100 self.check_reg("s1")
101
102 def test_t0(self):
103 # T0 is not saved/restored at all
104 self.check_reg("t2")
105
106 def test_t2(self):
107 # T2 is not saved/restored at all
108 self.check_reg("t2")
109
110 class SimpleMemoryTest(DeleteServer):
111 def setUp(self):
112 self.server = target.server()
113 self.gdb = gdb()
114 self.gdb.command("set arch riscv:rv%d" % target.xlen)
115 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
116
117 def access_test(self, size, data_type):
118 self.assertEqual(self.gdb.p("sizeof(%s)" % data_type),
119 size)
120 a = 0x86753095555aaaa & ((1<<(size*8))-1)
121 b = 0xdeadbeef12345678 & ((1<<(size*8))-1)
122 self.gdb.p("*((%s*)0x%x) = 0x%x" % (data_type, target.ram, a))
123 self.gdb.p("*((%s*)0x%x) = 0x%x" % (data_type, target.ram + size, b))
124 self.assertEqual(self.gdb.p("*((%s*)0x%x)" % (data_type, target.ram)), a)
125 self.assertEqual(self.gdb.p("*((%s*)0x%x)" % (data_type, target.ram + size)), b)
126
127 def test_8(self):
128 self.access_test(1, 'char')
129
130 def test_16(self):
131 self.access_test(2, 'short')
132
133 def test_32(self):
134 self.access_test(4, 'int')
135
136 def test_64(self):
137 self.access_test(8, 'long long')
138
139 def test_block(self):
140 length = 1024
141 line_length = 16
142 a = tempfile.NamedTemporaryFile(suffix=".ihex")
143 data = ""
144 for i in range(length / line_length):
145 line_data = "".join(["%c" % random.randrange(256) for _ in range(line_length)])
146 data += line_data
147 a.write(ihex_line(i * line_length, 0, line_data))
148 a.flush()
149
150 self.gdb.command("restore %s 0x%x" % (a.name, target.ram))
151 for offset in range(0, length, 19*4) + [length-4]:
152 value = self.gdb.p("*((int*)0x%x)" % (target.ram + offset))
153 written = ord(data[offset]) | \
154 (ord(data[offset+1]) << 8) | \
155 (ord(data[offset+2]) << 16) | \
156 (ord(data[offset+3]) << 24)
157 self.assertEqual(value, written)
158
159 b = tempfile.NamedTemporaryFile(suffix=".ihex")
160 self.gdb.command("dump ihex memory %s 0x%x 0x%x" % (b.name, target.ram,
161 target.ram + length))
162 for line in b:
163 record_type, address, line_data = ihex_parse(line)
164 if (record_type == 0):
165 self.assertEqual(line_data, data[address:address+len(line_data)])
166
167 class InstantHaltTest(DeleteServer):
168 def setUp(self):
169 self.server = target.server()
170 self.gdb = gdb()
171 self.gdb.command("set arch riscv:rv%d" % target.xlen)
172 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
173
174 def test_instant_halt(self):
175 self.assertEqual(target.reset_vector, self.gdb.p("$pc"))
176 # mcycle and minstret have no defined reset value.
177 mstatus = self.gdb.p("$mstatus")
178 self.assertEqual(mstatus & (MSTATUS_MIE | MSTATUS_MPRV |
179 MSTATUS_VM), 0)
180
181 def test_change_pc(self):
182 """Change the PC right as we come out of reset."""
183 # 0x13 is nop
184 self.gdb.command("p *((int*) 0x%x)=0x13" % target.ram)
185 self.gdb.command("p *((int*) 0x%x)=0x13" % (target.ram + 4))
186 self.gdb.command("p *((int*) 0x%x)=0x13" % (target.ram + 8))
187 self.gdb.p("$pc=0x%x" % target.ram)
188 self.gdb.stepi()
189 self.assertEqual((target.ram + 4), self.gdb.p("$pc"))
190 self.gdb.stepi()
191 self.assertEqual((target.ram + 8), self.gdb.p("$pc"))
192
193 class DebugTest(DeleteServer):
194 def setUp(self):
195 # Include malloc so that gdb can make function calls. I suspect this
196 # malloc will silently blow through the memory set aside for it, so be
197 # careful.
198 self.binary = target.compile("programs/debug.c", "programs/checksum.c",
199 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
200 self.server = target.server()
201 self.gdb = gdb()
202 self.gdb.command("file %s" % self.binary)
203 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
204 self.gdb.load()
205 self.gdb.b("_exit")
206
207 def exit(self, expected_result = 0xc86455d4):
208 output = self.gdb.c()
209 self.assertIn("Breakpoint", output)
210 self.assertIn("_exit", output)
211 self.assertEqual(self.gdb.p("status"), expected_result)
212
213 def test_function_call(self):
214 self.gdb.b("main:start")
215 self.gdb.c()
216 text = "Howdy, Earth!"
217 gdb_length = self.gdb.p('strlen("%s")' % text)
218 self.assertEqual(gdb_length, len(text))
219 self.exit()
220
221 def test_change_string(self):
222 text = "This little piggy went to the market."
223 self.gdb.b("main:start")
224 self.gdb.c()
225 self.gdb.p('fox = "%s"' % text)
226 self.exit(0x43b497b8)
227
228 def test_turbostep(self):
229 """Single step a bunch of times."""
230 self.gdb.command("p i=0");
231 last_pc = None
232 advances = 0
233 jumps = 0
234 for _ in range(100):
235 self.gdb.stepi()
236 pc = self.gdb.p("$pc")
237 self.assertNotEqual(last_pc, pc)
238 if (last_pc and pc > last_pc and pc - last_pc <= 4):
239 advances += 1
240 else:
241 jumps += 1
242 last_pc = pc
243 # Some basic sanity that we're not running between breakpoints or
244 # something.
245 self.assertGreater(jumps, 10)
246 self.assertGreater(advances, 50)
247
248 def test_exit(self):
249 self.exit()
250
251 def test_symbols(self):
252 self.gdb.b("main")
253 self.gdb.b("rot13")
254 output = self.gdb.c()
255 self.assertIn(", main ", output)
256 output = self.gdb.c()
257 self.assertIn(", rot13 ", output)
258
259 def test_breakpoint(self):
260 self.gdb.b("rot13")
261 # The breakpoint should be hit exactly 2 times.
262 for i in range(2):
263 output = self.gdb.c()
264 self.gdb.p("$pc")
265 self.assertIn("Breakpoint ", output)
266 #TODO self.assertIn("rot13 ", output)
267 self.exit()
268
269 def test_hwbp_1(self):
270 if target.instruction_hardware_breakpoint_count < 1:
271 return
272
273 self.gdb.hbreak("rot13")
274 # The breakpoint should be hit exactly 2 times.
275 for i in range(2):
276 output = self.gdb.c()
277 self.gdb.p("$pc")
278 self.assertIn("Breakpoint ", output)
279 #TODO self.assertIn("rot13 ", output)
280 self.exit()
281
282 def test_hwbp_2(self):
283 if target.instruction_hardware_breakpoint_count < 2:
284 return
285
286 self.gdb.hbreak("main")
287 self.gdb.hbreak("rot13")
288 # We should hit 3 breakpoints.
289 for i in range(3):
290 output = self.gdb.c()
291 self.gdb.p("$pc")
292 self.assertIn("Breakpoint ", output)
293 #TODO self.assertIn("rot13 ", output)
294 self.exit()
295
296 def test_too_many_hwbp(self):
297 for i in range(30):
298 self.gdb.hbreak("*rot13 + %d" % (i * 4))
299
300 output = self.gdb.c()
301 self.assertIn("Cannot insert hardware breakpoint", output)
302 # Clean up, otherwise the hardware breakpoints stay set and future
303 # tests may fail.
304 self.gdb.command("D")
305
306 def test_registers(self):
307 # Get to a point in the code where some registers have actually been
308 # used.
309 self.gdb.b("rot13")
310 self.gdb.c()
311 self.gdb.c()
312 # Try both forms to test gdb.
313 for cmd in ("info all-registers", "info registers all"):
314 output = self.gdb.command(cmd)
315 self.assertNotIn("Could not", output)
316 for reg in ('zero', 'ra', 'sp', 'gp', 'tp'):
317 self.assertIn(reg, output)
318
319 #TODO
320 # mcpuid is one of the few registers that should have the high bit set
321 # (for rv64).
322 # Leave this commented out until gdb and spike agree on the encoding of
323 # mcpuid (which is going to be renamed to misa in any case).
324 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
325
326 #TODO:
327 # The instret register should always be changing.
328 #last_instret = None
329 #for _ in range(5):
330 # instret = self.gdb.p("$instret")
331 # self.assertNotEqual(instret, last_instret)
332 # last_instret = instret
333 # self.gdb.stepi()
334
335 self.exit()
336
337 def test_interrupt(self):
338 """Sending gdb ^C while the program is running should cause it to halt."""
339 self.gdb.b("main:start")
340 self.gdb.c()
341 self.gdb.p("i=123");
342 self.gdb.c(wait=False)
343 time.sleep(0.1)
344 output = self.gdb.interrupt()
345 #TODO: assert "main" in output
346 self.assertGreater(self.gdb.p("j"), 10)
347 self.gdb.p("i=0");
348 self.exit()
349
350 class StepTest(DeleteServer):
351 def setUp(self):
352 self.binary = target.compile("programs/step.S")
353 self.server = target.server()
354 self.gdb = gdb()
355 self.gdb.command("file %s" % self.binary)
356 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
357 self.gdb.load()
358 self.gdb.b("main")
359 self.gdb.c()
360
361 def test_step(self):
362 main = self.gdb.p("$pc")
363 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
364 self.gdb.stepi()
365 pc = self.gdb.p("$pc")
366 self.assertEqual("%x" % pc, "%x" % (expected + main))
367
368 class RegsTest(DeleteServer):
369 def setUp(self):
370 self.binary = target.compile("programs/regs.S")
371 self.server = target.server()
372 self.gdb = gdb()
373 self.gdb.command("file %s" % self.binary)
374 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
375 self.gdb.load()
376 self.gdb.b("main")
377 self.gdb.b("handle_trap")
378 self.gdb.c()
379
380 def test_write_gprs(self):
381 regs = [("x%d" % n) for n in range(2, 32)]
382
383 self.gdb.p("$pc=write_regs")
384 for i, r in enumerate(regs):
385 self.gdb.command("p $%s=%d" % (r, (0xdeadbeef<<i)+17))
386 self.gdb.command("p $x1=data")
387 self.gdb.command("b all_done")
388 output = self.gdb.c()
389 self.assertIn("Breakpoint ", output)
390
391 # Just to get this data in the log.
392 self.gdb.command("x/30gx data")
393 self.gdb.command("info registers")
394 for n in range(len(regs)):
395 self.assertEqual(self.gdb.x("data+%d" % (8*n), 'g'),
396 ((0xdeadbeef<<n)+17) & ((1<<target.xlen)-1))
397
398 def test_write_csrs(self):
399 # As much a test of gdb as of the simulator.
400 self.gdb.p("$mscratch=0")
401 self.gdb.stepi()
402 self.assertEqual(self.gdb.p("$mscratch"), 0)
403 self.gdb.p("$mscratch=123")
404 self.gdb.stepi()
405 self.assertEqual(self.gdb.p("$mscratch"), 123)
406
407 self.gdb.command("p $pc=write_regs")
408 self.gdb.command("p $a0=data")
409 self.gdb.command("b all_done")
410 self.gdb.command("c")
411
412 self.assertEqual(123, self.gdb.p("$mscratch"))
413 self.assertEqual(123, self.gdb.p("$x1"))
414 self.assertEqual(123, self.gdb.p("$csr832"))
415
416 class DownloadTest(DeleteServer):
417 def setUp(self):
418 length = min(2**20, target.ram_size - 2048)
419 download_c = tempfile.NamedTemporaryFile(prefix="download_", suffix=".c")
420 download_c.write("#include <stdint.h>\n")
421 download_c.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
422 download_c.write("uint32_t length = %d;\n" % length)
423 download_c.write("uint8_t d[%d] = {\n" % length)
424 self.crc = 0
425 for i in range(length / 16):
426 download_c.write(" /* 0x%04x */ " % (i * 16));
427 for _ in range(16):
428 value = random.randrange(1<<8)
429 download_c.write("%d, " % value)
430 self.crc = binascii.crc32("%c" % value, self.crc)
431 download_c.write("\n");
432 download_c.write("};\n");
433 download_c.write("uint8_t *data = &d[0];\n");
434 download_c.write("uint32_t main() { return crc32a(data, length); }\n")
435 download_c.flush()
436
437 if self.crc < 0:
438 self.crc += 2**32
439
440 self.binary = target.compile(download_c.name, "programs/checksum.c")
441 self.server = target.server()
442 self.gdb = gdb()
443 self.gdb.command("file %s" % self.binary)
444 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
445
446 def test_download(self):
447 output = self.gdb.load()
448 self.gdb.command("b _exit")
449 self.gdb.c()
450 self.assertEqual(self.gdb.p("status"), self.crc)
451
452 class MprvTest(DeleteServer):
453 def setUp(self):
454 self.binary = target.compile("programs/mprv.S")
455 self.server = target.server()
456 self.gdb = gdb()
457 self.gdb.command("file %s" % self.binary)
458 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
459 self.gdb.load()
460
461 def test_mprv(self):
462 """Test that the debugger can access memory when MPRV is set."""
463 self.gdb.c(wait=False)
464 time.sleep(0.5)
465 self.gdb.interrupt()
466 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
467 self.assertIn("0xbead", output)
468
469 class PrivTest(DeleteServer):
470 def setUp(self):
471 self.binary = target.compile("programs/priv.S")
472 self.server = target.server()
473 self.gdb = gdb()
474 self.gdb.command("file %s" % self.binary)
475 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
476 self.gdb.load()
477
478 misa = self.gdb.p("$misa")
479 self.supported = set()
480 if misa & (1<<20):
481 self.supported.add(0)
482 if misa & (1<<18):
483 self.supported.add(1)
484 if misa & (1<<7):
485 self.supported.add(2)
486 self.supported.add(3)
487
488 def test_rw(self):
489 """Test reading/writing priv."""
490 for privilege in range(4):
491 self.gdb.p("$priv=%d" % privilege)
492 self.gdb.stepi()
493 actual = self.gdb.p("$priv")
494 self.assertIn(actual, self.supported)
495 if privilege in self.supported:
496 self.assertEqual(actual, privilege)
497
498 def test_change(self):
499 """Test that the core's privilege level actually changes."""
500
501 if 0 not in self.supported:
502 # TODO: return not applicable
503 return
504
505 self.gdb.b("main")
506 self.gdb.c()
507
508 # Machine mode
509 self.gdb.p("$priv=3")
510 main = self.gdb.p("$pc")
511 self.gdb.stepi()
512 self.assertEqual("%x" % self.gdb.p("$pc"), "%x" % (main+4))
513
514 # User mode
515 self.gdb.p("$priv=0")
516 self.gdb.stepi()
517 # Should have taken an exception, so be nowhere near main.
518 pc = self.gdb.p("$pc")
519 self.assertTrue(pc < main or pc > main + 0x100)
520
521 class Target(object):
522 directory = None
523
524 def server(self):
525 raise NotImplementedError
526
527 def compile(self, *sources):
528 binary_name = "%s_%s" % (
529 self.name,
530 os.path.basename(os.path.splitext(sources[0])[0]))
531 if parsed.isolate:
532 self.temporary_binary = tempfile.NamedTemporaryFile(
533 prefix=binary_name + "_")
534 binary_name = self.temporary_binary.name
535 testlib.compile(sources +
536 ("programs/entry.S", "programs/init.c",
537 "-I", "../env",
538 "-T", "targets/%s/link.lds" % (self.directory or self.name),
539 "-nostartfiles",
540 "-mcmodel=medany",
541 "-o", binary_name),
542 xlen=self.xlen)
543 return binary_name
544
545 class SpikeTarget(Target):
546 directory = "spike"
547 ram = 0x80010000
548 ram_size = 5 * 1024 * 1024
549 instruction_hardware_breakpoint_count = 0
550 reset_vector = 0x1000
551
552 class Spike64Target(SpikeTarget):
553 name = "spike64"
554 xlen = 64
555
556 def server(self):
557 return testlib.Spike(parsed.cmd, halted=True)
558
559 class Spike32Target(SpikeTarget):
560 name = "spike32"
561 xlen = 32
562
563 def server(self):
564 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
565
566 class FreedomE300Target(Target):
567 name = "freedom-e300"
568 xlen = 32
569 ram = 0x80000000
570 ram_size = 16 * 1024
571 instruction_hardware_breakpoint_count = 2
572
573 def server(self):
574 return testlib.Openocd(cmd=parsed.cmd,
575 config="targets/%s/openocd.cfg" % self.name)
576
577 targets = [
578 Spike32Target,
579 Spike64Target,
580 FreedomE300Target
581 ]
582
583 def main():
584 parser = argparse.ArgumentParser(
585 epilog="""
586 Example command line from the real world:
587 Run all RegsTest cases against a MicroSemi m2gl_m2s board, with custom openocd command:
588 ./gdbserver.py --m2gl_m2s --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
589 """)
590 group = parser.add_mutually_exclusive_group(required=True)
591 for t in targets:
592 group.add_argument("--%s" % t.name, action="store_const", const=t,
593 dest="target")
594 parser.add_argument("--cmd",
595 help="The command to use to start the debug server.")
596 parser.add_argument("--gdb",
597 help="The command to use to start gdb.")
598 parser.add_argument("--isolate", action="store_true",
599 help="Try to run in such a way that multiple instances can run at "
600 "the same time. This may make it harder to debug a failure if it "
601 "does occur.")
602 parser.add_argument("unittest", nargs="*")
603 global parsed
604 parsed = parser.parse_args()
605
606 global target
607 target = parsed.target()
608 unittest.main(argv=[sys.argv[0]] + parsed.unittest)
609
610 # TROUBLESHOOTING TIPS
611 # If a particular test fails, run just that one test, eg.:
612 # ./tests/gdbserver.py MprvTest.test_mprv
613 # Then inspect gdb.log and spike.log to see what happened in more detail.
614
615 if __name__ == '__main__':
616 sys.exit(main())