Debian Codegraph @

test/debug_context_test.py

raw symbols SCIP
1 # pyOCD debugger
2 # Copyright (c) 2019-2020,2025 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 import argparse
18 import os
19 import sys
20 import traceback
21 import logging
22 from unittest import mock
23
24 from pyocd.core.helpers import ConnectHelper
25 from pyocd.flash.file_programmer import FileProgrammer
26 from pyocd.probe.pydapaccess import DAPAccess
27 from pyocd.utility import conversion
28 from pyocd.utility.mask import same
29 from pyocd.core.memory_map import MemoryType
30 from pyocd.debug.elf.elf_reader import ElfReaderContext
31
32 from test_util import (
33 Test,
34 TestResult,
35 get_session_options,
36 get_target_test_params,
37 get_test_binary_path,
38 PYOCD_DIR,
39 binary_to_elf_file,
40 )
41
42 GDB_TEST_BIN = "src/gdb_test_program/gdb_test.bin"
43 GDB_TEST_ELF = "src/gdb_test_program/gdb_test.elf"
44
45 class DebugContextTestResult(TestResult):
46 def __init__(self):
47 super(DebugContextTestResult, self).__init__(None, None, None)
48 self.name = "debug_context"
49
50 class DebugContextTest(Test):
51 def __init__(self):
52 super(DebugContextTest, self).__init__("Debug Context Test", debug_context_test)
53
54 def run(self, board):
55 try:
56 result = self.test_function(board.unique_id)
57 except Exception as e:
58 result = DebugContextTestResult()
59 result.passed = False
60 print("Exception %s when testing board %s" % (e, board.unique_id))
61 traceback.print_exc(file=sys.stdout)
62 result.board = board
63 result.test = self
64 return result
65
66 def debug_context_test(board_id):
67 with ConnectHelper.session_with_chosen_probe(unique_id=board_id, **get_session_options()) as session:
68 board = session.board
69 target = session.target
70
71 test_params = get_target_test_params(session)
72 session.probe.set_clock(test_params['test_clock'])
73
74 memory_map = target.get_memory_map()
75 boot_region = memory_map.get_boot_memory()
76 ram_region = memory_map.get_default_region_of_type(MemoryType.RAM)
77 ram_base = ram_region.start
78 binary_file = get_test_binary_path(board.test_binary)
79 gdb_test_binary_file = os.path.join(PYOCD_DIR, GDB_TEST_BIN)
80
81 # Read the gdb test binary file.
82 with open(gdb_test_binary_file, "rb") as f:
83 gdb_test_binary_data = list(bytearray(f.read()))
84
85 # Read the test binary file.
86 with open(binary_file, "rb") as f:
87 test_binary_data = bytearray(f.read())
88 test_binary_data_length = len(test_binary_data)
89
90 # Generate ELF file from the binary test file.
91 temp_test_elf_name = binary_to_elf_file(binary_file, boot_region.start)
92
93 test_pass_count = 0
94 test_count = 0
95 result = DebugContextTestResult()
96
97 target.reset_and_halt()
98
99 # Reproduce a gdbserver failure.
100 print("\n------ Test 1: Mem cache ------")
101
102 ctx = target.get_target_context()
103
104 print("Writing gdb test binary")
105 ctx.write_memory_block8(ram_base, gdb_test_binary_data)
106
107 print("Reading first chunk")
108 data = ctx.read_memory_block8(ram_base, 64)
109 if data == gdb_test_binary_data[:64]:
110 test_pass_count += 1
111 print("TEST PASSED")
112 else:
113 print("TEST FAILED")
114 test_count += 1
115
116 print("Reading N chunks")
117 did_pass = True
118 for n in range(8):
119 offset = 0x7e + (4 * n)
120 data = ctx.read_memory_block8(ram_base + offset, 4)
121 if data == gdb_test_binary_data[offset:offset + 4]:
122 test_pass_count += 1
123 else:
124 did_pass = False
125 test_count += 1
126 if did_pass:
127 print("TEST PASSED")
128 else:
129 print("TEST FAILED")
130
131 # Force a memory cache clear.
132 target.step()
133
134 # ELF reader test goals:
135 # 1. Verify correct data is read without accessing the target memory.
136 # 2. Test null interval failure.
137 #
138 print("\n------ Test 2: ELF reader ------")
139
140 # Set the elf on the target, which will add a context to read from the elf.
141 target.elf = temp_test_elf_name
142 ctx = target.get_target_context()
143
144 print("Check that ElfReaderContext was created")
145 if isinstance(ctx, ElfReaderContext):
146 test_pass_count += 1
147 print("TEST PASSED")
148 else:
149 print("TEST FAILED")
150 test_count += 1
151
152 # Program the test binary.
153 print("Programming test binary to boot memory")
154 target.reset_and_halt()
155 FileProgrammer(session).program(binary_file, base_address=boot_region.start)
156
157 with mock.patch.object(target.selected_core, 'read_memory_block32') as read_block32_mock:
158 test_len = min(4096, test_binary_data_length)
159 print("Reading %d bytes of test binary from context." % test_len)
160 data = ctx.read_memory_block32(boot_region.start, test_len // 4)
161 data = conversion.u32le_list_to_byte_list(data)
162 if same(data, test_binary_data[:test_len]):
163 print("PASSED: expected data returned")
164 test_pass_count += 1
165 else:
166 print("FAILED: unexpected data")
167 test_count += 1
168
169 # Verify the target memory wasn't accessed.
170 try:
171 read_block32_mock.assert_not_called()
172 except AssertionError:
173 print("FAILED: target memory was accessed")
174 else:
175 print("PASSED: target memory was not accessed")
176 test_pass_count += 1
177 test_count += 1
178
179 print("\nTest Summary:")
180 print("Pass count %i of %i tests" % (test_pass_count, test_count))
181 if test_pass_count == test_count:
182 print("DEBUG CONTEXT TEST PASSED")
183 else:
184 print("DEBUG CONTEXT TEST FAILED")
185
186 # Clean up.
187 target.reset()
188
189 result.passed = test_count == test_pass_count
190 return result
191
192 if __name__ == "__main__":
193 parser = argparse.ArgumentParser(description='pyOCD debug context test')
194 parser.add_argument('-d', '--debug', action="store_true", help='Enable debug logging')
195 parser.add_argument("-da", "--daparg", dest="daparg", nargs='+', help="Send setting to DAPAccess layer.")
196 args = parser.parse_args()
197 level = logging.DEBUG if args.debug else logging.INFO
198 logging.basicConfig(level=level)
199 DAPAccess.set_args(args.daparg)
200 # Set to debug to print some of the decisions made while flashing
201 session = ConnectHelper.session_with_chosen_probe(**get_session_options())
202 test = DebugContextTest()
203 result = [test.run(session.board)]