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