267bcdc6bd0b6aaade07dfd71ea7a7b7842d4ead
[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
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
33
34 def gdb(
35 target=None,
36 port=None,
37 binary=None
38 ):
39
40 gdb = None
41 if parsed.gdb:
42 gdb = testlib.Gdb(parsed.gdb)
43 else:
44 gdb = testlib.Gdb()
45
46 if binary:
47 gdb.command("file %s" % binary)
48 if target:
49 gdb.command("set arch riscv:rv%d" % target.xlen)
50 gdb.command("set remotetimeout %d" % target.timeout_sec)
51 if port:
52 gdb.command("target extended-remote localhost:%d" % port)
53
54 return gdb
55
56
57 def ihex_line(address, record_type, data):
58 assert len(data) < 128
59 line = ":%02X%04X%02X" % (len(data), address, record_type)
60 check = len(data)
61 check += address % 256
62 check += address >> 8
63 check += record_type
64 for char in data:
65 value = ord(char)
66 check += value
67 line += "%02X" % value
68 line += "%02X\n" % ((256-check)%256)
69 return line
70
71 def ihex_parse(line):
72 assert line.startswith(":")
73 line = line[1:]
74 data_len = int(line[:2], 16)
75 address = int(line[2:6], 16)
76 record_type = int(line[6:8], 16)
77 data = ""
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
81
82 def readable_binary_string(s):
83 return "".join("%02x" % ord(c) for c in s)
84
85 class DeleteServer(unittest.TestCase):
86 def tearDown(self):
87 del self.server
88
89 class SimpleRegisterTest(DeleteServer):
90 def setUp(self):
91 self.server = target.server()
92 self.gdb = gdb(target, self.server.port)
93
94 # 0x13 is nop
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)
99
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))
104 self.gdb.stepi()
105 self.assertEqual(self.gdb.p("$%s" % name), a)
106 self.gdb.p("$%s=0x%x" % (name, b))
107 self.gdb.stepi()
108 self.assertEqual(self.gdb.p("$%s" % name), b)
109
110 def test_s0(self):
111 # S0 is saved/restored in DSCRATCH
112 self.check_reg("s0")
113
114 def test_s1(self):
115 # S1 is saved/restored in Debug RAM
116 self.check_reg("s1")
117
118 def test_t0(self):
119 # T0 is not saved/restored at all
120 self.check_reg("t2")
121
122 def test_t2(self):
123 # T2 is not saved/restored at all
124 self.check_reg("t2")
125
126 class SimpleMemoryTest(DeleteServer):
127 def setUp(self):
128 self.server = target.server()
129 self.gdb = gdb(target, self.server.port)
130
131 def access_test(self, size, data_type):
132 self.assertEqual(self.gdb.p("sizeof(%s)" % data_type),
133 size)
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)
140
141 def test_8(self):
142 self.access_test(1, 'char')
143
144 def test_16(self):
145 self.access_test(2, 'short')
146
147 def test_32(self):
148 self.access_test(4, 'int')
149
150 def test_64(self):
151 self.access_test(8, 'long long')
152
153 def test_block(self):
154 length = 1024
155 line_length = 16
156 a = tempfile.NamedTemporaryFile(suffix=".ihex")
157 data = ""
158 for i in range(length / line_length):
159 line_data = "".join(["%c" % random.randrange(256) for _ in range(line_length)])
160 data += line_data
161 a.write(ihex_line(i * line_length, 0, line_data))
162 a.flush()
163
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)
172
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))
176 for line in b:
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)]))
181
182 class InstantHaltTest(DeleteServer):
183 def setUp(self):
184 self.server = target.server()
185 self.gdb = gdb(target, self.server.port)
186
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 |
192 MSTATUS_VM), 0)
193
194 def test_change_pc(self):
195 """Change the PC right as we come out of reset."""
196 # 0x13 is nop
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)
201 self.gdb.stepi()
202 self.assertEqual((target.ram + 4), self.gdb.p("$pc"))
203 self.gdb.stepi()
204 self.assertEqual((target.ram + 8), self.gdb.p("$pc"))
205
206 class DebugTest(DeleteServer):
207 def setUp(self):
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
210 # careful.
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)
215 self.gdb.load()
216 self.gdb.b("_exit")
217
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)
223
224 def test_function_call(self):
225 self.gdb.b("main:start")
226 self.gdb.c()
227 self.assertEqual(self.gdb.p('fib(6)'), 8)
228 self.assertEqual(self.gdb.p('fib(7)'), 13)
229 self.exit()
230
231 def test_change_string(self):
232 text = "This little piggy went to the market."
233 self.gdb.b("main:start")
234 self.gdb.c()
235 self.gdb.p('fox = "%s"' % text)
236 self.exit(0x43b497b8)
237
238 def test_turbostep(self):
239 """Single step a bunch of times."""
240 self.gdb.b("main:start")
241 self.gdb.c()
242 self.gdb.command("p i=0");
243 last_pc = None
244 advances = 0
245 jumps = 0
246 for _ in range(100):
247 self.gdb.stepi()
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):
251 advances += 1
252 else:
253 jumps += 1
254 last_pc = pc
255 # Some basic sanity that we're not running between breakpoints or
256 # something.
257 self.assertGreater(jumps, 10)
258 self.assertGreater(advances, 50)
259
260 def test_exit(self):
261 self.exit()
262
263 def test_symbols(self):
264 self.gdb.b("main")
265 self.gdb.b("rot13")
266 output = self.gdb.c()
267 self.assertIn(", main ", output)
268 output = self.gdb.c()
269 self.assertIn(", rot13 ", output)
270
271 def test_breakpoint(self):
272 self.gdb.b("rot13")
273 # The breakpoint should be hit exactly 2 times.
274 for i in range(2):
275 output = self.gdb.c()
276 self.gdb.p("$pc")
277 self.assertIn("Breakpoint ", output)
278 #TODO self.assertIn("rot13 ", output)
279 self.exit()
280
281 def test_hwbp_1(self):
282 if target.instruction_hardware_breakpoint_count < 1:
283 return
284
285 self.gdb.hbreak("rot13")
286 # The breakpoint should be hit exactly 2 times.
287 for i in range(2):
288 output = self.gdb.c()
289 self.gdb.p("$pc")
290 self.assertIn("Breakpoint ", output)
291 #TODO self.assertIn("rot13 ", output)
292 self.exit()
293
294 def test_hwbp_2(self):
295 if target.instruction_hardware_breakpoint_count < 2:
296 return
297
298 self.gdb.hbreak("main")
299 self.gdb.hbreak("rot13")
300 # We should hit 3 breakpoints.
301 for i in range(3):
302 output = self.gdb.c()
303 self.gdb.p("$pc")
304 self.assertIn("Breakpoint ", output)
305 #TODO self.assertIn("rot13 ", output)
306 self.exit()
307
308 def test_too_many_hwbp(self):
309 for i in range(30):
310 self.gdb.hbreak("*rot13 + %d" % (i * 4))
311
312 output = self.gdb.c()
313 self.assertIn("Cannot insert hardware breakpoint", output)
314 # Clean up, otherwise the hardware breakpoints stay set and future
315 # tests may fail.
316 self.gdb.command("D")
317
318 def test_registers(self):
319 # Get to a point in the code where some registers have actually been
320 # used.
321 self.gdb.b("rot13")
322 self.gdb.c()
323 self.gdb.c()
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)
330
331 #TODO
332 # mcpuid is one of the few registers that should have the high bit set
333 # (for rv64).
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")
337
338 #TODO:
339 # The instret register should always be changing.
340 #last_instret = None
341 #for _ in range(5):
342 # instret = self.gdb.p("$instret")
343 # self.assertNotEqual(instret, last_instret)
344 # last_instret = instret
345 # self.gdb.stepi()
346
347 self.exit()
348
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")
352 self.gdb.c()
353 self.gdb.p("i=123");
354 self.gdb.c(wait=False)
355 time.sleep(0.1)
356 output = self.gdb.interrupt()
357 #TODO: assert "main" in output
358 self.assertGreater(self.gdb.p("j"), 10)
359 self.gdb.p("i=0");
360 self.exit()
361
362 class StepTest(DeleteServer):
363 def setUp(self):
364 self.binary = target.compile("programs/step.S")
365 self.server = target.server()
366 self.gdb = gdb(target, self.server.port, self.binary)
367 self.gdb.load()
368 self.gdb.b("main")
369 self.gdb.c()
370
371 def test_step(self):
372 main = self.gdb.p("$pc")
373 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
374 self.gdb.stepi()
375 pc = self.gdb.p("$pc")
376 self.assertEqual("%x" % pc, "%x" % (expected + main))
377
378 class RegsTest(DeleteServer):
379 def setUp(self):
380 self.binary = target.compile("programs/regs.S")
381 self.server = target.server()
382 self.gdb = gdb(target, self.server.port, self.binary)
383 self.gdb.load()
384 self.gdb.b("main")
385 self.gdb.b("handle_trap")
386 self.gdb.c()
387
388 def test_write_gprs(self):
389 regs = [("x%d" % n) for n in range(2, 32)]
390
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)
398
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))
405
406 def test_write_csrs(self):
407 # As much a test of gdb as of the simulator.
408 self.gdb.p("$mscratch=0")
409 self.gdb.stepi()
410 self.assertEqual(self.gdb.p("$mscratch"), 0)
411 self.gdb.p("$mscratch=123")
412 self.gdb.stepi()
413 self.assertEqual(self.gdb.p("$mscratch"), 123)
414
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")
419
420 self.assertEqual(123, self.gdb.p("$mscratch"))
421 self.assertEqual(123, self.gdb.p("$x1"))
422 self.assertEqual(123, self.gdb.p("$csr832"))
423
424 class DownloadTest(DeleteServer):
425 def setUp(self):
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)
432 self.crc = 0
433 for i in range(length / 16):
434 download_c.write(" /* 0x%04x */ " % (i * 16));
435 for _ in range(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")
443 download_c.flush()
444
445 if self.crc < 0:
446 self.crc += 2**32
447
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)
451
452 def test_download(self):
453 output = self.gdb.load()
454 self.gdb.command("b _exit")
455 self.gdb.c()
456 self.assertEqual(self.gdb.p("status"), self.crc)
457
458 class MprvTest(DeleteServer):
459 def setUp(self):
460 self.binary = target.compile("programs/mprv.S")
461 self.server = target.server()
462 self.gdb = gdb(target, self.server.port, self.binary)
463 self.gdb.load()
464
465 def test_mprv(self):
466 """Test that the debugger can access memory when MPRV is set."""
467 self.gdb.c(wait=False)
468 time.sleep(0.5)
469 self.gdb.interrupt()
470 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
471 self.assertIn("0xbead", output)
472
473 class PrivTest(DeleteServer):
474 def setUp(self):
475 self.binary = target.compile("programs/priv.S")
476 self.server = target.server()
477 self.gdb = gdb(target, self.server.port, self.binary)
478 self.gdb.load()
479
480 misa = self.gdb.p("$misa")
481 self.supported = set()
482 if misa & (1<<20):
483 self.supported.add(0)
484 if misa & (1<<18):
485 self.supported.add(1)
486 if misa & (1<<7):
487 self.supported.add(2)
488 self.supported.add(3)
489
490 def test_rw(self):
491 """Test reading/writing priv."""
492 for privilege in range(4):
493 self.gdb.p("$priv=%d" % privilege)
494 self.gdb.stepi()
495 actual = self.gdb.p("$priv")
496 self.assertIn(actual, self.supported)
497 if privilege in self.supported:
498 self.assertEqual(actual, privilege)
499
500 def test_change(self):
501 """Test that the core's privilege level actually changes."""
502
503 if 0 not in self.supported:
504 # TODO: return not applicable
505 return
506
507 self.gdb.b("main")
508 self.gdb.c()
509
510 # Machine mode
511 self.gdb.p("$priv=3")
512 main = self.gdb.p("$pc")
513 self.gdb.stepi()
514 self.assertEqual("%x" % self.gdb.p("$pc"), "%x" % (main+4))
515
516 # User mode
517 self.gdb.p("$priv=0")
518 self.gdb.stepi()
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)
522
523 class Target(object):
524 directory = None
525 timeout_sec = 2
526
527 def server(self):
528 raise NotImplementedError
529
530 def compile(self, *sources):
531 binary_name = "%s_%s-%d" % (
532 self.name,
533 os.path.basename(os.path.splitext(sources[0])[0]),
534 self.xlen)
535 if parsed.isolate:
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",
541 "-I", "../env",
542 "-T", "targets/%s/link.lds" % (self.directory or self.name),
543 "-nostartfiles",
544 "-mcmodel=medany",
545 "-o", binary_name),
546 xlen=self.xlen)
547 return binary_name
548
549 class SpikeTarget(Target):
550 directory = "spike"
551 ram = 0x80010000
552 ram_size = 5 * 1024 * 1024
553 instruction_hardware_breakpoint_count = 0
554 reset_vector = 0x1000
555
556 class Spike64Target(SpikeTarget):
557 name = "spike64"
558 xlen = 64
559
560 def server(self):
561 return testlib.Spike(parsed.cmd, halted=True)
562
563 class Spike32Target(SpikeTarget):
564 name = "spike32"
565 xlen = 32
566
567 def server(self):
568 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
569
570 class FreedomE300Target(Target):
571 name = "freedom-e300"
572 xlen = 32
573 ram = 0x80000000
574 ram_size = 16 * 1024
575 instruction_hardware_breakpoint_count = 2
576
577 def server(self):
578 return testlib.Openocd(cmd=parsed.cmd,
579 config="targets/%s/openocd.cfg" % self.name)
580
581 class FreedomE300SimTarget(Target):
582 name = "freedom-e300-sim"
583 xlen = 32
584 timeout_sec = 240
585 ram = 0x80000000
586 ram_size = 256 * 1024 * 1024
587 instruction_hardware_breakpoint_count = 2
588
589 def server(self):
590 sim = testlib.VcsSim(simv=parsed.run, debug=False)
591 openocd = testlib.Openocd(cmd=parsed.cmd,
592 config="targets/%s/openocd.cfg" % self.name,
593 otherProcess = sim)
594 time.sleep(20)
595 return openocd
596
597 class FreedomU500Target(Target):
598 name = "freedom-u500"
599 xlen = 64
600 ram = 0x80000000
601 ram_size = 16 * 1024
602 instruction_hardware_breakpoint_count = 2
603
604 def server(self):
605 return testlib.Openocd(cmd=parsed.cmd,
606 config="targets/%s/openocd.cfg" % self.name)
607
608 class FreedomU500SimTarget(Target):
609 name = "freedom-u500-sim"
610 xlen = 64
611 timeout_sec = 240
612 ram = 0x80000000
613 ram_size = 256 * 1024 * 1024
614 instruction_hardware_breakpoint_count = 2
615
616 def server(self):
617 sim = testlib.VcsSim(simv=parsed.run, debug=False)
618 openocd = testlib.Openocd(cmd=parsed.cmd,
619 config="targets/%s/openocd.cfg" % self.name,
620 otherProcess = sim)
621 time.sleep(20)
622 return openocd
623
624 targets = [
625 Spike32Target,
626 Spike64Target,
627 FreedomE300Target,
628 FreedomU500Target,
629 FreedomE300SimTarget,
630 FreedomU500SimTarget]
631
632 def main():
633 parser = argparse.ArgumentParser(
634 epilog="""
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
638 """)
639 group = parser.add_mutually_exclusive_group(required=True)
640 for t in targets:
641 group.add_argument("--%s" % t.name, action="store_const", const=t,
642 dest="target")
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.")
649
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.")
655
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 "
659 "does occur.")
660
661 parser.add_argument("unittest", nargs="*")
662 global parsed
663 parsed = parser.parse_args()
664
665 global target
666 target = parsed.target()
667
668 if parsed.xlen:
669 target.xlen = parsed.xlen
670
671 unittest.main(argv=[sys.argv[0]] + parsed.unittest)
672
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.
677
678 if __name__ == '__main__':
679 sys.exit(main())