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