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