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