Update dmode test to match spec.
[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 MemTestBlock(GdbTest):
297 def test(self):
298 length = 1024
299 line_length = 16
300 a = tempfile.NamedTemporaryFile(suffix=".ihex")
301 data = ""
302 for i in range(length / line_length):
303 line_data = "".join(["%c" % random.randrange(256)
304 for _ in range(line_length)])
305 data += line_data
306 a.write(ihex_line(i * line_length, 0, line_data))
307 a.flush()
308
309 self.gdb.command("restore %s 0x%x" % (a.name, self.target.ram))
310 for offset in range(0, length, 19*4) + [length-4]:
311 value = self.gdb.p("*((int*)0x%x)" % (self.target.ram + offset))
312 written = ord(data[offset]) | \
313 (ord(data[offset+1]) << 8) | \
314 (ord(data[offset+2]) << 16) | \
315 (ord(data[offset+3]) << 24)
316 assertEqual(value, written)
317
318 b = tempfile.NamedTemporaryFile(suffix=".ihex")
319 self.gdb.command("dump ihex memory %s 0x%x 0x%x" % (b.name,
320 self.target.ram, self.target.ram + length))
321 for line in b:
322 record_type, address, line_data = ihex_parse(line)
323 if record_type == 0:
324 assertEqual(readable_binary_string(line_data),
325 readable_binary_string(
326 data[address:address+len(line_data)]))
327
328 class InstantHaltTest(GdbTest):
329 def test(self):
330 assertEqual(self.target.reset_vector, self.gdb.p("$pc"))
331 # mcycle and minstret have no defined reset value.
332 mstatus = self.gdb.p("$mstatus")
333 assertEqual(mstatus & (MSTATUS_MIE | MSTATUS_MPRV |
334 MSTATUS_VM), 0)
335
336 class InstantChangePc(GdbTest):
337 def test(self):
338 """Change the PC right as we come out of reset."""
339 # 0x13 is nop
340 self.gdb.command("p *((int*) 0x%x)=0x13" % self.target.ram)
341 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 4))
342 self.gdb.command("p *((int*) 0x%x)=0x13" % (self.target.ram + 8))
343 self.gdb.p("$pc=0x%x" % self.target.ram)
344 self.gdb.stepi()
345 assertEqual((self.target.ram + 4), self.gdb.p("$pc"))
346 self.gdb.stepi()
347 assertEqual((self.target.ram + 8), self.gdb.p("$pc"))
348
349 class DebugTest(GdbTest):
350 # Include malloc so that gdb can make function calls. I suspect this malloc
351 # will silently blow through the memory set aside for it, so be careful.
352 compile_args = ("programs/debug.c", "programs/checksum.c",
353 "programs/tiny-malloc.c", "-DDEFINE_MALLOC", "-DDEFINE_FREE")
354
355 def setUp(self):
356 self.gdb.load()
357 self.gdb.b("_exit")
358
359 def exit(self, expected_result=0xc86455d4):
360 output = self.gdb.c()
361 assertIn("Breakpoint", output)
362 assertIn("_exit", output)
363 assertEqual(self.gdb.p("status"), expected_result)
364
365 class DebugFunctionCall(DebugTest):
366 def test(self):
367 self.gdb.b("main:start")
368 self.gdb.c()
369 assertEqual(self.gdb.p('fib(6)'), 8)
370 assertEqual(self.gdb.p('fib(7)'), 13)
371 self.exit()
372
373 class DebugChangeString(DebugTest):
374 def test(self):
375 text = "This little piggy went to the market."
376 self.gdb.b("main:start")
377 self.gdb.c()
378 self.gdb.p('fox = "%s"' % text)
379 self.exit(0x43b497b8)
380
381 class DebugTurbostep(DebugTest):
382 def test(self):
383 """Single step a bunch of times."""
384 self.gdb.b("main:start")
385 self.gdb.c()
386 self.gdb.command("p i=0")
387 last_pc = None
388 advances = 0
389 jumps = 0
390 for _ in range(100):
391 self.gdb.stepi()
392 pc = self.gdb.p("$pc")
393 assertNotEqual(last_pc, pc)
394 if last_pc and pc > last_pc and pc - last_pc <= 4:
395 advances += 1
396 else:
397 jumps += 1
398 last_pc = pc
399 # Some basic sanity that we're not running between breakpoints or
400 # something.
401 assertGreater(jumps, 10)
402 assertGreater(advances, 50)
403
404 class DebugExit(DebugTest):
405 def test(self):
406 self.exit()
407
408 class DebugSymbols(DebugTest):
409 def test(self):
410 self.gdb.b("main")
411 self.gdb.b("rot13")
412 output = self.gdb.c()
413 assertIn(", main ", output)
414 output = self.gdb.c()
415 assertIn(", rot13 ", output)
416
417 class DebugBreakpoint(DebugTest):
418 def test(self):
419 self.gdb.b("rot13")
420 # The breakpoint should be hit exactly 2 times.
421 for _ in range(2):
422 output = self.gdb.c()
423 self.gdb.p("$pc")
424 assertIn("Breakpoint ", output)
425 assertIn("rot13 ", output)
426 self.exit()
427
428 class Hwbp1(DebugTest):
429 def test(self):
430 if self.target.instruction_hardware_breakpoint_count < 1:
431 return 'not_applicable'
432
433 self.gdb.hbreak("rot13")
434 # The breakpoint should be hit exactly 2 times.
435 for _ in range(2):
436 output = self.gdb.c()
437 self.gdb.p("$pc")
438 assertRegexpMatches(output, r"[bB]reakpoint")
439 assertIn("rot13 ", output)
440 self.exit()
441
442 class Hwbp2(DebugTest):
443 def test(self):
444 if self.target.instruction_hardware_breakpoint_count < 2:
445 return 'not_applicable'
446
447 self.gdb.hbreak("main")
448 self.gdb.hbreak("rot13")
449 # We should hit 3 breakpoints.
450 for expected in ("main", "rot13", "rot13"):
451 output = self.gdb.c()
452 self.gdb.p("$pc")
453 assertRegexpMatches(output, r"[bB]reakpoint")
454 assertIn("%s " % expected, output)
455 self.exit()
456
457 class TooManyHwbp(DebugTest):
458 def run(self):
459 for i in range(30):
460 self.gdb.hbreak("*rot13 + %d" % (i * 4))
461
462 output = self.gdb.c()
463 assertIn("Cannot insert hardware breakpoint", output)
464 # Clean up, otherwise the hardware breakpoints stay set and future
465 # tests may fail.
466 self.gdb.command("D")
467
468 class Registers(DebugTest):
469 def test(self):
470 # Get to a point in the code where some registers have actually been
471 # used.
472 self.gdb.b("rot13")
473 self.gdb.c()
474 self.gdb.c()
475 # Try both forms to test gdb.
476 for cmd in ("info all-registers", "info registers all"):
477 output = self.gdb.command(cmd)
478 assertNotIn("Could not", output)
479 for reg in ('zero', 'ra', 'sp', 'gp', 'tp'):
480 assertIn(reg, output)
481
482 #TODO
483 # mcpuid is one of the few registers that should have the high bit set
484 # (for rv64).
485 # Leave this commented out until gdb and spike agree on the encoding of
486 # mcpuid (which is going to be renamed to misa in any case).
487 #assertRegexpMatches(output, ".*mcpuid *0x80")
488
489 #TODO:
490 # The instret register should always be changing.
491 #last_instret = None
492 #for _ in range(5):
493 # instret = self.gdb.p("$instret")
494 # assertNotEqual(instret, last_instret)
495 # last_instret = instret
496 # self.gdb.stepi()
497
498 self.exit()
499
500 class UserInterrupt(DebugTest):
501 def test(self):
502 """Sending gdb ^C while the program is running should cause it to
503 halt."""
504 self.gdb.b("main:start")
505 self.gdb.c()
506 self.gdb.p("i=123")
507 self.gdb.c(wait=False)
508 time.sleep(0.1)
509 output = self.gdb.interrupt()
510 assert "main" in output
511 assertGreater(self.gdb.p("j"), 10)
512 self.gdb.p("i=0")
513 self.exit()
514
515 class StepTest(GdbTest):
516 compile_args = ("programs/step.S", )
517
518 def setUp(self):
519 self.gdb.load()
520 self.gdb.b("main")
521 self.gdb.c()
522
523 def test(self):
524 main_address = self.gdb.p("$pc")
525 for expected in (4, 8, 0xc, 0x10, 0x18, 0x1c, 0x28, 0x20, 0x2c, 0x2c):
526 self.gdb.stepi()
527 pc = self.gdb.p("$pc")
528 assertEqual("%x" % pc, "%x" % (expected + main_address))
529
530 class TriggerTest(GdbTest):
531 compile_args = ("programs/trigger.S", )
532 def setUp(self):
533 self.gdb.load()
534 self.gdb.b("_exit")
535 self.gdb.b("main")
536 self.gdb.c()
537
538 def exit(self):
539 output = self.gdb.c()
540 assertIn("Breakpoint", output)
541 assertIn("_exit", output)
542
543 class TriggerExecuteInstant(TriggerTest):
544 """Test an execute breakpoint on the first instruction executed out of
545 debug mode."""
546 def test(self):
547 main_address = self.gdb.p("$pc")
548 self.gdb.command("hbreak *0x%x" % (main_address + 4))
549 self.gdb.c()
550 assertEqual(self.gdb.p("$pc"), main_address+4)
551
552 class TriggerLoadAddress(TriggerTest):
553 def test(self):
554 self.gdb.command("rwatch *((&data)+1)")
555 output = self.gdb.c()
556 assertIn("read_loop", output)
557 assertEqual(self.gdb.p("$a0"),
558 self.gdb.p("(&data)+1"))
559 self.exit()
560
561 class TriggerLoadAddressInstant(TriggerTest):
562 """Test a load address breakpoint on the first instruction executed out of
563 debug mode."""
564 def test(self):
565 self.gdb.command("b just_before_read_loop")
566 self.gdb.c()
567 read_loop = self.gdb.p("&read_loop")
568 self.gdb.command("rwatch data")
569 self.gdb.c()
570 # Accept hitting the breakpoint before or after the load instruction.
571 assertIn(self.gdb.p("$pc"), [read_loop, read_loop + 4])
572 assertEqual(self.gdb.p("$a0"), self.gdb.p("&data"))
573
574 class TriggerStoreAddress(TriggerTest):
575 def test(self):
576 self.gdb.command("watch *((&data)+3)")
577 output = self.gdb.c()
578 assertIn("write_loop", output)
579 assertEqual(self.gdb.p("$a0"),
580 self.gdb.p("(&data)+3"))
581 self.exit()
582
583 class TriggerStoreAddressInstant(TriggerTest):
584 def test(self):
585 """Test a store address breakpoint on the first instruction executed out
586 of debug mode."""
587 self.gdb.command("b just_before_write_loop")
588 self.gdb.c()
589 write_loop = self.gdb.p("&write_loop")
590 self.gdb.command("watch data")
591 self.gdb.c()
592 # Accept hitting the breakpoint before or after the store instruction.
593 assertIn(self.gdb.p("$pc"), [write_loop, write_loop + 4])
594 assertEqual(self.gdb.p("$a0"), self.gdb.p("&data"))
595
596 class TriggerDmode(TriggerTest):
597 def check_triggers(self, tdata1_lsbs, tdata2):
598 dmode = 1 << (self.target.xlen-5)
599
600 triggers = []
601
602 if self.target.xlen == 32:
603 xlen_type = 'int'
604 elif self.target.xlen == 64:
605 xlen_type = 'long long'
606 else:
607 raise NotImplementedError
608
609 dmode_count = 0
610 i = 0
611 for i in range(16):
612 tdata1 = self.gdb.p("((%s *)&data)[%d]" % (xlen_type, 2*i))
613 if tdata1 == 0:
614 break
615 tdata2 = self.gdb.p("((%s *)&data)[%d]" % (xlen_type, 2*i+1))
616
617 if tdata1 & dmode:
618 dmode_count += 1
619 else:
620 assertEqual(tdata1 & 0xffff, tdata1_lsbs)
621 assertEqual(tdata2, tdata2)
622
623 assertGreater(i, 1)
624 assertEqual(dmode_count, 1)
625
626 return triggers
627
628 def test(self):
629 self.gdb.command("hbreak write_load_trigger")
630 self.gdb.b("clear_triggers")
631 self.gdb.p("$pc=write_store_trigger")
632 output = self.gdb.c()
633 assertIn("write_load_trigger", output)
634 self.check_triggers((1<<6) | (1<<1), 0xdeadbee0)
635 output = self.gdb.c()
636 assertIn("clear_triggers", output)
637 self.check_triggers((1<<6) | (1<<0), 0xfeedac00)
638
639 class RegsTest(GdbTest):
640 compile_args = ("programs/regs.S", )
641 def setUp(self):
642 self.gdb.load()
643 self.gdb.b("main")
644 self.gdb.b("handle_trap")
645 self.gdb.c()
646
647 class WriteGprs(RegsTest):
648 def test(self):
649 regs = [("x%d" % n) for n in range(2, 32)]
650
651 self.gdb.p("$pc=write_regs")
652 for i, r in enumerate(regs):
653 self.gdb.p("$%s=%d" % (r, (0xdeadbeef<<i)+17))
654 self.gdb.p("$x1=data")
655 self.gdb.command("b all_done")
656 output = self.gdb.c()
657 assertIn("Breakpoint ", output)
658
659 # Just to get this data in the log.
660 self.gdb.command("x/30gx data")
661 self.gdb.command("info registers")
662 for n in range(len(regs)):
663 assertEqual(self.gdb.x("data+%d" % (8*n), 'g'),
664 ((0xdeadbeef<<n)+17) & ((1<<self.target.xlen)-1))
665
666 class WriteCsrs(RegsTest):
667 def test(self):
668 # As much a test of gdb as of the simulator.
669 self.gdb.p("$mscratch=0")
670 self.gdb.stepi()
671 assertEqual(self.gdb.p("$mscratch"), 0)
672 self.gdb.p("$mscratch=123")
673 self.gdb.stepi()
674 assertEqual(self.gdb.p("$mscratch"), 123)
675
676 self.gdb.command("p $pc=write_regs")
677 self.gdb.command("p $a0=data")
678 self.gdb.command("b all_done")
679 self.gdb.command("c")
680
681 assertEqual(123, self.gdb.p("$mscratch"))
682 assertEqual(123, self.gdb.p("$x1"))
683 assertEqual(123, self.gdb.p("$csr832"))
684
685 class DownloadTest(GdbTest):
686 def setUp(self):
687 length = min(2**20, self.target.ram_size - 2048)
688 download_c = tempfile.NamedTemporaryFile(prefix="download_",
689 suffix=".c")
690 download_c.write("#include <stdint.h>\n")
691 download_c.write(
692 "unsigned int crc32a(uint8_t *message, unsigned int size);\n")
693 download_c.write("uint32_t length = %d;\n" % length)
694 download_c.write("uint8_t d[%d] = {\n" % length)
695 self.crc = 0
696 for i in range(length / 16):
697 download_c.write(" /* 0x%04x */ " % (i * 16))
698 for _ in range(16):
699 value = random.randrange(1<<8)
700 download_c.write("%d, " % value)
701 self.crc = binascii.crc32("%c" % value, self.crc)
702 download_c.write("\n")
703 download_c.write("};\n")
704 download_c.write("uint8_t *data = &d[0];\n")
705 download_c.write("uint32_t main() { return crc32a(data, length); }\n")
706 download_c.flush()
707
708 if self.crc < 0:
709 self.crc += 2**32
710
711 self.binary = self.target.compile(download_c.name,
712 "programs/checksum.c")
713 self.gdb.command("file %s" % self.binary)
714
715 def test(self):
716 self.gdb.load()
717 self.gdb.command("b _exit")
718 self.gdb.c()
719 assertEqual(self.gdb.p("status"), self.crc)
720
721 class MprvTest(GdbTest):
722 compile_args = ("programs/mprv.S", )
723 def setUp(self):
724 self.gdb.load()
725
726 def test(self):
727 """Test that the debugger can access memory when MPRV is set."""
728 self.gdb.c(wait=False)
729 time.sleep(0.5)
730 self.gdb.interrupt()
731 output = self.gdb.command("p/x *(int*)(((char*)&data)-0x80000000)")
732 assertIn("0xbead", output)
733
734 class PrivTest(GdbTest):
735 compile_args = ("programs/priv.S", )
736 def setUp(self):
737 self.gdb.load()
738
739 misa = self.gdb.p("$misa")
740 self.supported = set()
741 if misa & (1<<20):
742 self.supported.add(0)
743 if misa & (1<<18):
744 self.supported.add(1)
745 if misa & (1<<7):
746 self.supported.add(2)
747 self.supported.add(3)
748
749 class PrivRw(PrivTest):
750 def test(self):
751 """Test reading/writing priv."""
752 for privilege in range(4):
753 self.gdb.p("$priv=%d" % privilege)
754 self.gdb.stepi()
755 actual = self.gdb.p("$priv")
756 assertIn(actual, self.supported)
757 if privilege in self.supported:
758 assertEqual(actual, privilege)
759
760 class PrivChange(PrivTest):
761 def test(self):
762 """Test that the core's privilege level actually changes."""
763
764 if 0 not in self.supported:
765 return 'not_applicable'
766
767 self.gdb.b("main")
768 self.gdb.c()
769
770 # Machine mode
771 self.gdb.p("$priv=3")
772 main_address = self.gdb.p("$pc")
773 self.gdb.stepi()
774 assertEqual("%x" % self.gdb.p("$pc"), "%x" % (main_address+4))
775
776 # User mode
777 self.gdb.p("$priv=0")
778 self.gdb.stepi()
779 # Should have taken an exception, so be nowhere near main.
780 pc = self.gdb.p("$pc")
781 assertTrue(pc < main_address or pc > main_address + 0x100)
782
783 class Target(object):
784 name = "name"
785 xlen = 0
786 directory = None
787 timeout_sec = 2
788 temporary_files = []
789 temporary_binary = None
790
791 def server(self):
792 raise NotImplementedError
793
794 def compile(self, *sources):
795 binary_name = "%s_%s-%d" % (
796 self.name,
797 os.path.basename(os.path.splitext(sources[0])[0]),
798 self.xlen)
799 if parsed.isolate:
800 self.temporary_binary = tempfile.NamedTemporaryFile(
801 prefix=binary_name + "_")
802 binary_name = self.temporary_binary.name
803 Target.temporary_files.append(self.temporary_binary)
804 testlib.compile(sources +
805 ("programs/entry.S", "programs/init.c",
806 "-I", "../env",
807 "-T", "targets/%s/link.lds" % (self.directory or self.name),
808 "-nostartfiles",
809 "-mcmodel=medany",
810 "-o", binary_name),
811 xlen=self.xlen)
812 return binary_name
813
814 class SpikeTarget(Target):
815 directory = "spike"
816 ram = 0x80010000
817 ram_size = 5 * 1024 * 1024
818 instruction_hardware_breakpoint_count = 4
819 reset_vector = 0x1000
820
821 class Spike64Target(SpikeTarget):
822 name = "spike64"
823 xlen = 64
824
825 def server(self):
826 return testlib.Spike(parsed.cmd, halted=True)
827
828 class Spike32Target(SpikeTarget):
829 name = "spike32"
830 xlen = 32
831
832 def server(self):
833 return testlib.Spike(parsed.cmd, halted=True, xlen=32)
834
835 class FreedomE300Target(Target):
836 name = "freedom-e300"
837 xlen = 32
838 ram = 0x80000000
839 ram_size = 16 * 1024
840 instruction_hardware_breakpoint_count = 2
841
842 def server(self):
843 return testlib.Openocd(cmd=parsed.cmd,
844 config="targets/%s/openocd.cfg" % self.name)
845
846 class FreedomE300SimTarget(Target):
847 name = "freedom-e300-sim"
848 xlen = 32
849 timeout_sec = 240
850 ram = 0x80000000
851 ram_size = 256 * 1024 * 1024
852 instruction_hardware_breakpoint_count = 2
853
854 def server(self):
855 sim = testlib.VcsSim(simv=parsed.run, debug=False)
856 openocd = testlib.Openocd(cmd=parsed.cmd,
857 config="targets/%s/openocd.cfg" % self.name,
858 otherProcess=sim)
859 time.sleep(20)
860 return openocd
861
862 class FreedomU500Target(Target):
863 name = "freedom-u500"
864 xlen = 64
865 ram = 0x80000000
866 ram_size = 16 * 1024
867 instruction_hardware_breakpoint_count = 2
868
869 def server(self):
870 return testlib.Openocd(cmd=parsed.cmd,
871 config="targets/%s/openocd.cfg" % self.name)
872
873 class FreedomU500SimTarget(Target):
874 name = "freedom-u500-sim"
875 xlen = 64
876 timeout_sec = 240
877 ram = 0x80000000
878 ram_size = 256 * 1024 * 1024
879 instruction_hardware_breakpoint_count = 2
880
881 def server(self):
882 sim = testlib.VcsSim(simv=parsed.run, debug=False)
883 openocd = testlib.Openocd(cmd=parsed.cmd,
884 config="targets/%s/openocd.cfg" % self.name,
885 otherProcess=sim)
886 time.sleep(20)
887 return openocd
888
889 targets = [
890 Spike32Target,
891 Spike64Target,
892 FreedomE300Target,
893 FreedomU500Target,
894 FreedomE300SimTarget,
895 FreedomU500SimTarget]
896
897 parsed = None
898 def main():
899 parser = argparse.ArgumentParser(
900 epilog="""
901 Example command line from the real world:
902 Run all RegsTest cases against a physical FPGA, with custom openocd command:
903 ./gdbserver.py --freedom-e300 --cmd "$HOME/SiFive/openocd/src/openocd -s $HOME/SiFive/openocd/tcl -d" RegsTest
904 """)
905 group = parser.add_mutually_exclusive_group(required=True)
906 for t in targets:
907 group.add_argument("--%s" % t.name, action="store_const", const=t,
908 dest="target")
909 parser.add_argument("--run",
910 help="The command to use to start the actual target (e.g. "
911 "simulation)")
912 parser.add_argument("--cmd",
913 help="The command to use to start the debug server.")
914 parser.add_argument("--gdb",
915 help="The command to use to start gdb.")
916
917 xlen_group = parser.add_mutually_exclusive_group()
918 xlen_group.add_argument("--32", action="store_const", const=32, dest="xlen",
919 help="Force the target to be 32-bit.")
920 xlen_group.add_argument("--64", action="store_const", const=64, dest="xlen",
921 help="Force the target to be 64-bit.")
922
923 parser.add_argument("--isolate", action="store_true",
924 help="Try to run in such a way that multiple instances can run at "
925 "the same time. This may make it harder to debug a failure if it "
926 "does occur.")
927
928 parser.add_argument("--fail-fast", "-f", action="store_true",
929 help="Exit as soon as any test fails.")
930
931 parser.add_argument("test", nargs='*',
932 help="Run only tests that are named here.")
933
934 # TODO: remove global
935 global parsed # pylint: disable=global-statement
936 parsed = parser.parse_args()
937
938 target = parsed.target()
939 if parsed.xlen:
940 target.xlen = parsed.xlen
941
942 return run_all_tests(target, parsed.test, parsed.fail_fast)
943
944 # TROUBLESHOOTING TIPS
945 # If a particular test fails, run just that one test, eg.:
946 # ./gdbserver.py MprvTest.test_mprv
947 # Then inspect gdb.log and spike.log to see what happened in more detail.
948
949 if __name__ == '__main__':
950 sys.exit(main())