Test step over invalid instruction.
[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 self.binary = target.compile("programs/debug.c", "programs/checksum.c")
161 self.server = target.server()
162 self.gdb = testlib.Gdb()
163 self.gdb.command("file %s" % self.binary)
164 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
165 self.gdb.load()
166 self.gdb.b("_exit")
167
168 def exit(self):
169 output = self.gdb.c()
170 self.assertIn("Breakpoint", output)
171 #TODO self.assertIn("_exit", output)
172 #TODO self.assertEqual(self.gdb.p("status"), 0xc86455d4)
173 # Use a0 until gdb can resolve "status"
174 self.assertEqual(self.gdb.p("$a0") & 0xffffffff, 0xc86455d4)
175
176 def test_turbostep(self):
177 """Single step a bunch of times."""
178 self.gdb.command("p i=0");
179 last_pc = None
180 advances = 0
181 jumps = 0
182 for _ in range(100):
183 self.gdb.stepi()
184 pc = self.gdb.p("$pc")
185 self.assertNotEqual(last_pc, pc)
186 if (last_pc and pc > last_pc and pc - last_pc <= 4):
187 advances += 1
188 else:
189 jumps += 1
190 last_pc = pc
191 # Some basic sanity that we're not running between breakpoints or
192 # something.
193 self.assertGreater(jumps, 10)
194 self.assertGreater(advances, 50)
195
196 def test_exit(self):
197 self.exit()
198
199 def test_symbols(self):
200 self.gdb.b("main")
201 self.gdb.b("rot13")
202 output = self.gdb.c()
203 self.assertIn(", main ", output)
204 output = self.gdb.c()
205 self.assertIn(", rot13 ", output)
206
207 def test_breakpoint(self):
208 self.gdb.b("rot13")
209 # The breakpoint should be hit exactly 2 times.
210 for i in range(2):
211 output = self.gdb.c()
212 self.gdb.p("$pc")
213 self.assertIn("Breakpoint ", output)
214 #TODO self.assertIn("rot13 ", output)
215 self.exit()
216
217 def test_hwbp_1(self):
218 self.gdb.hbreak("rot13")
219 # The breakpoint should be hit exactly 2 times.
220 for i in range(2):
221 output = self.gdb.c()
222 self.gdb.p("$pc")
223 self.assertIn("Breakpoint ", output)
224 #TODO self.assertIn("rot13 ", output)
225 self.exit()
226
227 def test_hwbp_2(self):
228 self.gdb.hbreak("main")
229 self.gdb.hbreak("rot13")
230 # We should hit 3 breakpoints.
231 for i in range(3):
232 output = self.gdb.c()
233 self.gdb.p("$pc")
234 self.assertIn("Breakpoint ", output)
235 #TODO self.assertIn("rot13 ", output)
236 self.exit()
237
238 def test_too_many_hwbp(self):
239 for i in range(30):
240 self.gdb.hbreak("*rot13 + %d" % (i * 4))
241
242 output = self.gdb.c()
243 self.assertIn("Cannot insert hardware breakpoint", output)
244 # Clean up, otherwise the hardware breakpoints stay set and future
245 # tests may fail.
246 self.gdb.command("D")
247
248 def test_registers(self):
249 # Get to a point in the code where some registers have actually been
250 # used.
251 self.gdb.b("rot13")
252 self.gdb.c()
253 self.gdb.c()
254 # Try both forms to test gdb.
255 for cmd in ("info all-registers", "info registers all"):
256 output = self.gdb.command(cmd)
257 self.assertNotIn("Could not", output)
258 for reg in ('zero', 'ra', 'sp', 'gp', 'tp'):
259 self.assertIn(reg, output)
260
261 #TODO
262 # mcpuid is one of the few registers that should have the high bit set
263 # (for rv64).
264 # Leave this commented out until gdb and spike agree on the encoding of
265 # mcpuid (which is going to be renamed to misa in any case).
266 #self.assertRegexpMatches(output, ".*mcpuid *0x80")
267
268 #TODO:
269 # The instret register should always be changing.
270 #last_instret = None
271 #for _ in range(5):
272 # instret = self.gdb.p("$instret")
273 # self.assertNotEqual(instret, last_instret)
274 # last_instret = instret
275 # self.gdb.stepi()
276
277 self.exit()
278
279 def test_interrupt(self):
280 """Sending gdb ^C while the program is running should cause it to halt."""
281 self.gdb.b("main:start")
282 self.gdb.c()
283 self.gdb.p("i=123");
284 self.gdb.c(wait=False)
285 time.sleep(0.1)
286 output = self.gdb.interrupt()
287 #TODO: assert "main" in output
288 self.assertGreater(self.gdb.p("j"), 10)
289 self.gdb.p("i=0");
290 self.exit()
291
292 class StepTest(DeleteServer):
293 def setUp(self):
294 self.binary = target.compile("programs/step.S")
295 self.server = target.server()
296 self.gdb = testlib.Gdb()
297 self.gdb.command("file %s" % self.binary)
298 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
299 self.gdb.load()
300 self.gdb.b("main")
301 self.gdb.c()
302
303 def test_step(self):
304 main = self.gdb.p("$pc")
305 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
306 self.gdb.stepi()
307 pc = self.gdb.p("$pc")
308 self.assertEqual("%x" % pc, "%x" % (expected + main))
309
310 class RegsTest(DeleteServer):
311 def setUp(self):
312 self.binary = target.compile("programs/regs.S")
313 self.server = target.server()
314 self.gdb = testlib.Gdb()
315 self.gdb.command("file %s" % self.binary)
316 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
317 self.gdb.load()
318 self.gdb.b("main")
319 self.gdb.b("handle_trap")
320 self.gdb.c()
321
322 def test_write_gprs(self):
323 regs = [("x%d" % n) for n in range(2, 32)]
324
325 self.gdb.p("$pc=write_regs")
326 for i, r in enumerate(regs):
327 self.gdb.command("p $%s=%d" % (r, (0xdeadbeef<<i)+17))
328 self.gdb.command("p $x1=data")
329 self.gdb.command("b all_done")
330 output = self.gdb.c()
331 self.assertIn("Breakpoint ", output)
332
333 # Just to get this data in the log.
334 self.gdb.command("x/30gx data")
335 self.gdb.command("info registers")
336 for n in range(len(regs)):
337 self.assertEqual(self.gdb.x("data+%d" % (8*n), 'g'),
338 ((0xdeadbeef<<n)+17) & ((1<<target.xlen)-1))
339
340 def test_write_csrs(self):
341 # As much a test of gdb as of the simulator.
342 self.gdb.p("$mscratch=0")
343 self.gdb.stepi()
344 self.assertEqual(self.gdb.p("$mscratch"), 0)
345 self.gdb.p("$mscratch=123")
346 self.gdb.stepi()
347 self.assertEqual(self.gdb.p("$mscratch"), 123)
348
349 self.gdb.command("p $pc=write_regs")
350 self.gdb.command("p $a0=data")
351 self.gdb.command("b all_done")
352 self.gdb.command("c")
353
354 self.assertEqual(123, self.gdb.p("$mscratch"))
355 self.assertEqual(123, self.gdb.p("$x1"))
356 self.assertEqual(123, self.gdb.p("$csr832"))
357
358 class DownloadTest(DeleteServer):
359 def setUp(self):
360 length = min(2**20, target.ram_size - 2048)
361 fd = file("download.c", "w")
362 fd.write("#include <stdint.h>\n")
363 fd.write("unsigned int crc32a(uint8_t *message, unsigned int size);\n")
364 fd.write("uint32_t length = %d;\n" % length)
365 fd.write("uint8_t d[%d] = {\n" % length)
366 self.crc = 0
367 for i in range(length / 16):
368 fd.write(" /* 0x%04x */ " % (i * 16));
369 for _ in range(16):
370 value = random.randrange(1<<8)
371 fd.write("%d, " % value)
372 self.crc = binascii.crc32("%c" % value, self.crc)
373 fd.write("\n");
374 fd.write("};\n");
375 fd.write("uint8_t *data = &d[0];\n");
376 fd.write("uint32_t main() { return crc32a(data, length); }\n")
377 fd.close()
378
379 if self.crc < 0:
380 self.crc += 2**32
381
382 self.binary = target.compile("download.c", "programs/checksum.c")
383 self.server = target.server()
384 self.gdb = testlib.Gdb()
385 self.gdb.command("file %s" % self.binary)
386 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
387
388 def test_download(self):
389 output = self.gdb.load()
390 self.gdb.command("b _exit")
391 self.gdb.c()
392 self.assertEqual(self.gdb.p("status"), self.crc)
393
394 class MprvTest(DeleteServer):
395 def setUp(self):
396 self.binary = target.compile("programs/mprv.S")
397 self.server = target.server()
398 self.gdb = testlib.Gdb()
399 self.gdb.command("file %s" % self.binary)
400 self.gdb.command("target extended-remote localhost:%d" % self.server.port)
401 self.gdb.load()
402
403 def test_mprv(self):
404 """Test that the debugger can access memory when MPRV is set."""
405 self.gdb.c(wait=False)
406 time.sleep(0.5)
407 self.gdb.interrupt()
408 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
409 self.assertIn("0xbead", output)
410
411 class Target(object):
412 directory = None
413
414 def server(self):
415 raise NotImplementedError
416
417 def compile(self, *sources):
418 return testlib.compile(sources +
419 ("programs/entry.S", "programs/init.c",
420 "-I", "../env",
421 "-T", "targets/%s/link.lds" % (self.directory or self.name),
422 "-nostartfiles",
423 "-mcmodel=medany"), xlen=self.xlen)
424
425 class Spike64Target(Target):
426 name = "spike"
427 xlen = 64
428 ram = 0x80010000
429 ram_size = 5 * 1024 * 1024
430
431 def server(self):
432 return testlib.Spike(parsed.cmd, halted=True)
433
434 class Spike32Target(Target):
435 name = "spike32"
436 directory = "spike"
437 xlen = 32
438 ram = 0x80010000
439 ram_size = 5 * 1024 * 1024
440
441 def server(self):
442 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
443
444 class MicroSemiTarget(Target):
445 name = "m2gl_m2s"
446 xlen = 32
447 ram = 0x80000000
448 ram_size = 16 * 1024
449
450 def server(self):
451 return testlib.Openocd(cmd=parsed.cmd,
452 config="targets/%s/openocd.cfg" % self.name)
453
454 targets = [
455 Spike32Target,
456 Spike64Target,
457 MicroSemiTarget
458 ]
459
460 def main():
461 parser = argparse.ArgumentParser(
462 epilog="""
463 Example command line from the real world:
464 Run all RegsTest cases against a MicroSemi m2gl_m2s board, with custom openocd command:
465 ./gdbserver.py --m2gl_m2s --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" -- -vf RegsTest
466 """)
467 group = parser.add_mutually_exclusive_group(required=True)
468 for t in targets:
469 group.add_argument("--%s" % t.name, action="store_const", const=t,
470 dest="target")
471 parser.add_argument("--cmd",
472 help="The command to use to start the debug server.")
473 parser.add_argument("unittest", nargs="*")
474 global parsed
475 parsed = parser.parse_args()
476
477 global target
478 target = parsed.target()
479 unittest.main(argv=[sys.argv[0]] + parsed.unittest)
480
481 # TROUBLESHOOTING TIPS
482 # If a particular test fails, run just that one test, eg.:
483 # ./tests/gdbserver.py MprvTest.test_mprv
484 # Then inspect gdb.log and spike.log to see what happened in more detail.
485
486 if __name__ == '__main__':
487 sys.exit(main())