Add --32 and --64 options to gdbserver.py.
[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 text = "Howdy, Earth!"
228 gdb_length = self.gdb.p('strlen("%s")' % text)
229 self.assertEqual(gdb_length, len(text))
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.command("p i=0");
242 last_pc = None
243 advances = 0
244 jumps = 0
245 for _ in range(100):
246 self.gdb.stepi()
247 pc = self.gdb.p("$pc")
248 self.assertNotEqual(last_pc, pc)
249 if (last_pc and pc > last_pc and pc - last_pc <= 4):
250 advances += 1
251 else:
252 jumps += 1
253 last_pc = pc
254 # Some basic sanity that we're not running between breakpoints or
255 # something.
256 self.assertGreater(jumps, 10)
257 self.assertGreater(advances, 50)
258
259 def test_exit(self):
260 self.exit()
261
262 def test_symbols(self):
263 self.gdb.b("main")
264 self.gdb.b("rot13")
265 output = self.gdb.c()
266 self.assertIn(", main ", output)
267 output = self.gdb.c()
268 self.assertIn(", rot13 ", output)
269
270 def test_breakpoint(self):
271 self.gdb.b("rot13")
272 # The breakpoint should be hit exactly 2 times.
273 for i in range(2):
274 output = self.gdb.c()
275 self.gdb.p("$pc")
276 self.assertIn("Breakpoint ", output)
277 #TODO self.assertIn("rot13 ", output)
278 self.exit()
279
280 def test_hwbp_1(self):
281 if target.instruction_hardware_breakpoint_count < 1:
282 return
283
284 self.gdb.hbreak("rot13")
285 # The breakpoint should be hit exactly 2 times.
286 for i in range(2):
287 output = self.gdb.c()
288 self.gdb.p("$pc")
289 self.assertIn("Breakpoint ", output)
290 #TODO self.assertIn("rot13 ", output)
291 self.exit()
292
293 def test_hwbp_2(self):
294 if target.instruction_hardware_breakpoint_count < 2:
295 return
296
297 self.gdb.hbreak("main")
298 self.gdb.hbreak("rot13")
299 # We should hit 3 breakpoints.
300 for i in range(3):
301 output = self.gdb.c()
302 self.gdb.p("$pc")
303 self.assertIn("Breakpoint ", output)
304 #TODO self.assertIn("rot13 ", output)
305 self.exit()
306
307 def test_too_many_hwbp(self):
308 for i in range(30):
309 self.gdb.hbreak("*rot13 + %d" % (i * 4))
310
311 output = self.gdb.c()
312 self.assertIn("Cannot insert hardware breakpoint", output)
313 # Clean up, otherwise the hardware breakpoints stay set and future
314 # tests may fail.
315 self.gdb.command("D")
316
317 def test_registers(self):
318 # Get to a point in the code where some registers have actually been
319 # used.
320 self.gdb.b("rot13")
321 self.gdb.c()
322 self.gdb.c()
323 # Try both forms to test gdb.
324 for cmd in ("info all-registers", "info registers all"):
325 output = self.gdb.command(cmd)
326 self.assertNotIn("Could not", output)
327 for reg in ('zero', 'ra', 'sp', 'gp', 'tp'):
328 self.assertIn(reg, output)
329
330 #TODO
331 # mcpuid is one of the few registers that should have the high bit set
332 # (for rv64).
333 # Leave this commented out until gdb and spike agree on the encoding of
334 # mcpuid (which is going to be renamed to misa in any case).
335 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
336
337 #TODO:
338 # The instret register should always be changing.
339 #last_instret = None
340 #for _ in range(5):
341 # instret = self.gdb.p("$instret")
342 # self.assertNotEqual(instret, last_instret)
343 # last_instret = instret
344 # self.gdb.stepi()
345
346 self.exit()
347
348 def test_interrupt(self):
349 """Sending gdb ^C while the program is running should cause it to halt."""
350 self.gdb.b("main:start")
351 self.gdb.c()
352 self.gdb.p("i=123");
353 self.gdb.c(wait=False)
354 time.sleep(0.1)
355 output = self.gdb.interrupt()
356 #TODO: assert "main" in output
357 self.assertGreater(self.gdb.p("j"), 10)
358 self.gdb.p("i=0");
359 self.exit()
360
361 class StepTest(DeleteServer):
362 def setUp(self):
363 self.binary = target.compile("programs/step.S")
364 self.server = target.server()
365 self.gdb = gdb(target, self.server.port, self.binary)
366 self.gdb.load()
367 self.gdb.b("main")
368 self.gdb.c()
369
370 def test_step(self):
371 main = self.gdb.p("$pc")
372 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
373 self.gdb.stepi()
374 pc = self.gdb.p("$pc")
375 self.assertEqual("%x" % pc, "%x" % (expected + main))
376
377 class RegsTest(DeleteServer):
378 def setUp(self):
379 self.binary = target.compile("programs/regs.S")
380 self.server = target.server()
381 self.gdb = gdb(target, self.server.port, self.binary)
382 self.gdb.load()
383 self.gdb.b("main")
384 self.gdb.b("handle_trap")
385 self.gdb.c()
386
387 def test_write_gprs(self):
388 regs = [("x%d" % n) for n in range(2, 32)]
389
390 self.gdb.p("$pc=write_regs")
391 for i, r in enumerate(regs):
392 self.gdb.p("$%s=%d" % (r, (0xdeadbeef<<i)+17))
393 self.gdb.p("$x1=data")
394 self.gdb.command("b all_done")
395 output = self.gdb.c()
396 self.assertIn("Breakpoint ", output)
397
398 # Just to get this data in the log.
399 self.gdb.command("x/30gx data")
400 self.gdb.command("info registers")
401 for n in range(len(regs)):
402 self.assertEqual(self.gdb.x("data+%d" % (8*n), 'g'),
403 ((0xdeadbeef<<n)+17) & ((1<<target.xlen)-1))
404
405 def test_write_csrs(self):
406 # As much a test of gdb as of the simulator.
407 self.gdb.p("$mscratch=0")
408 self.gdb.stepi()
409 self.assertEqual(self.gdb.p("$mscratch"), 0)
410 self.gdb.p("$mscratch=123")
411 self.gdb.stepi()
412 self.assertEqual(self.gdb.p("$mscratch"), 123)
413
414 self.gdb.command("p $pc=write_regs")
415 self.gdb.command("p $a0=data")
416 self.gdb.command("b all_done")
417 self.gdb.command("c")
418
419 self.assertEqual(123, self.gdb.p("$mscratch"))
420 self.assertEqual(123, self.gdb.p("$x1"))
421 self.assertEqual(123, self.gdb.p("$csr832"))
422
423 class DownloadTest(DeleteServer):
424 def setUp(self):
425 length = min(2**20, target.ram_size - 2048)
426 download_c = tempfile.NamedTemporaryFile(prefix="download_", suffix=".c")
427 download_c.write("#include <stdint.h>\n")
428 download_c.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
429 download_c.write("uint32_t length = %d;\n" % length)
430 download_c.write("uint8_t d[%d] = {\n" % length)
431 self.crc = 0
432 for i in range(length / 16):
433 download_c.write(" /* 0x%04x */ " % (i * 16));
434 for _ in range(16):
435 value = random.randrange(1<<8)
436 download_c.write("%d, " % value)
437 self.crc = binascii.crc32("%c" % value, self.crc)
438 download_c.write("\n");
439 download_c.write("};\n");
440 download_c.write("uint8_t *data = &d[0];\n");
441 download_c.write("uint32_t main() { return crc32a(data, length); }\n")
442 download_c.flush()
443
444 if self.crc < 0:
445 self.crc += 2**32
446
447 self.binary = target.compile(download_c.name, "programs/checksum.c")
448 self.server = target.server()
449 self.gdb = gdb(target, self.server.port, self.binary)
450
451 def test_download(self):
452 output = self.gdb.load()
453 self.gdb.command("b _exit")
454 self.gdb.c()
455 self.assertEqual(self.gdb.p("status"), self.crc)
456
457 class MprvTest(DeleteServer):
458 def setUp(self):
459 self.binary = target.compile("programs/mprv.S")
460 self.server = target.server()
461 self.gdb = gdb(target, self.server.port, self.binary)
462 self.gdb.load()
463
464 def test_mprv(self):
465 """Test that the debugger can access memory when MPRV is set."""
466 self.gdb.c(wait=False)
467 time.sleep(0.5)
468 self.gdb.interrupt()
469 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
470 self.assertIn("0xbead", output)
471
472 class PrivTest(DeleteServer):
473 def setUp(self):
474 self.binary = target.compile("programs/priv.S")
475 self.server = target.server()
476 self.gdb = gdb(target, self.server.port, self.binary)
477 self.gdb.load()
478
479 misa = self.gdb.p("$misa")
480 self.supported = set()
481 if misa & (1<<20):
482 self.supported.add(0)
483 if misa & (1<<18):
484 self.supported.add(1)
485 if misa & (1<<7):
486 self.supported.add(2)
487 self.supported.add(3)
488
489 def test_rw(self):
490 """Test reading/writing priv."""
491 for privilege in range(4):
492 self.gdb.p("$priv=%d" % privilege)
493 self.gdb.stepi()
494 actual = self.gdb.p("$priv")
495 self.assertIn(actual, self.supported)
496 if privilege in self.supported:
497 self.assertEqual(actual, privilege)
498
499 def test_change(self):
500 """Test that the core's privilege level actually changes."""
501
502 if 0 not in self.supported:
503 # TODO: return not applicable
504 return
505
506 self.gdb.b("main")
507 self.gdb.c()
508
509 # Machine mode
510 self.gdb.p("$priv=3")
511 main = self.gdb.p("$pc")
512 self.gdb.stepi()
513 self.assertEqual("%x" % self.gdb.p("$pc"), "%x" % (main+4))
514
515 # User mode
516 self.gdb.p("$priv=0")
517 self.gdb.stepi()
518 # Should have taken an exception, so be nowhere near main.
519 pc = self.gdb.p("$pc")
520 self.assertTrue(pc < main or pc > main + 0x100)
521
522 class Target(object):
523 directory = None
524 timeout_sec = 2
525
526 def server(self):
527 raise NotImplementedError
528
529 def compile(self, *sources):
530 binary_name = "%s_%s-%d" % (
531 self.name,
532 os.path.basename(os.path.splitext(sources[0])[0]),
533 self.xlen)
534 if parsed.isolate:
535 self.temporary_binary = tempfile.NamedTemporaryFile(
536 prefix=binary_name + "_")
537 binary_name = self.temporary_binary.name
538 testlib.compile(sources +
539 ("programs/entry.S", "programs/init.c",
540 "-I", "../env",
541 "-T", "targets/%s/link.lds" % (self.directory or self.name),
542 "-nostartfiles",
543 "-mcmodel=medany",
544 "-o", binary_name),
545 xlen=self.xlen)
546 return binary_name
547
548 class SpikeTarget(Target):
549 directory = "spike"
550 ram = 0x80010000
551 ram_size = 5 * 1024 * 1024
552 instruction_hardware_breakpoint_count = 0
553 reset_vector = 0x1000
554
555 class Spike64Target(SpikeTarget):
556 name = "spike64"
557 xlen = 64
558
559 def server(self):
560 return testlib.Spike(parsed.cmd, halted=True)
561
562 class Spike32Target(SpikeTarget):
563 name = "spike32"
564 xlen = 32
565
566 def server(self):
567 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
568
569 class FreedomE300Target(Target):
570 name = "freedom-e300"
571 xlen = 32
572 ram = 0x80000000
573 ram_size = 16 * 1024
574 instruction_hardware_breakpoint_count = 2
575
576 def server(self):
577 return testlib.Openocd(cmd=parsed.cmd,
578 config="targets/%s/openocd.cfg" % self.name)
579
580 class FreedomE300SimTarget(Target):
581 name = "freedom-e300-sim"
582 xlen = 32
583 timeout_sec = 240
584 ram = 0x80000000
585 ram_size = 256 * 1024 * 1024
586 instruction_hardware_breakpoint_count = 2
587
588 def server(self):
589 sim = testlib.VcsSim(simv=parsed.run, debug=False)
590 openocd = testlib.Openocd(cmd=parsed.cmd,
591 config="targets/%s/openocd.cfg" % self.name,
592 otherProcess = sim)
593 time.sleep(20)
594 return openocd
595
596 class FreedomU500Target(Target):
597 name = "freedom-u500"
598 xlen = 64
599 ram = 0x80000000
600 ram_size = 16 * 1024
601 instruction_hardware_breakpoint_count = 2
602
603 def server(self):
604 return testlib.Openocd(cmd=parsed.cmd,
605 config="targets/%s/openocd.cfg" % self.name)
606
607 class FreedomU500SimTarget(Target):
608 name = "freedom-u500-sim"
609 xlen = 64
610 timeout_sec = 240
611 ram = 0x80000000
612 ram_size = 256 * 1024 * 1024
613 instruction_hardware_breakpoint_count = 2
614
615 def server(self):
616 sim = testlib.VcsSim(simv=parsed.run, debug=False)
617 openocd = testlib.Openocd(cmd=parsed.cmd,
618 config="targets/%s/openocd.cfg" % self.name,
619 otherProcess = sim)
620 time.sleep(20)
621 return openocd
622
623 targets = [
624 Spike32Target,
625 Spike64Target,
626 FreedomE300Target,
627 FreedomU500Target,
628 FreedomE300SimTarget,
629 FreedomU500SimTarget]
630
631 def main():
632 parser = argparse.ArgumentParser(
633 epilog="""
634 Example command line from the real world:
635 Run all RegsTest cases against a physical FPGA, with custom openocd command:
636 ./gdbserver.py --freedom-e-300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
637 """)
638 group = parser.add_mutually_exclusive_group(required=True)
639 for t in targets:
640 group.add_argument("--%s" % t.name, action="store_const", const=t,
641 dest="target")
642 parser.add_argument("--run",
643 help="The command to use to start the actual target (e.g. simulation)")
644 parser.add_argument("--cmd",
645 help="The command to use to start the debug server.")
646 parser.add_argument("--gdb",
647 help="The command to use to start gdb.")
648
649 xlen_group = parser.add_mutually_exclusive_group()
650 xlen_group.add_argument("--32", action="store_const", const=32, dest="xlen",
651 help="Force the target to be 32-bit.")
652 xlen_group.add_argument("--64", action="store_const", const=64, dest="xlen",
653 help="Force the target to be 64-bit.")
654
655 parser.add_argument("--isolate", action="store_true",
656 help="Try to run in such a way that multiple instances can run at "
657 "the same time. This may make it harder to debug a failure if it "
658 "does occur.")
659
660 parser.add_argument("unittest", nargs="*")
661 global parsed
662 parsed = parser.parse_args()
663
664 global target
665 target = parsed.target()
666
667 if parsed.xlen:
668 target.xlen = parsed.xlen
669
670 unittest.main(argv=[sys.argv[0]] + parsed.unittest)
671
672 # TROUBLESHOOTING TIPS
673 # If a particular test fails, run just that one test, eg.:
674 # ./gdbserver.py MprvTest.test_mprv
675 # Then inspect gdb.log and spike.log to see what happened in more detail.
676
677 if __name__ == '__main__':
678 sys.exit(main())