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