318428daba3407d70038c95fa6e2255a6479a0b4
[riscv-tests.git] / debug / gdbserver.py
1 #!/usr/bin/env python
2
3 import argparse
4 import binascii
5 import os
6 import random
7 import re
8 import sys
9 import tempfile
10 import time
11 import traceback
12
13 import testlib
14
15 MSTATUS_UIE = 0x00000001
16 MSTATUS_SIE = 0x00000002
17 MSTATUS_HIE = 0x00000004
18 MSTATUS_MIE = 0x00000008
19 MSTATUS_UPIE = 0x00000010
20 MSTATUS_SPIE = 0x00000020
21 MSTATUS_HPIE = 0x00000040
22 MSTATUS_MPIE = 0x00000080
23 MSTATUS_SPP = 0x00000100
24 MSTATUS_HPP = 0x00000600
25 MSTATUS_MPP = 0x00001800
26 MSTATUS_FS = 0x00006000
27 MSTATUS_XS = 0x00018000
28 MSTATUS_MPRV = 0x00020000
29 MSTATUS_PUM = 0x00040000
30 MSTATUS_MXR = 0x00080000
31 MSTATUS_VM = 0x1F000000
32 MSTATUS32_SD = 0x80000000
33 MSTATUS64_SD = 0x8000000000000000
34
35 # pylint: disable=abstract-method
36
37 def gdb(
38 target=None,
39 port=None,
40 binary=None
41 ):
42
43 g = None
44 if parsed.gdb:
45 g = testlib.Gdb(parsed.gdb)
46 else:
47 g = testlib.Gdb()
48
49 if binary:
50 g.command("file %s" % binary)
51 if target:
52 g.command("set arch riscv:rv%d" % target.xlen)
53 g.command("set remotetimeout %d" % target.timeout_sec)
54 if port:
55 g.command("target extended-remote localhost:%d" % port)
56
57 g.p("$priv=3")
58
59 return g
60
61 def ihex_line(address, record_type, data):
62 assert len(data) < 128
63 line = ":%02X%04X%02X" % (len(data), address, record_type)
64 check = len(data)
65 check += address % 256
66 check += address >> 8
67 check += record_type
68 for char in data:
69 value = ord(char)
70 check += value
71 line += "%02X" % value
72 line += "%02X\n" % ((256-check)%256)
73 return line
74
75 def ihex_parse(line):
76 assert line.startswith(":")
77 line = line[1:]
78 data_len = int(line[:2], 16)
79 address = int(line[2:6], 16)
80 record_type = int(line[6:8], 16)
81 data = ""
82 for i in range(data_len):
83 data += "%c" % int(line[8+2*i:10+2*i], 16)
84 return record_type, address, data
85
86 def readable_binary_string(s):
87 return "".join("%02x" % ord(c) for c in s)
88
89 def header(title):
90 dashes = '-' * (36 - len(title))
91 before = dashes[:len(dashes)/2]
92 after = dashes[len(dashes)/2:]
93 print "%s[ %s ]%s" % (before, title, after)
94
95 class GdbTest(object):
96 compiled = {}
97
98 def __init__(self, target):
99 self.target = target
100 self.server = None
101 self.binary = None
102 self.gdb = None
103
104 def setUp(self):
105 pass
106
107 def run(self):
108 """
109 If compile_args is set, compile a program and set self.binary.
110
111 Call setUp().
112
113 Then call test() and return the result, displaying relevant information
114 if an exception is raised.
115 """
116 self.server = self.target.server()
117
118 print "Running", type(self).__name__, "...",
119 sys.stdout.flush()
120
121 start = time.time()
122
123 compile_args = getattr(self, 'compile_args', None)
124 if compile_args:
125 if compile_args not in GdbTest.compiled:
126 try:
127 # pylint: disable=star-args
128 GdbTest.compiled[compile_args] = \
129 self.target.compile(*compile_args)
130 except Exception: # pylint: disable=broad-except
131 print "exception while compiling in %.2fs" % (
132 time.time() - start)
133 print "=" * 40
134 header("Traceback")
135 traceback.print_exc(file=sys.stdout)
136 print "/" * 40
137 return "exception"
138 self.binary = GdbTest.compiled.get(compile_args)
139
140 self.gdb = gdb(self.target, self.server.port, self.binary)
141
142 try:
143 self.setUp()
144 result = self.test() # pylint: disable=no-member
145 except Exception as e: # pylint: disable=broad-except
146 if isinstance(e, TestFailed):
147 result = "fail"
148 else:
149 result = "exception"
150 print "%s in %.2fs" % (result, time.time() - start)
151 print "=" * 40
152 if isinstance(e, TestFailed):
153 header("Message")
154 print e.message
155 header("Traceback")
156 traceback.print_exc(file=sys.stdout)
157 header("gdb.log")
158 print open("gdb.log", "r").read()
159 header(self.server.logname)
160 print open(self.server.logname, "r").read()
161 print "/" * 40
162 return result
163
164 finally:
165 del self.server
166 del self.gdb
167
168 if not result:
169 result = 'pass'
170 print "%s in %.2fs" % (result, time.time() - start)
171 return result
172
173 class TestFailed(Exception):
174 def __init__(self, message):
175 Exception.__init__(self)
176 self.message = message
177
178 def run_all_tests(target, tests, fail_fast):
179 good_results = set(('pass', 'not_applicable'))
180
181 results = {}
182 module = sys.modules[__name__]
183 for name in dir(module):
184 definition = getattr(module, name)
185 if type(definition) == type and hasattr(definition, 'test') and \
186 (not tests or any(test in name for test in tests)):
187 instance = definition(target)
188 result = instance.run()
189 results.setdefault(result, []).append(name)
190 if result not in good_results and fail_fast:
191 break
192
193 print ":" * 40
194
195 result = 0
196 for key, value in results.iteritems():
197 print "%d tests returned %s" % (len(value), key)
198 if key not in good_results:
199 result = 1
200 for test in value:
201 print " ", test
202
203 return result
204
205 def assertEqual(a, b):
206 if a != b:
207 raise TestFailed("%r != %r" % (a, b))
208
209 def assertNotEqual(a, b):
210 if a == b:
211 raise TestFailed("%r == %r" % (a, b))
212
213 def assertIn(a, b):
214 if a not in b:
215 raise TestFailed("%r not in %r" % (a, b))
216
217 def assertNotIn(a, b):
218 if a in b:
219 raise TestFailed("%r in %r" % (a, b))
220
221 def assertGreater(a, b):
222 if not a > b:
223 raise TestFailed("%r not greater than %r" % (a, b))
224
225 def assertTrue(a):
226 if not a:
227 raise TestFailed("%r is not True" % a)
228
229 def assertRegexpMatches(text, regexp):
230 if not re.search(regexp, text):
231 raise TestFailed("can't find %r in %r" % (regexp, text))
232
233 class SimpleRegisterTest(GdbTest):
234 def check_reg(self, name):
235 a = random.randrange(1<<self.target.xlen)
236 b = random.randrange(1<<self.target.xlen)
237 self.gdb.p("$%s=0x%x" % (name, a))
238 self.gdb.stepi()
239 assertEqual(self.gdb.p("$%s" % name), a)
240 self.gdb.p("$%s=0x%x" % (name, b))
241 self.gdb.stepi()
242 assertEqual(self.gdb.p("$%s" % name), b)
243
244 def setUp(self):
245 # 0x13 is nop
246 self.gdb.command("p *((int*) 0x%x)=0x13" % self.target.ram)
247 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 4))
248 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 8))
249 self.gdb.p("$pc=0x%x" % self.target.ram)
250
251 class SimpleS0Test(SimpleRegisterTest):
252 def test(self):
253 self.check_reg("s0")
254
255 class SimpleS1Test(SimpleRegisterTest):
256 def test(self):
257 self.check_reg("s1")
258
259 class SimpleT0Test(SimpleRegisterTest):
260 def test(self):
261 self.check_reg("t0")
262
263 class SimpleT1Test(SimpleRegisterTest):
264 def test(self):
265 self.check_reg("t1")
266
267 class SimpleMemoryTest(GdbTest):
268 def access_test(self, size, data_type):
269 assertEqual(self.gdb.p("sizeof(%s)" % data_type), size)
270 a = 0x86753095555aaaa & ((1<<(size*8))-1)
271 b = 0xdeadbeef12345678 & ((1<<(size*8))-1)
272 self.gdb.p("*((%s*)0x%x) = 0x%x" % (data_type, self.target.ram, a))
273 self.gdb.p("*((%s*)0x%x) = 0x%x" % (data_type, self.target.ram + size,
274 b))
275 assertEqual(self.gdb.p("*((%s*)0x%x)" % (data_type, self.target.ram)),
276 a)
277 assertEqual(self.gdb.p("*((%s*)0x%x)" % (
278 data_type, self.target.ram + size)), b)
279
280 class MemTest8(SimpleMemoryTest):
281 def test(self):
282 self.access_test(1, 'char')
283
284 class MemTest16(SimpleMemoryTest):
285 def test(self):
286 self.access_test(2, 'short')
287
288 class MemTest32(SimpleMemoryTest):
289 def test(self):
290 self.access_test(4, 'int')
291
292 class MemTest64(SimpleMemoryTest):
293 def test(self):
294 self.access_test(8, 'long long')
295
296 class MemTestReadInvalid(SimpleMemoryTest):
297 def test(self):
298 # This test relies on 'gdb_report_data_abort enable' being executed in
299 # the openocd.cfg file.
300 try:
301 self.gdb.p("*((int*)0xdeadbeef)")
302 assert False, "Read should have failed."
303 except testlib.CannotAccess as e:
304 assertEqual(e.address, 0xdeadbeef)
305 self.gdb.p("*((int*)0x%x)" % self.target.ram)
306
307 class MemTestWriteInvalid(SimpleMemoryTest):
308 def test(self):
309 # This test relies on 'gdb_report_data_abort enable' being executed in
310 # the openocd.cfg file.
311 try:
312 self.gdb.p("*((int*)0xdeadbeef)=8675309")
313 assert False, "Write should have failed."
314 except testlib.CannotAccess as e:
315 assertEqual(e.address, 0xdeadbeef)
316 self.gdb.p("*((int*)0x%x)=6874742" % self.target.ram)
317
318 class MemTestBlock(GdbTest):
319 def test(self):
320 length = 1024
321 line_length = 16
322 a = tempfile.NamedTemporaryFile(suffix=".ihex")
323 data = ""
324 for i in range(length / line_length):
325 line_data = "".join(["%c" % random.randrange(256)
326 for _ in range(line_length)])
327 data += line_data
328 a.write(ihex_line(i * line_length, 0, line_data))
329 a.flush()
330
331 self.gdb.command("restore %s 0x%x" % (a.name, self.target.ram))
332 for offset in range(0, length, 19*4) + [length-4]:
333 value = self.gdb.p("*((int*)0x%x)" % (self.target.ram + offset))
334 written = ord(data[offset]) | \
335 (ord(data[offset+1]) << 8) | \
336 (ord(data[offset+2]) << 16) | \
337 (ord(data[offset+3]) << 24)
338 assertEqual(value, written)
339
340 b = tempfile.NamedTemporaryFile(suffix=".ihex")
341 self.gdb.command("dump ihex memory %s 0x%x 0x%x" % (b.name,
342 self.target.ram, self.target.ram + length))
343 for line in b:
344 record_type, address, line_data = ihex_parse(line)
345 if record_type == 0:
346 assertEqual(readable_binary_string(line_data),
347 readable_binary_string(
348 data[address:address+len(line_data)]))
349
350 class InstantHaltTest(GdbTest):
351 def test(self):
352 assertEqual(self.target.reset_vector, self.gdb.p("$pc"))
353 # mcycle and minstret have no defined reset value.
354 mstatus = self.gdb.p("$mstatus")
355 assertEqual(mstatus & (MSTATUS_MIE | MSTATUS_MPRV |
356 MSTATUS_VM), 0)
357
358 class InstantChangePc(GdbTest):
359 def test(self):
360 """Change the PC right as we come out of reset."""
361 # 0x13 is nop
362 self.gdb.command("p *((int*) 0x%x)=0x13" % self.target.ram)
363 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 4))
364 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 8))
365 self.gdb.p("$pc=0x%x" % self.target.ram)
366 self.gdb.stepi()
367 assertEqual((self.target.ram + 4), self.gdb.p("$pc"))
368 self.gdb.stepi()
369 assertEqual((self.target.ram + 8), self.gdb.p("$pc"))
370
371 class DebugTest(GdbTest):
372 # Include malloc so that gdb can make function calls. I suspect this malloc
373 # will silently blow through the memory set aside for it, so be careful.
374 compile_args = ("programs/debug.c", "programs/checksum.c",
375 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
376
377 def setUp(self):
378 self.gdb.load()
379 self.gdb.b("_exit")
380
381 def exit(self, expected_result=0xc86455d4):
382 output = self.gdb.c()
383 assertIn("Breakpoint", output)
384 assertIn("_exit", output)
385 assertEqual(self.gdb.p("status"), expected_result)
386
387 class DebugFunctionCall(DebugTest):
388 def test(self):
389 self.gdb.b("main:start")
390 self.gdb.c()
391 assertEqual(self.gdb.p('fib(6)'), 8)
392 assertEqual(self.gdb.p('fib(7)'), 13)
393 self.exit()
394
395 class DebugChangeString(DebugTest):
396 def test(self):
397 text = "This little piggy went to the market."
398 self.gdb.b("main:start")
399 self.gdb.c()
400 self.gdb.p('fox = "%s"' % text)
401 self.exit(0x43b497b8)
402
403 class DebugTurbostep(DebugTest):
404 def test(self):
405 """Single step a bunch of times."""
406 self.gdb.b("main:start")
407 self.gdb.c()
408 self.gdb.command("p i=0")
409 last_pc = None
410 advances = 0
411 jumps = 0
412 for _ in range(100):
413 self.gdb.stepi()
414 pc = self.gdb.p("$pc")
415 assertNotEqual(last_pc, pc)
416 if last_pc and pc > last_pc and pc - last_pc <= 4:
417 advances += 1
418 else:
419 jumps += 1
420 last_pc = pc
421 # Some basic sanity that we're not running between breakpoints or
422 # something.
423 assertGreater(jumps, 10)
424 assertGreater(advances, 50)
425
426 class DebugExit(DebugTest):
427 def test(self):
428 self.exit()
429
430 class DebugSymbols(DebugTest):
431 def test(self):
432 self.gdb.b("main")
433 self.gdb.b("rot13")
434 output = self.gdb.c()
435 assertIn(", main ", output)
436 output = self.gdb.c()
437 assertIn(", rot13 ", output)
438
439 class DebugBreakpoint(DebugTest):
440 def test(self):
441 self.gdb.b("rot13")
442 # The breakpoint should be hit exactly 2 times.
443 for _ in range(2):
444 output = self.gdb.c()
445 self.gdb.p("$pc")
446 assertIn("Breakpoint ", output)
447 assertIn("rot13 ", output)
448 self.exit()
449
450 class Hwbp1(DebugTest):
451 def test(self):
452 if self.target.instruction_hardware_breakpoint_count < 1:
453 return 'not_applicable'
454
455 self.gdb.hbreak("rot13")
456 # The breakpoint should be hit exactly 2 times.
457 for _ in range(2):
458 output = self.gdb.c()
459 self.gdb.p("$pc")
460 assertRegexpMatches(output, r"[bB]reakpoint")
461 assertIn("rot13 ", output)
462 self.exit()
463
464 class Hwbp2(DebugTest):
465 def test(self):
466 if self.target.instruction_hardware_breakpoint_count < 2:
467 return 'not_applicable'
468
469 self.gdb.hbreak("main")
470 self.gdb.hbreak("rot13")
471 # We should hit 3 breakpoints.
472 for expected in ("main", "rot13", "rot13"):
473 output = self.gdb.c()
474 self.gdb.p("$pc")
475 assertRegexpMatches(output, r"[bB]reakpoint")
476 assertIn("%s " % expected, output)
477 self.exit()
478
479 class TooManyHwbp(DebugTest):
480 def run(self):
481 for i in range(30):
482 self.gdb.hbreak("*rot13 + %d" % (i * 4))
483
484 output = self.gdb.c()
485 assertIn("Cannot insert hardware breakpoint", output)
486 # Clean up, otherwise the hardware breakpoints stay set and future
487 # tests may fail.
488 self.gdb.command("D")
489
490 class Registers(DebugTest):
491 def test(self):
492 # Get to a point in the code where some registers have actually been
493 # used.
494 self.gdb.b("rot13")
495 self.gdb.c()
496 self.gdb.c()
497 # Try both forms to test gdb.
498 for cmd in ("info all-registers", "info registers all"):
499 output = self.gdb.command(cmd)
500 assertNotIn("Could not", output)
501 for reg in ('zero', 'ra', 'sp', 'gp', 'tp'):
502 assertIn(reg, output)
503
504 #TODO
505 # mcpuid is one of the few registers that should have the high bit set
506 # (for rv64).
507 # Leave this commented out until gdb and spike agree on the encoding of
508 # mcpuid (which is going to be renamed to misa in any case).
509 #assertRegexpMatches(output, ".*mcpuid *0x80")
510
511 #TODO:
512 # The instret register should always be changing.
513 #last_instret = None
514 #for _ in range(5):
515 # instret = self.gdb.p("$instret")
516 # assertNotEqual(instret, last_instret)
517 # last_instret = instret
518 # self.gdb.stepi()
519
520 self.exit()
521
522 class UserInterrupt(DebugTest):
523 def test(self):
524 """Sending gdb ^C while the program is running should cause it to
525 halt."""
526 self.gdb.b("main:start")
527 self.gdb.c()
528 self.gdb.p("i=123")
529 self.gdb.c(wait=False)
530 time.sleep(0.1)
531 output = self.gdb.interrupt()
532 assert "main" in output
533 assertGreater(self.gdb.p("j"), 10)
534 self.gdb.p("i=0")
535 self.exit()
536
537 class StepTest(GdbTest):
538 compile_args = ("programs/step.S", )
539
540 def setUp(self):
541 self.gdb.load()
542 self.gdb.b("main")
543 self.gdb.c()
544
545 def test(self):
546 main_address = self.gdb.p("$pc")
547 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
548 self.gdb.stepi()
549 pc = self.gdb.p("$pc")
550 assertEqual("%x" % pc, "%x" % (expected + main_address))
551
552 class TriggerTest(GdbTest):
553 compile_args = ("programs/trigger.S", )
554 def setUp(self):
555 self.gdb.load()
556 self.gdb.b("_exit")
557 self.gdb.b("main")
558 self.gdb.c()
559
560 def exit(self):
561 output = self.gdb.c()
562 assertIn("Breakpoint", output)
563 assertIn("_exit", output)
564
565 class TriggerExecuteInstant(TriggerTest):
566 """Test an execute breakpoint on the first instruction executed out of
567 debug mode."""
568 def test(self):
569 main_address = self.gdb.p("$pc")
570 self.gdb.command("hbreak *0x%x" % (main_address + 4))
571 self.gdb.c()
572 assertEqual(self.gdb.p("$pc"), main_address+4)
573
574 class TriggerLoadAddress(TriggerTest):
575 def test(self):
576 self.gdb.command("rwatch *((&data)+1)")
577 output = self.gdb.c()
578 assertIn("read_loop", output)
579 assertEqual(self.gdb.p("$a0"),
580 self.gdb.p("(&data)+1"))
581 self.exit()
582
583 class TriggerLoadAddressInstant(TriggerTest):
584 """Test a load address breakpoint on the first instruction executed out of
585 debug mode."""
586 def test(self):
587 self.gdb.command("b just_before_read_loop")
588 self.gdb.c()
589 read_loop = self.gdb.p("&read_loop")
590 self.gdb.command("rwatch data")
591 self.gdb.c()
592 # Accept hitting the breakpoint before or after the load instruction.
593 assertIn(self.gdb.p("$pc"), [read_loop, read_loop + 4])
594 assertEqual(self.gdb.p("$a0"), self.gdb.p("&data"))
595
596 class TriggerStoreAddress(TriggerTest):
597 def test(self):
598 self.gdb.command("watch *((&data)+3)")
599 output = self.gdb.c()
600 assertIn("write_loop", output)
601 assertEqual(self.gdb.p("$a0"),
602 self.gdb.p("(&data)+3"))
603 self.exit()
604
605 class TriggerStoreAddressInstant(TriggerTest):
606 def test(self):
607 """Test a store address breakpoint on the first instruction executed out
608 of debug mode."""
609 self.gdb.command("b just_before_write_loop")
610 self.gdb.c()
611 write_loop = self.gdb.p("&write_loop")
612 self.gdb.command("watch data")
613 self.gdb.c()
614 # Accept hitting the breakpoint before or after the store instruction.
615 assertIn(self.gdb.p("$pc"), [write_loop, write_loop + 4])
616 assertEqual(self.gdb.p("$a0"), self.gdb.p("&data"))
617
618 class TriggerDmode(TriggerTest):
619 def check_triggers(self, tdata1_lsbs, tdata2):
620 dmode = 1 << (self.target.xlen-5)
621
622 triggers = []
623
624 if self.target.xlen == 32:
625 xlen_type = 'int'
626 elif self.target.xlen == 64:
627 xlen_type = 'long long'
628 else:
629 raise NotImplementedError
630
631 dmode_count = 0
632 i = 0
633 for i in range(16):
634 tdata1 = self.gdb.p("((%s *)&data)[%d]" % (xlen_type, 2*i))
635 if tdata1 == 0:
636 break
637 tdata2 = self.gdb.p("((%s *)&data)[%d]" % (xlen_type, 2*i+1))
638
639 if tdata1 & dmode:
640 dmode_count += 1
641 else:
642 assertEqual(tdata1 & 0xffff, tdata1_lsbs)
643 assertEqual(tdata2, tdata2)
644
645 assertGreater(i, 1)
646 assertEqual(dmode_count, 1)
647
648 return triggers
649
650 def test(self):
651 self.gdb.command("hbreak write_load_trigger")
652 self.gdb.b("clear_triggers")
653 self.gdb.p("$pc=write_store_trigger")
654 output = self.gdb.c()
655 assertIn("write_load_trigger", output)
656 self.check_triggers((1<<6) | (1<<1), 0xdeadbee0)
657 output = self.gdb.c()
658 assertIn("clear_triggers", output)
659 self.check_triggers((1<<6) | (1<<0), 0xfeedac00)
660
661 class RegsTest(GdbTest):
662 compile_args = ("programs/regs.S", )
663 def setUp(self):
664 self.gdb.load()
665 self.gdb.b("main")
666 self.gdb.b("handle_trap")
667 self.gdb.c()
668
669 class WriteGprs(RegsTest):
670 def test(self):
671 regs = [("x%d" % n) for n in range(2, 32)]
672
673 self.gdb.p("$pc=write_regs")
674 for i, r in enumerate(regs):
675 self.gdb.p("$%s=%d" % (r, (0xdeadbeef<<i)+17))
676 self.gdb.p("$x1=data")
677 self.gdb.command("b all_done")
678 output = self.gdb.c()
679 assertIn("Breakpoint ", output)
680
681 # Just to get this data in the log.
682 self.gdb.command("x/30gx data")
683 self.gdb.command("info registers")
684 for n in range(len(regs)):
685 assertEqual(self.gdb.x("data+%d" % (8*n), 'g'),
686 ((0xdeadbeef<<n)+17) & ((1<<self.target.xlen)-1))
687
688 class WriteCsrs(RegsTest):
689 def test(self):
690 # As much a test of gdb as of the simulator.
691 self.gdb.p("$mscratch=0")
692 self.gdb.stepi()
693 assertEqual(self.gdb.p("$mscratch"), 0)
694 self.gdb.p("$mscratch=123")
695 self.gdb.stepi()
696 assertEqual(self.gdb.p("$mscratch"), 123)
697
698 self.gdb.command("p $pc=write_regs")
699 self.gdb.command("p $a0=data")
700 self.gdb.command("b all_done")
701 self.gdb.command("c")
702
703 assertEqual(123, self.gdb.p("$mscratch"))
704 assertEqual(123, self.gdb.p("$x1"))
705 assertEqual(123, self.gdb.p("$csr832"))
706
707 class DownloadTest(GdbTest):
708 def setUp(self):
709 length = min(2**20, self.target.ram_size - 2048)
710 download_c = tempfile.NamedTemporaryFile(prefix="download_",
711 suffix=".c")
712 download_c.write("#include <stdint.h>\n")
713 download_c.write(
714 "unsigned int crc32a(uint8_t *message, unsigned int size);\n")
715 download_c.write("uint32_t length = %d;\n" % length)
716 download_c.write("uint8_t d[%d] = {\n" % length)
717 self.crc = 0
718 for i in range(length / 16):
719 download_c.write(" /* 0x%04x */ " % (i * 16))
720 for _ in range(16):
721 value = random.randrange(1<<8)
722 download_c.write("%d, " % value)
723 self.crc = binascii.crc32("%c" % value, self.crc)
724 download_c.write("\n")
725 download_c.write("};\n")
726 download_c.write("uint8_t *data = &d[0];\n")
727 download_c.write("uint32_t main() { return crc32a(data, length); }\n")
728 download_c.flush()
729
730 if self.crc < 0:
731 self.crc += 2**32
732
733 self.binary = self.target.compile(download_c.name,
734 "programs/checksum.c")
735 self.gdb.command("file %s" % self.binary)
736
737 def test(self):
738 self.gdb.load()
739 self.gdb.command("b _exit")
740 self.gdb.c()
741 assertEqual(self.gdb.p("status"), self.crc)
742
743 class MprvTest(GdbTest):
744 compile_args = ("programs/mprv.S", )
745 def setUp(self):
746 self.gdb.load()
747
748 def test(self):
749 """Test that the debugger can access memory when MPRV is set."""
750 self.gdb.c(wait=False)
751 time.sleep(0.5)
752 self.gdb.interrupt()
753 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
754 assertIn("0xbead", output)
755
756 class PrivTest(GdbTest):
757 compile_args = ("programs/priv.S", )
758 def setUp(self):
759 self.gdb.load()
760
761 misa = self.gdb.p("$misa")
762 self.supported = set()
763 if misa & (1<<20):
764 self.supported.add(0)
765 if misa & (1<<18):
766 self.supported.add(1)
767 if misa & (1<<7):
768 self.supported.add(2)
769 self.supported.add(3)
770
771 class PrivRw(PrivTest):
772 def test(self):
773 """Test reading/writing priv."""
774 for privilege in range(4):
775 self.gdb.p("$priv=%d" % privilege)
776 self.gdb.stepi()
777 actual = self.gdb.p("$priv")
778 assertIn(actual, self.supported)
779 if privilege in self.supported:
780 assertEqual(actual, privilege)
781
782 class PrivChange(PrivTest):
783 def test(self):
784 """Test that the core's privilege level actually changes."""
785
786 if 0 not in self.supported:
787 return 'not_applicable'
788
789 self.gdb.b("main")
790 self.gdb.c()
791
792 # Machine mode
793 self.gdb.p("$priv=3")
794 main_address = self.gdb.p("$pc")
795 self.gdb.stepi()
796 assertEqual("%x" % self.gdb.p("$pc"), "%x" % (main_address+4))
797
798 # User mode
799 self.gdb.p("$priv=0")
800 self.gdb.stepi()
801 # Should have taken an exception, so be nowhere near main.
802 pc = self.gdb.p("$pc")
803 assertTrue(pc < main_address or pc > main_address + 0x100)
804
805 class Target(object):
806 name = "name"
807 xlen = 0
808 directory = None
809 timeout_sec = 2
810 temporary_files = []
811 temporary_binary = None
812
813 def server(self):
814 raise NotImplementedError
815
816 def compile(self, *sources):
817 binary_name = "%s_%s-%d" % (
818 self.name,
819 os.path.basename(os.path.splitext(sources[0])[0]),
820 self.xlen)
821 if parsed.isolate:
822 self.temporary_binary = tempfile.NamedTemporaryFile(
823 prefix=binary_name + "_")
824 binary_name = self.temporary_binary.name
825 Target.temporary_files.append(self.temporary_binary)
826 testlib.compile(sources +
827 ("programs/entry.S", "programs/init.c",
828 "-I", "../env",
829 "-T", "targets/%s/link.lds" % (self.directory or self.name),
830 "-nostartfiles",
831 "-mcmodel=medany",
832 "-o", binary_name),
833 xlen=self.xlen)
834 return binary_name
835
836 class SpikeTarget(Target):
837 directory = "spike"
838 ram = 0x80010000
839 ram_size = 5 * 1024 * 1024
840 instruction_hardware_breakpoint_count = 4
841 reset_vector = 0x1000
842
843 class Spike64Target(SpikeTarget):
844 name = "spike64"
845 xlen = 64
846
847 def server(self):
848 return testlib.Spike(parsed.cmd, halted=True)
849
850 class Spike32Target(SpikeTarget):
851 name = "spike32"
852 xlen = 32
853
854 def server(self):
855 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
856
857 class FreedomE300Target(Target):
858 name = "freedom-e300"
859 xlen = 32
860 ram = 0x80000000
861 ram_size = 16 * 1024
862 instruction_hardware_breakpoint_count = 2
863
864 def server(self):
865 return testlib.Openocd(cmd=parsed.cmd,
866 config="targets/%s/openocd.cfg" % self.name)
867
868 class FreedomE300SimTarget(Target):
869 name = "freedom-e300-sim"
870 xlen = 32
871 timeout_sec = 240
872 ram = 0x80000000
873 ram_size = 256 * 1024 * 1024
874 instruction_hardware_breakpoint_count = 2
875
876 def server(self):
877 sim = testlib.VcsSim(simv=parsed.run, debug=False)
878 openocd = testlib.Openocd(cmd=parsed.cmd,
879 config="targets/%s/openocd.cfg" % self.name,
880 otherProcess=sim)
881 time.sleep(20)
882 return openocd
883
884 class FreedomU500Target(Target):
885 name = "freedom-u500"
886 xlen = 64
887 ram = 0x80000000
888 ram_size = 16 * 1024
889 instruction_hardware_breakpoint_count = 2
890
891 def server(self):
892 return testlib.Openocd(cmd=parsed.cmd,
893 config="targets/%s/openocd.cfg" % self.name)
894
895 class FreedomU500SimTarget(Target):
896 name = "freedom-u500-sim"
897 xlen = 64
898 timeout_sec = 240
899 ram = 0x80000000
900 ram_size = 256 * 1024 * 1024
901 instruction_hardware_breakpoint_count = 2
902
903 def server(self):
904 sim = testlib.VcsSim(simv=parsed.run, debug=False)
905 openocd = testlib.Openocd(cmd=parsed.cmd,
906 config="targets/%s/openocd.cfg" % self.name,
907 otherProcess=sim)
908 time.sleep(20)
909 return openocd
910
911 targets = [
912 Spike32Target,
913 Spike64Target,
914 FreedomE300Target,
915 FreedomU500Target,
916 FreedomE300SimTarget,
917 FreedomU500SimTarget]
918
919 parsed = None
920 def main():
921 parser = argparse.ArgumentParser(
922 epilog="""
923 Example command line from the real world:
924 Run all RegsTest cases against a physical FPGA, with custom openocd command:
925 ./gdbserver.py --freedom-e300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" RegsTest
926 """)
927 group = parser.add_mutually_exclusive_group(required=True)
928 for t in targets:
929 group.add_argument("--%s" % t.name, action="store_const", const=t,
930 dest="target")
931 parser.add_argument("--run",
932 help="The command to use to start the actual target (e.g. "
933 "simulation)")
934 parser.add_argument("--cmd",
935 help="The command to use to start the debug server.")
936 parser.add_argument("--gdb",
937 help="The command to use to start gdb.")
938
939 xlen_group = parser.add_mutually_exclusive_group()
940 xlen_group.add_argument("--32", action="store_const", const=32, dest="xlen",
941 help="Force the target to be 32-bit.")
942 xlen_group.add_argument("--64", action="store_const", const=64, dest="xlen",
943 help="Force the target to be 64-bit.")
944
945 parser.add_argument("--isolate", action="store_true",
946 help="Try to run in such a way that multiple instances can run at "
947 "the same time. This may make it harder to debug a failure if it "
948 "does occur.")
949
950 parser.add_argument("--fail-fast", "-f", action="store_true",
951 help="Exit as soon as any test fails.")
952
953 parser.add_argument("test", nargs='*',
954 help="Run only tests that are named here.")
955
956 # TODO: remove global
957 global parsed # pylint: disable=global-statement
958 parsed = parser.parse_args()
959
960 target = parsed.target()
961 if parsed.xlen:
962 target.xlen = parsed.xlen
963
964 return run_all_tests(target, parsed.test, parsed.fail_fast)
965
966 # TROUBLESHOOTING TIPS
967 # If a particular test fails, run just that one test, eg.:
968 # ./gdbserver.py MprvTest.test_mprv
969 # Then inspect gdb.log and spike.log to see what happened in more detail.
970
971 if __name__ == '__main__':
972 sys.exit(main())