|
| 1 | +import re |
| 2 | +import sys |
| 3 | +import textwrap |
| 4 | +import unittest |
| 5 | +from dataclasses import dataclass |
| 6 | +from functools import cache |
| 7 | +from test import support |
| 8 | +from test.support.script_helper import run_python_until_end |
| 9 | + |
| 10 | +_strace_binary = "/usr/bin/strace" |
| 11 | +_syscall_regex = re.compile( |
| 12 | + r"(?P<syscall>[^(]*)\((?P<args>[^)]*)\)\s*[=]\s*(?P<returncode>.+)") |
| 13 | +_returncode_regex = re.compile( |
| 14 | + br"\+\+\+ exited with (?P<returncode>\d+) \+\+\+") |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class StraceEvent: |
| 19 | + syscall: str |
| 20 | + args: list[str] |
| 21 | + returncode: str |
| 22 | + |
| 23 | + |
| 24 | +@dataclass |
| 25 | +class StraceResult: |
| 26 | + strace_returncode: int |
| 27 | + python_returncode: int |
| 28 | + |
| 29 | + """The event messages generated by strace. This is very similar to the |
| 30 | + stderr strace produces with returncode marker section removed.""" |
| 31 | + event_bytes: bytes |
| 32 | + stdout: bytes |
| 33 | + stderr: bytes |
| 34 | + |
| 35 | + def events(self): |
| 36 | + """Parse event_bytes data into system calls for easier processing. |
| 37 | +
|
| 38 | + This assumes the program under inspection doesn't print any non-utf8 |
| 39 | + strings which would mix into the strace output.""" |
| 40 | + decoded_events = self.event_bytes.decode('utf-8') |
| 41 | + matches = [ |
| 42 | + _syscall_regex.match(event) |
| 43 | + for event in decoded_events.splitlines() |
| 44 | + ] |
| 45 | + return [ |
| 46 | + StraceEvent(match["syscall"], |
| 47 | + [arg.strip() for arg in (match["args"].split(","))], |
| 48 | + match["returncode"]) for match in matches if match |
| 49 | + ] |
| 50 | + |
| 51 | + def sections(self): |
| 52 | + """Find all "MARK <X>" writes and use them to make groups of events. |
| 53 | +
|
| 54 | + This is useful to avoid variable / overhead events, like those at |
| 55 | + interpreter startup or when opening a file so a test can verify just |
| 56 | + the small case under study.""" |
| 57 | + current_section = "__startup" |
| 58 | + sections = {current_section: []} |
| 59 | + for event in self.events(): |
| 60 | + if event.syscall == 'write' and len( |
| 61 | + event.args) > 2 and event.args[1].startswith("\"MARK "): |
| 62 | + # Found a new section, don't include the write in the section |
| 63 | + # but all events until next mark should be in that section |
| 64 | + current_section = event.args[1].split( |
| 65 | + " ", 1)[1].removesuffix('\\n"') |
| 66 | + if current_section not in sections: |
| 67 | + sections[current_section] = list() |
| 68 | + else: |
| 69 | + sections[current_section].append(event) |
| 70 | + |
| 71 | + return sections |
| 72 | + |
| 73 | + |
| 74 | +@support.requires_subprocess() |
| 75 | +def strace_python(code, strace_flags, check=True): |
| 76 | + """Run strace and return the trace. |
| 77 | +
|
| 78 | + Sets strace_returncode and python_returncode to `-1` on error.""" |
| 79 | + res = None |
| 80 | + |
| 81 | + def _make_error(reason, details): |
| 82 | + return StraceResult( |
| 83 | + strace_returncode=-1, |
| 84 | + python_returncode=-1, |
| 85 | + event_bytes=f"error({reason},details={details}) = -1".encode('utf-8'), |
| 86 | + stdout=res.out if res else b"", |
| 87 | + stderr=res.err if res else b"") |
| 88 | + |
| 89 | + # Run strace, and get out the raw text |
| 90 | + try: |
| 91 | + res, cmd_line = run_python_until_end( |
| 92 | + "-c", |
| 93 | + textwrap.dedent(code), |
| 94 | + __run_using_command=[_strace_binary] + strace_flags) |
| 95 | + except OSError as err: |
| 96 | + return _make_error("Caught OSError", err) |
| 97 | + |
| 98 | + if check and res.rc: |
| 99 | + res.fail(cmd_line) |
| 100 | + |
| 101 | + # Get out program returncode |
| 102 | + stripped = res.err.strip() |
| 103 | + output = stripped.rsplit(b"\n", 1) |
| 104 | + if len(output) != 2: |
| 105 | + return _make_error("Expected strace events and exit code line", |
| 106 | + stripped[-50:]) |
| 107 | + |
| 108 | + returncode_match = _returncode_regex.match(output[1]) |
| 109 | + if not returncode_match: |
| 110 | + return _make_error("Expected to find returncode in last line.", |
| 111 | + output[1][:50]) |
| 112 | + |
| 113 | + python_returncode = int(returncode_match["returncode"]) |
| 114 | + if check and python_returncode: |
| 115 | + res.fail(cmd_line) |
| 116 | + |
| 117 | + return StraceResult(strace_returncode=res.rc, |
| 118 | + python_returncode=python_returncode, |
| 119 | + event_bytes=output[0], |
| 120 | + stdout=res.out, |
| 121 | + stderr=res.err) |
| 122 | + |
| 123 | + |
| 124 | +def get_events(code, strace_flags, prelude, cleanup): |
| 125 | + # NOTE: The flush is currently required to prevent the prints from getting |
| 126 | + # buffered and done all at once at exit |
| 127 | + prelude = textwrap.dedent(prelude) |
| 128 | + code = textwrap.dedent(code) |
| 129 | + cleanup = textwrap.dedent(cleanup) |
| 130 | + to_run = f""" |
| 131 | +print("MARK prelude", flush=True) |
| 132 | +{prelude} |
| 133 | +print("MARK code", flush=True) |
| 134 | +{code} |
| 135 | +print("MARK cleanup", flush=True) |
| 136 | +{cleanup} |
| 137 | +print("MARK __shutdown", flush=True) |
| 138 | + """ |
| 139 | + trace = strace_python(to_run, strace_flags) |
| 140 | + all_sections = trace.sections() |
| 141 | + return all_sections['code'] |
| 142 | + |
| 143 | + |
| 144 | +def get_syscalls(code, strace_flags, prelude="", cleanup=""): |
| 145 | + """Get the syscalls which a given chunk of python code generates""" |
| 146 | + events = get_events(code, strace_flags, prelude=prelude, cleanup=cleanup) |
| 147 | + return [ev.syscall for ev in events] |
| 148 | + |
| 149 | + |
| 150 | +# Moderately expensive (spawns a subprocess), so share results when possible. |
| 151 | +@cache |
| 152 | +def _can_strace(): |
| 153 | + res = strace_python("import sys; sys.exit(0)", [], check=False) |
| 154 | + assert res.events(), "Should have parsed multiple calls" |
| 155 | + |
| 156 | + return res.strace_returncode == 0 and res.python_returncode == 0 |
| 157 | + |
| 158 | + |
| 159 | +def requires_strace(): |
| 160 | + if sys.platform != "linux": |
| 161 | + return unittest.skip("Linux only, requires strace.") |
| 162 | + |
| 163 | + if support.check_sanitizer(address=True, memory=True): |
| 164 | + return unittest.skip("LeakSanitizer does not work under ptrace (strace, gdb, etc)") |
| 165 | + |
| 166 | + return unittest.skipUnless(_can_strace(), "Requires working strace") |
| 167 | + |
| 168 | + |
| 169 | +__all__ = ["get_events", "get_syscalls", "requires_strace", "strace_python", |
| 170 | + "StraceEvent", "StraceResult"] |
0 commit comments