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