Debian Codegraph @

Lib/test/test_gdb/util.py

raw
1 import os
2 import re
3 import shlex
4 import shutil
5 import subprocess
6 import sys
7 import sysconfig
8 import unittest
9 from test import support
10 from test.support.testcase import ExtraAssertions
11
12
13 GDB_PROGRAM = shutil.which('gdb') or 'gdb'
14
15 # Location of custom hooks file in a repository checkout.
16 CHECKOUT_HOOK_PATH = os.path.join(os.path.dirname(sys.executable),
17 'python-gdb.py')
18
19 SAMPLE_SCRIPT = os.path.join(os.path.dirname(__file__), 'gdb_sample.py')
20 BREAKPOINT_FN = 'builtin_id'
21
22 PYTHONHASHSEED = '123'
23
24
25 def clean_environment():
26 # Remove PYTHON* environment variables such as PYTHONHOME
27 return {name: value for name, value in os.environ.items()
28 if not name.startswith('PYTHON')}
29
30
31 # Temporary value until it's initialized by get_gdb_version() below
32 GDB_VERSION = (0, 0)
33
34 def run_gdb(*args, exitcode=0, check=True, **env_vars):
35 """Runs gdb in --batch mode with the additional arguments given by *args.
36
37 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
38 """
39 env = clean_environment()
40 if env_vars:
41 env.update(env_vars)
42
43 cmd = [GDB_PROGRAM,
44 # Batch mode: Exit after processing all the command files
45 # specified with -x/--command
46 '--batch',
47 # -nx: Do not execute commands from any .gdbinit initialization
48 # files (gh-66384)
49 '-nx']
50 if GDB_VERSION >= (7, 4):
51 cmd.extend(('--init-eval-command',
52 f'add-auto-load-safe-path {CHECKOUT_HOOK_PATH}'))
53 cmd.extend(args)
54
55 proc = subprocess.run(
56 cmd,
57 # Redirect stdin to prevent gdb from messing with the terminal settings
58 stdin=subprocess.PIPE,
59 stdout=subprocess.PIPE,
60 stderr=subprocess.PIPE,
61 encoding="utf8", errors="backslashreplace",
62 env=env)
63
64 stdout = proc.stdout
65 stderr = proc.stderr
66 if check and proc.returncode != exitcode:
67 cmd_text = shlex.join(cmd)
68 raise Exception(f"{cmd_text} failed with exit code {proc.returncode}, "
69 f"expected exit code {exitcode}:\n"
70 f"stdout={stdout!r}\n"
71 f"stderr={stderr!r}")
72
73 return (stdout, stderr)
74
75
76 def get_gdb_version():
77 try:
78 stdout, stderr = run_gdb('--version')
79 except OSError as exc:
80 # This is what "no gdb" looks like. There may, however, be other
81 # errors that manifest this way too.
82 raise unittest.SkipTest(f"Couldn't find gdb program on the path: {exc}")
83
84 # Regex to parse:
85 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
86 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
87 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
88 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
89 # 'HP gdb 6.7 for HP Itanium (32 or 64 bit) and target HP-UX 11iv2 and 11iv3.\n' -> 6.7
90 match = re.search(r"^(?:GNU|HP) gdb.*?\b(\d+)\.(\d+)", stdout)
91 if match is None:
92 raise Exception("unable to parse gdb version: %r" % stdout)
93 version_text = stdout
94 major = int(match.group(1))
95 minor = int(match.group(2))
96 version = (major, minor)
97 return (version_text, version)
98
99 GDB_VERSION_TEXT, GDB_VERSION = get_gdb_version()
100 if GDB_VERSION < (7, 0):
101 raise unittest.SkipTest(
102 f"gdb versions before 7.0 didn't support python embedding. "
103 f"Saw gdb version {GDB_VERSION[0]}.{GDB_VERSION[1]}:\n"
104 f"{GDB_VERSION_TEXT}")
105
106
107 def check_usable_gdb():
108 # Verify that "gdb" was built with the embedded Python support enabled and
109 # verify that "gdb" can load our custom hooks, as OS security settings may
110 # disallow this without a customized .gdbinit.
111 stdout, stderr = run_gdb(
112 '--eval-command=python import sys; print(sys.version_info)',
113 '--args', sys.executable,
114 check=False)
115
116 if "auto-loading has been declined" in stderr:
117 raise unittest.SkipTest(
118 f"gdb security settings prevent use of custom hooks; "
119 f"stderr: {stderr!r}")
120
121 if not stdout:
122 raise unittest.SkipTest(
123 f"gdb not built with embedded python support; "
124 f"stderr: {stderr!r}")
125
126 if "major=2" in stdout:
127 raise unittest.SkipTest("gdb built with Python 2")
128
129 check_usable_gdb()
130
131
132 # Control-flow enforcement technology
133 def cet_protection():
134 cflags = sysconfig.get_config_var('CFLAGS')
135 if not cflags:
136 return False
137 flags = cflags.split()
138 # True if "-mcet -fcf-protection" options are found, but false
139 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
140 return (('-mcet' in flags)
141 and any((flag.startswith('-fcf-protection')
142 and not flag.endswith(("=none", "=return")))
143 for flag in flags))
144 CET_PROTECTION = cet_protection()
145
146
147 def setup_module():
148 if support.verbose:
149 print(f"gdb version {GDB_VERSION[0]}.{GDB_VERSION[1]}:")
150 for line in GDB_VERSION_TEXT.splitlines():
151 print(" " * 4 + line)
152 print(f" path: {GDB_PROGRAM}")
153 print()
154
155
156 class DebuggerTests(unittest.TestCase, ExtraAssertions):
157
158 """Test that the debugger can debug Python."""
159
160 def get_stack_trace(self, source=None, script=None,
161 breakpoint=BREAKPOINT_FN,
162 cmds_after_breakpoint=None,
163 import_site=False,
164 ignore_stderr=False):
165 '''
166 Run 'python -c SOURCE' under gdb with a breakpoint.
167
168 Support injecting commands after the breakpoint is reached
169
170 Returns the stdout from gdb
171
172 cmds_after_breakpoint: if provided, a list of strings: gdb commands
173 '''
174 # We use "set breakpoint pending yes" to avoid blocking with a:
175 # Function "foo" not defined.
176 # Make breakpoint pending on future shared library load? (y or [n])
177 # error, which typically happens python is dynamically linked (the
178 # breakpoints of interest are to be found in the shared library)
179 # When this happens, we still get:
180 # Function "textiowrapper_write" not defined.
181 # emitted to stderr each time, alas.
182
183 # Initially I had "--eval-command=continue" here, but removed it to
184 # avoid repeated print breakpoints when traversing hierarchical data
185 # structures
186
187 # Generate a list of commands in gdb's language:
188 commands = [
189 'set breakpoint pending yes',
190 'break %s' % breakpoint,
191
192 # The tests assume that the first frame of printed
193 # backtrace will not contain program counter,
194 # that is however not guaranteed by gdb
195 # therefore we need to use 'set print address off' to
196 # make sure the counter is not there. For example:
197 # #0 in PyObject_Print ...
198 # is assumed, but sometimes this can be e.g.
199 # #0 0x00003fffb7dd1798 in PyObject_Print ...
200 'set print address off',
201
202 'run',
203 ]
204
205 # GDB as of 7.4 onwards can distinguish between the
206 # value of a variable at entry vs current value:
207 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
208 # which leads to the selftests failing with errors like this:
209 # AssertionError: 'v@entry=()' != '()'
210 # Disable this:
211 if GDB_VERSION >= (7, 4):
212 commands += ['set print entry-values no']
213
214 if cmds_after_breakpoint:
215 if CET_PROTECTION:
216 # bpo-32962: When Python is compiled with -mcet
217 # -fcf-protection, function arguments are unusable before
218 # running the first instruction of the function entry point.
219 # The 'next' command makes the required first step.
220 commands += ['next']
221 commands += cmds_after_breakpoint
222 else:
223 commands += ['backtrace']
224
225 # print commands
226
227 # Use "commands" to generate the arguments with which to invoke "gdb":
228 args = ['--eval-command=%s' % cmd for cmd in commands]
229 args += ["--args",
230 sys.executable]
231 args.extend(subprocess._args_from_interpreter_flags())
232
233 if not import_site:
234 # -S suppresses the default 'import site'
235 args += ["-S"]
236
237 if source:
238 args += ["-c", source]
239 elif script:
240 args += [script]
241
242 # Use "args" to invoke gdb, capturing stdout, stderr:
243 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
244
245 if not ignore_stderr:
246 for line in err.splitlines():
247 print(line, file=sys.stderr)
248
249 # bpo-34007: Sometimes some versions of the shared libraries that
250 # are part of the traceback are compiled in optimised mode and the
251 # Program Counter (PC) is not present, not allowing gdb to walk the
252 # frames back. When this happens, the Python bindings of gdb raise
253 # an exception, making the test impossible to succeed.
254 if "PC not saved" in err:
255 raise unittest.SkipTest("gdb cannot walk the frame object"
256 " because the Program Counter is"
257 " not present")
258
259 # bpo-40019: Skip the test if gdb failed to read debug information
260 # because the Python binary is optimized.
261 for pattern in (
262 '(frame information optimized out)',
263 'Unable to read information on python frame',
264
265 # gh-91960: On Python built with "clang -Og", gdb gets
266 # "frame=<optimized out>" for _PyEval_EvalFrameDefault() parameter
267 '(unable to read python frame information)',
268
269 # gh-104736: On Python built with "clang -Og" on ppc64le,
270 # "py-bt" displays a truncated or not traceback, but "where"
271 # logs this error message:
272 'Backtrace stopped: frame did not save the PC',
273
274 # gh-104736: When "bt" command displays something like:
275 # "#1 0x0000000000000000 in ?? ()", the traceback is likely
276 # truncated or wrong.
277 ' ?? ()',
278 ):
279 if pattern in out:
280 raise unittest.SkipTest(f"{pattern!r} found in gdb output")
281
282 return out
283
284 def assertMultilineMatches(self, actual, pattern):
285 m = re.match(pattern, actual, re.DOTALL)
286 if not m:
287 self.fail(msg='%r did not match %r' % (actual, pattern))