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