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