Debian Codegraph @

test/gdb_test_script.py

raw symbols SCIP
1 # pyOCD debugger
2 # Copyright (c) 2015-2020 Arm Limited
3 # Copyright (c) 2021 Chris Reed
4 # SPDX-License-Identifier: Apache-2.0
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Notes about this script
19 # 1. This script runs inside arm-none-eabi-gdb-py
20 # 2. GDB processes commands inside a queue on a worker
21 # thread. Commands that change the state of the target
22 # should run from this queue via gdb.post_event(cb).
23 # 3. After running a command that changes the state of a target
24 # in the background, like "continue&", the code needs to
25 # return so the event processing that occurs on the worker
26 # thread can continue. No target state changes will be
27 # seen until the worker thread gets a chance to process the data.
28 # 4. To make the code flow better with #3 the main test function,
29 # run_test, takes advantage of the 'yield' call. After
30 # performing a background operation that causes the target run
31 # 'yield' must be called with a timeout value. The code
32 # will wait for the target to halt for the time specified and
33 # if no signal arrives in that time the target is explicitly
34 # halted.
35 # 5. Only use packages in the standard library in this script.
36 # Since the current version of arm-none-eabi-gdb-py.exe is
37 # only 32 bit on windows, there must be a 32 bit python
38 # install for it to work. If your primary version of python
39 # is 64 bit, you can install the 32 bit version as a non
40 # primary version. This will allow arm-none-eabi-gdb-py.exe
41 # to work. The only problem with this is that when pyOCD
42 # is installed through pip only the 64 bit version of
43 # pyOCD and it's dependencies will get installed.
44 # If only the standard library is used here then this
45 # script will have no external dependencies.
46
47 import gdb
48 from time import time
49 from threading import Timer
50 from functools import partial
51 from random import randrange
52 from itertools import product
53 import traceback
54 import json
55 import sys
56 import os
57
58 # We expect arm-none-eabi-gdb-py to only run Python 2.x. If it moves
59 # to Python 3, we need to know about it, so print a warning.
60 print("arm-none-eabi-gdb-py is using Python %s" % sys.version)
61 if sys.version_info.major != 2:
62 print("*** Unexpected arm-none-eabi-gdb-py Python version %d! ***" % sys.version_info.major)
63
64 DEFAULT_TIMEOUT = 2.0
65 STACK_OFFSET = 0x800
66 TEST_RAM_OFFSET = 0x800
67 MAX_TEST_SIZE = 0x1000
68 MAX_BKPT = 10
69
70 assert STACK_OFFSET < MAX_TEST_SIZE
71 assert TEST_RAM_OFFSET < MAX_TEST_SIZE
72
73 monitor_commands = [
74 "help",
75 "help reset",
76 "help halt",
77 "init",
78 "reset",
79 "reset halt",
80 "halt",
81 "arm semihosting enable",
82 "arm semihosting disable",
83 "set vector-catch n",
84 "set vector-catch a",
85 "set step-into-interrupts on",
86 "set step-into-interrupts off",
87 "threads status",
88 "readdp 0",
89 "status",
90 "show fault",
91 # Invalid Command
92 "intentional_invalid_command_fawehfawoefhad"
93 ]
94
95 SIZE_TO_C_TYPE = {
96 1: "uint8_t*",
97 2: "uint16_t*",
98 4: "uint32_t*",
99 }
100
101 TO_GDB_ACCESS = {
102 "read": gdb.WP_READ,
103 "write": gdb.WP_WRITE,
104 "read_write": gdb.WP_ACCESS,
105 }
106
107 env_name = os.environ.get('TOX_ENV_NAME', '')
108 env_file_name = ("_" + env_name) if env_name else ''
109
110 def gdb_execute(cmd):
111 print("Executing command:", cmd)
112 gdb.execute(cmd)
113
114
115 def test_step_type(step_type):
116 step_count = 20
117 start = time()
118 for _ in range(step_count):
119 gdb_execute(step_type)
120 end = time()
121 seconds_per_operation = (end - start) / step_count
122 return seconds_per_operation
123
124
125 def is_event_breakpoint(event, bkpt=None):
126 if not isinstance(event, gdb.BreakpointEvent):
127 return False
128 if bkpt is None:
129 return True
130 return event.breakpoints[-1] is bkpt
131
132
133 def is_event_signal(event, signal_name):
134 if not isinstance(event, gdb.SignalEvent):
135 return False
136 return event.stop_signal == signal_name
137
138
139 def has_read(name):
140 if name == "read":
141 return True
142 if name == "read_write":
143 return True
144 assert name == "write"
145 return False
146
147
148 def has_write(name):
149 if name == "write":
150 return True
151 if name == "read_write":
152 return True
153 assert name == "read"
154 return False
155
156
157 def size_to_type(size):
158 return SIZE_TO_C_TYPE[size]
159
160
161 def to_gdb_access(access):
162 return TO_GDB_ACCESS[access]
163
164
165 def should_trigger_break(bkpt_size, bkpt_access,
166 bkpt_addr, size, access, addr):
167 left_access_addr = addr
168 right_access_addr = addr + size - 1
169 left_bkpt_addr = bkpt_addr
170 right_bkpt_addr = bkpt_addr + bkpt_size
171 overlap = (left_access_addr <= right_bkpt_addr and
172 right_access_addr >= left_bkpt_addr)
173 read_break = has_read(bkpt_access) and has_read(access)
174 write_break = has_write(bkpt_access) and has_write(access)
175 should_break = overlap and (read_break or write_break)
176 return should_break
177
178
179 def valid_watchpoint(bkpt_size, bkpt_access, bkpt_addr):
180 # Unaligned breakpoints are not allowed
181 return bkpt_addr % bkpt_size == 0
182
183
184 # Initial setup
185 testn = int(gdb.parse_and_eval("$testn"))
186
187 test_param_filename = os.path.join("output", "gdb_test_params%s_%d.txt" % (env_file_name, testn))
188 with open(test_param_filename, "rb") as f:
189 test_params = json.loads(f.read())
190
191
192 def run_test():
193
194 test_result = {}
195 test_port = test_params["test_port"]
196 rom_start = test_params['rom_start']
197 ram_start = test_params['ram_start']
198 ram_length = test_params['ram_length']
199 invalid_addr = test_params["invalid_start"]
200 error_on_invalid_access = test_params["expect_error_on_invalid_access"]
201 ignore_hw_bkpt_result = test_params["ignore_hw_bkpt_result"]
202 target_test_elf = test_params["test_elf"]
203
204 assert ram_length >= MAX_TEST_SIZE
205 stack_addr = ram_start + STACK_OFFSET
206 test_ram_addr = ram_start + TEST_RAM_OFFSET
207
208 fail_count = 0
209 try:
210 # Turn off confirmations that would block the script
211 gdb_execute("set pagination off")
212 gdb_execute("set confirm off")
213
214 # Allow GDB to access even unmapped regions
215 gdb_execute("set mem inaccessible-by-default off")
216
217 # Set raw logging
218 gdb_execute("set remotelogfile output/gdb_test_raw%s_%d.txt" % (env_file_name, testn))
219
220 # Connect to server
221 gdb_execute("target remote localhost:%d" % test_port)
222
223 # Show memory regions, useful for debug and verification.
224 gdb_execute("info mem")
225
226 # Possibly useful other commands for reference:
227 # info breakpoints
228 # info mem
229 # show code-cache
230 # show stack-cache
231 # show dcache
232 # show mem inaccessible-by-default
233 # show can-use-hw-watchpoints
234 # info all-registers
235 # set logging file gdb.txt
236 # set logging on
237
238 # Test running the monitor commands
239 for command in monitor_commands:
240 gdb_execute("mon %s" % command)
241
242 # Load target-specific test program into flash.
243 gdb_execute("load %s" % target_test_elf)
244
245 # Reset the target and let it run so it has
246 # a chance to disable the watchdog
247 gdb_execute("mon reset halt")
248 gdb_execute("c&")
249 event = yield(0.1)
250 if not is_event_signal(event, "SIGINT"):
251 fail_count += 1
252 print("Error - target not interrupted as expected")
253
254 # Load test program and symbols
255 test_binary = "../src/gdb_test_program/gdb_test.bin"
256 test_elf = "../src/gdb_test_program/gdb_test.elf"
257 gdb_execute("restore %s binary 0x%x" % (test_binary, ram_start))
258 gdb_execute("add-symbol-file %s 0x%x" % (test_elf, ram_start))
259
260 # Set pc to the test program. Make sure
261 # interrupts are disabled to prevent
262 # other code from running.
263 gdb_execute("set $primask = 1")
264 gdb_execute("set $sp = 0x%x" % stack_addr)
265 gdb_execute("b main")
266 breakpoint = gdb.Breakpoint("main")
267 gdb_execute("set $pc = main")
268 gdb_execute("c&")
269 event = yield(DEFAULT_TIMEOUT)
270 if not is_event_breakpoint(event, breakpoint):
271 fail_count += 1
272 print("Expected: %s\nReceived: %s" % (breakpoint, event))
273 print("Error - could not set pc to function")
274 breakpoint.delete()
275
276 ## Stepping removed as a workaround for a GDB bug. Launchpad issue tracking this is here:
277 ## https://bugs.launchpad.net/gcc-arm-embedded/+bug/1700595
278 #
279 # # Test the speed of the different step types
280 # test_result["step_time_si"] = test_step_type("si")
281 # test_result["step_time_s"] = test_step_type("s")
282 # test_result["step_time_n"] = test_step_type("n")
283 test_result["step_time_si"] = -1
284 test_result["step_time_s"] = -1
285 test_result["step_time_n"] = -1
286 # TODO,c1728p9 - test speed getting stack trace
287 # TODO,c1728p9 - test speed with cache turned on
288 # TODO,c1728p9 - check speed vs breakpoints
289
290 # Let target run to initialize variables
291 gdb_execute("c&")
292 event = yield(0.1)
293 if not is_event_signal(event, "SIGINT"):
294 fail_count += 1
295 print("Error - target not interrupted as expected")
296
297 # Check number of supported breakpoints, along
298 # with graceful handling of a request using
299 # more than the supported number of breakpoints
300 break_list = []
301 for i in range(MAX_BKPT):
302 addr = rom_start + i * 4
303 breakpoint = gdb.Breakpoint("*0x%x" % addr)
304 break_list.append(breakpoint)
305 while True:
306 try:
307 gdb_execute("c&")
308 yield(0.1)
309 break
310 except gdb.error:
311 bkpt = break_list.pop()
312 bkpt.delete()
313 test_result["breakpoint_count"] = len(break_list)
314 for bkpt in break_list:
315 bkpt.delete()
316
317 # Check number of supported watchpoints, along
318 # with graceful handling of a request using
319 # more than the supported number of watchpoints
320 watch_list = []
321 for i in range(MAX_BKPT):
322 addr = rom_start + i * 4
323 breakpoint = gdb.Breakpoint("*0x%x" % addr,
324 gdb.BP_WATCHPOINT, gdb.WP_ACCESS)
325 watch_list.append(breakpoint)
326 while True:
327 try:
328 gdb_execute("c&")
329 yield(0.1)
330 break
331 except gdb.error:
332 bkpt = watch_list.pop()
333 bkpt.delete()
334 test_result["watchpoint_count"] = len(watch_list)
335 for bkpt in watch_list:
336 bkpt.delete()
337
338 # Make sure breakpoint is hit as expected
339 rmt_func = "breakpoint_test"
340 gdb_execute("set var run_breakpoint_test = 1")
341 breakpoint = gdb.Breakpoint(rmt_func)
342 gdb_execute("c&")
343 event = yield(DEFAULT_TIMEOUT)
344 if not is_event_breakpoint(event, breakpoint):
345 fail_count += 1
346 print("Error - breakpoint 1 test failed")
347 func = gdb.selected_frame().function()
348 if func is None:
349 fail_count += 1
350 print("ERROR - selected frame has no function!?")
351 print(gdb.selected_frame())
352 else:
353 func_name = func.name
354 if rmt_func != func_name:
355 fail_count += 1
356 print("ERROR - break occurred at wrong function %s" % func_name)
357 breakpoint.delete()
358 gdb_execute("set var run_breakpoint_test = 0")
359
360 # Let target run, make sure breakpoint isn't hit
361 gdb_execute("set var run_breakpoint_test = 1")
362 gdb_execute("c&")
363 event = yield(0.1)
364 if not is_event_signal(event, "SIGINT"):
365 fail_count += 1
366 print("Error - target not interrupted as expected")
367 gdb_execute("set var run_breakpoint_test = 0")
368
369 # Make sure hardware breakpoint is hit as expected
370 rmt_func = "breakpoint_test"
371 gdb_execute("set var run_breakpoint_test = 1")
372 gdb_execute("hbreak %s" % rmt_func)
373 gdb_execute("c&")
374 event = yield(DEFAULT_TIMEOUT)
375 # TODO, c1728p9 - determine why there isn't a breakpoint event returned
376 # if not is_event_breakpoint(event):
377 # fail_count += 1
378 # print("Error - breakpoint 2 test failed")
379 func = gdb.selected_frame().function()
380 if func is None:
381 fail_count += 1
382 print("ERROR - selected frame has no function!?")
383 print(gdb.selected_frame())
384 else:
385 func_name = func.name
386 if rmt_func != func_name and not ignore_hw_bkpt_result:
387 fail_count += 1
388 print("ERROR - break occurred at wrong function %s" % func_name)
389 gdb_execute("clear %s" % rmt_func)
390 gdb_execute("set var run_breakpoint_test = 0")
391
392 # Test valid memory write
393 addr_value_list = [(test_ram_addr + i * 4,
394 randrange(1, 50)) for i in range(4)]
395 for addr, value in addr_value_list:
396 gdb_execute("set *((int *) 0x%x) = 0x%x" % (addr, value))
397
398 # Test invalid memory write
399 invalid_addr_list = [invalid_addr + i * 4 for i in range(4)]
400 for addr in invalid_addr_list:
401 try:
402 gdb_execute("set *((int *) 0x%x) = 0x%x" % (addr, randrange(1, 50)))
403 if error_on_invalid_access:
404 fail_count += 1
405 print("Error - invalid memory write did not fault @ 0x%x" % addr)
406 except gdb.MemoryError:
407 pass
408
409 # Test valid memory read
410 for addr, value in addr_value_list:
411 val_read = gdb.parse_and_eval("*((int *) 0x%x)" % addr)
412 val_read = int(val_read)
413 assert value == val_read
414
415 # Test invalid memory read
416 for addr in invalid_addr_list:
417 try:
418 gdb_execute("x 0x%x" % addr)
419 if error_on_invalid_access:
420 fail_count += 1
421 print("Error - invalid memory read did not fault @ 0x%x" % addr)
422 except gdb.MemoryError:
423 pass
424
425 # Test watchpoints
426 access_addr = int(gdb.parse_and_eval("&watchpoint_write_buffer[1]"))
427 bkpt_sizes = [1, 2, 4]
428 bkpt_accesses = ["read", "write", "read_write"]
429 # use "range(-4, 8, 1)" for extended testing
430 bkpt_addresses = [access_addr + offset for offset in range(0, 4, 1)]
431 sizes = [1, 2, 4]
432 accesses = ["read", "write", "read_write"]
433 addresses = [access_addr]
434 generator = product(bkpt_sizes, bkpt_accesses, bkpt_addresses,
435 sizes, accesses, addresses)
436 for bkpt_size, bkpt_access, bkpt_addr, size, access, addr in generator:
437 gdb_size = size_to_type(bkpt_size)
438 gdb_access = to_gdb_access(bkpt_access)
439 gdb_execute("set var watchpoint_write = %i" %
440 (1 if has_write(access) else 0))
441 gdb_execute("set var watchpoint_read = %i" %
442 (1 if has_read(access) else 0))
443 gdb_execute("set var watchpoint_size = %i" % size)
444 gdb_execute("set var write_address = %i" % addr)
445 breakpoint = gdb.Breakpoint("*(%s)0x%x" % (gdb_size, bkpt_addr),
446 gdb.BP_WATCHPOINT, gdb_access)
447
448 # Run until breakpoint is hit
449 gdb_execute("c&")
450 event = yield(0.1)
451 bkpt_hit = not is_event_signal(event, "SIGINT")
452
453 # Compare against expected result
454 should_break = should_trigger_break(bkpt_size, bkpt_access,
455 bkpt_addr, size, access, addr)
456 valid = valid_watchpoint(bkpt_size, bkpt_access, bkpt_addr)
457
458 if valid and bkpt_hit != should_break:
459 fail_count += 1
460 print("Error - watchpoint problem:")
461 print(" Watchpoint was hit %s" % bkpt_hit)
462 print(" Watchpoint should be hit %s" % should_break)
463 print(" bkpt_size %s, bkpt_access %s, bkpt_address 0x%x, "
464 "size %s, access %s, addr 0x%x" %
465 (bkpt_size, bkpt_access, bkpt_addr, size, access, addr))
466 print()
467
468 breakpoint.delete()
469
470 # TODO,c1728p9 - test reading/writing registers
471
472 # TODO,c1728p9 - test stepping into interrupts
473
474 # TODO,c1728p9 - test vector catch
475 # -test hard fault handling
476 # -test reset catch
477 # TODO,c1728p9 - test signals/hard fault
478
479 if fail_count:
480 print("Test completed with %i errors" % fail_count)
481 else:
482 print("Test completed successfully")
483 except Exception:
484 print("Main Error:")
485 traceback.print_exc()
486 fail_count += 1
487 finally:
488 test_result["fail_count"] = fail_count
489 test_result_filename = os.path.join("output", "gdb_test_results%s_%d.txt" % (env_file_name, testn))
490 with open(test_result_filename, "wb") as f:
491 f.write(json.dumps(test_result))
492 # Ignore errors detaching, in case connecting failed.
493 try:
494 gdb_execute("detach")
495 except gdb.error:
496 pass
497 gdb_execute("quit %i" % fail_count)
498
499
500 ignore_events = True
501 interrupt_timer = None
502 interrupt_arg = None
503 generator = run_test()
504
505
506 # Post task to halt the processor
507 def post_interrupt_task(interrupt_arg):
508 # Halt the target by interrupting it
509 # This must only run on GDB's queue
510 def interrupt_task():
511 if not interrupt_arg["aborted"]:
512 gdb_execute("interrupt")
513 gdb.post_event(interrupt_task)
514
515
516 # Run the main test by repeatedly calling the generator
517 # This must only run on GDB's queue
518 def run_generator(event):
519 global ignore_events
520 global interrupt_timer
521 global interrupt_arg
522 ignore_events = True
523 if interrupt_timer is not None:
524 interrupt_timer.cancel()
525 interrupt_arg["aborted"] = True
526 interrupt_arg = None
527 stop_delay = 0
528 try:
529 stop_delay = generator.send(event)
530 except Exception:
531 print("Error")
532 traceback.print_exc()
533 interrupt_arg = {"aborted": False}
534 interrupt_timer = Timer(stop_delay, post_interrupt_task, [interrupt_arg])
535 interrupt_timer.start()
536 ignore_events = False
537
538
539 # Runs on stop events and posts run_generator to the
540 # main queue so it can continue execution
541 def stop_handler(event):
542 if ignore_events:
543 return
544 bound_run_generator = partial(run_generator, event)
545 gdb.post_event(bound_run_generator)
546 gdb.events.stop.connect(stop_handler)
547
548 # Start testing
549 bound_run_generator = partial(run_generator, None)
550 gdb.post_event(bound_run_generator)