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