Debian Codegraph @

Lib/test/test_perf_profiler.py

raw
1 import unittest
2 import string
3 import subprocess
4 import sys
5 import sysconfig
6 import os
7 import pathlib
8 import shutil
9 from test import support
10 from test.support.script_helper import (
11 make_script,
12 assert_python_failure,
13 assert_python_ok,
14 )
15 from test.support.os_helper import temp_dir
16
17
18 if not support.has_subprocess_support:
19 raise unittest.SkipTest("test module requires subprocess")
20
21 if support.check_sanitizer(address=True, memory=True, ub=True):
22 # gh-109580: Skip the test because it does crash randomly if Python is
23 # built with ASAN.
24 raise unittest.SkipTest("test crash randomly on ASAN/MSAN/UBSAN build")
25
26
27 def supports_trampoline_profiling():
28 perf_trampoline = sysconfig.get_config_var("PY_HAVE_PERF_TRAMPOLINE")
29 if not perf_trampoline:
30 return False
31 return int(perf_trampoline) == 1
32
33
34 if not supports_trampoline_profiling():
35 raise unittest.SkipTest("perf trampoline profiling not supported")
36
37
38 class TestPerfTrampoline(unittest.TestCase):
39 def setUp(self):
40 super().setUp()
41 self.perf_files = set(pathlib.Path("/tmp/").glob("perf-*.map"))
42
43 def tearDown(self) -> None:
44 super().tearDown()
45 files_to_delete = (
46 set(pathlib.Path("/tmp/").glob("perf-*.map")) - self.perf_files
47 )
48 for file in files_to_delete:
49 file.unlink()
50
51 def test_trampoline_works(self):
52 code = """if 1:
53 def foo():
54 pass
55
56 def bar():
57 foo()
58
59 def baz():
60 bar()
61
62 baz()
63 """
64 with temp_dir() as script_dir:
65 script = make_script(script_dir, "perftest", code)
66 with subprocess.Popen(
67 [sys.executable, "-Xperf", script],
68 text=True,
69 stderr=subprocess.PIPE,
70 stdout=subprocess.PIPE,
71 ) as process:
72 stdout, stderr = process.communicate()
73
74 self.assertEqual(stderr, "")
75 self.assertEqual(stdout, "")
76
77 perf_file = pathlib.Path(f"/tmp/perf-{process.pid}.map")
78 self.assertTrue(perf_file.exists())
79 perf_file_contents = perf_file.read_text()
80 perf_lines = perf_file_contents.splitlines()
81 expected_symbols = [
82 f"py::foo:{script}",
83 f"py::bar:{script}",
84 f"py::baz:{script}",
85 ]
86 for expected_symbol in expected_symbols:
87 perf_line = next(
88 (line for line in perf_lines if expected_symbol in line), None
89 )
90 self.assertIsNotNone(
91 perf_line, f"Could not find {expected_symbol} in perf file"
92 )
93 perf_addr = perf_line.split(" ")[0]
94 self.assertFalse(
95 perf_addr.startswith("0x"), "Address should not be prefixed with 0x"
96 )
97 self.assertTrue(
98 set(perf_addr).issubset(string.hexdigits),
99 "Address should contain only hex characters",
100 )
101
102 def test_trampoline_works_with_forks(self):
103 code = """if 1:
104 import os, sys
105
106 def foo_fork():
107 pass
108
109 def bar_fork():
110 foo_fork()
111
112 def baz_fork():
113 bar_fork()
114
115 def foo():
116 pid = os.fork()
117 if pid == 0:
118 print(os.getpid())
119 baz_fork()
120 else:
121 _, status = os.waitpid(-1, 0)
122 sys.exit(status)
123
124 def bar():
125 foo()
126
127 def baz():
128 bar()
129
130 baz()
131 """
132 with temp_dir() as script_dir:
133 script = make_script(script_dir, "perftest", code)
134 with subprocess.Popen(
135 [sys.executable, "-Xperf", script],
136 text=True,
137 stderr=subprocess.PIPE,
138 stdout=subprocess.PIPE,
139 ) as process:
140 stdout, stderr = process.communicate()
141
142 self.assertEqual(process.returncode, 0)
143 self.assertEqual(stderr, "")
144 child_pid = int(stdout.strip())
145 perf_file = pathlib.Path(f"/tmp/perf-{process.pid}.map")
146 perf_child_file = pathlib.Path(f"/tmp/perf-{child_pid}.map")
147 self.assertTrue(perf_file.exists())
148 self.assertTrue(perf_child_file.exists())
149
150 perf_file_contents = perf_file.read_text()
151 self.assertIn(f"py::foo:{script}", perf_file_contents)
152 self.assertIn(f"py::bar:{script}", perf_file_contents)
153 self.assertIn(f"py::baz:{script}", perf_file_contents)
154
155 child_perf_file_contents = perf_child_file.read_text()
156 self.assertIn(f"py::foo_fork:{script}", child_perf_file_contents)
157 self.assertIn(f"py::bar_fork:{script}", child_perf_file_contents)
158 self.assertIn(f"py::baz_fork:{script}", child_perf_file_contents)
159
160 # The parent's map should not contain the child's symbols.
161 self.assertNotIn(f"py::foo_fork:{script}", perf_file_contents)
162 self.assertNotIn(f"py::bar_fork:{script}", perf_file_contents)
163 self.assertNotIn(f"py::baz_fork:{script}", perf_file_contents)
164
165 # The child's map should not contain the parent's symbols.
166 self.assertNotIn(f"py::foo:{script}", child_perf_file_contents)
167 self.assertNotIn(f"py::bar:{script}", child_perf_file_contents)
168 self.assertNotIn(f"py::baz:{script}", child_perf_file_contents)
169
170 def test_sys_api(self):
171 code = """if 1:
172 import sys
173 def foo():
174 pass
175
176 def spam():
177 pass
178
179 def bar():
180 sys.deactivate_stack_trampoline()
181 foo()
182 sys.activate_stack_trampoline("perf")
183 spam()
184
185 def baz():
186 bar()
187
188 sys.activate_stack_trampoline("perf")
189 baz()
190 """
191 with temp_dir() as script_dir:
192 script = make_script(script_dir, "perftest", code)
193 with subprocess.Popen(
194 [sys.executable, script],
195 text=True,
196 stderr=subprocess.PIPE,
197 stdout=subprocess.PIPE,
198 ) as process:
199 stdout, stderr = process.communicate()
200
201 self.assertEqual(stderr, "")
202 self.assertEqual(stdout, "")
203
204 perf_file = pathlib.Path(f"/tmp/perf-{process.pid}.map")
205 self.assertTrue(perf_file.exists())
206 perf_file_contents = perf_file.read_text()
207 self.assertNotIn(f"py::foo:{script}", perf_file_contents)
208 self.assertIn(f"py::spam:{script}", perf_file_contents)
209 self.assertIn(f"py::bar:{script}", perf_file_contents)
210 self.assertIn(f"py::baz:{script}", perf_file_contents)
211
212 def test_sys_api_with_existing_trampoline(self):
213 code = """if 1:
214 import sys
215 sys.activate_stack_trampoline("perf")
216 sys.activate_stack_trampoline("perf")
217 """
218 assert_python_ok("-c", code)
219
220 def test_sys_api_with_invalid_trampoline(self):
221 code = """if 1:
222 import sys
223 sys.activate_stack_trampoline("invalid")
224 """
225 rc, out, err = assert_python_failure("-c", code)
226 self.assertIn("invalid backend: invalid", err.decode())
227
228 def test_sys_api_get_status(self):
229 code = """if 1:
230 import sys
231 sys.activate_stack_trampoline("perf")
232 assert sys.is_stack_trampoline_active() is True
233 sys.deactivate_stack_trampoline()
234 assert sys.is_stack_trampoline_active() is False
235 """
236 assert_python_ok("-c", code)
237
238 def test_sys_api_perf_jit_backend(self):
239 code = """if 1:
240 import sys
241 sys.activate_stack_trampoline("perf_jit")
242 assert sys.is_stack_trampoline_active() is True
243 sys.deactivate_stack_trampoline()
244 assert sys.is_stack_trampoline_active() is False
245 """
246 assert_python_ok("-c", code, PYTHON_JIT="0")
247
248 def test_sys_api_with_existing_perf_jit_trampoline(self):
249 code = """if 1:
250 import sys
251 sys.activate_stack_trampoline("perf_jit")
252 sys.activate_stack_trampoline("perf_jit")
253 """
254 assert_python_ok("-c", code, PYTHON_JIT="0")
255
256
257 def is_unwinding_reliable_with_frame_pointers():
258 cflags = sysconfig.get_config_var("PY_CORE_CFLAGS")
259 if not cflags:
260 return False
261 return "no-omit-frame-pointer" in cflags and "_Py_JIT" not in cflags
262
263
264 def perf_command_works():
265 try:
266 cmd = ["perf", "--help"]
267 stdout = subprocess.check_output(cmd, text=True)
268 except (subprocess.SubprocessError, OSError):
269 return False
270
271 # perf version does not return a version number on Fedora. Use presence
272 # of "perf.data" in help as indicator that it's perf from Linux tools.
273 if "perf.data" not in stdout:
274 return False
275
276 # Check that we can run a simple perf run
277 with temp_dir() as script_dir:
278 try:
279 output_file = script_dir + "/perf_output.perf"
280 cmd = (
281 "perf",
282 "record",
283 "--no-buildid",
284 "--no-buildid-cache",
285 "-g",
286 "--call-graph=fp",
287 "-o",
288 output_file,
289 "--",
290 sys.executable,
291 "-c",
292 'print("hello")',
293 )
294 stdout = subprocess.check_output(
295 cmd, cwd=script_dir, text=True, stderr=subprocess.STDOUT
296 )
297 except (subprocess.SubprocessError, OSError):
298 return False
299
300 if "hello" not in stdout:
301 return False
302
303 return True
304
305
306 def run_perf(cwd, *args, use_jit=False, **env_vars):
307 if env_vars:
308 env = os.environ.copy()
309 env.update(env_vars)
310 else:
311 env = None
312 output_file = cwd + "/perf_output.perf"
313 if not use_jit:
314 base_cmd = (
315 "perf",
316 "record",
317 "--no-buildid",
318 "--no-buildid-cache",
319 "-g",
320 "--call-graph=fp",
321 "-o", output_file,
322 "--"
323 )
324 else:
325 base_cmd = (
326 "perf",
327 "record",
328 "--no-buildid",
329 "--no-buildid-cache",
330 "-g",
331 "--call-graph=dwarf,65528",
332 "-F99",
333 "-k1",
334 "-o",
335 output_file,
336 "--",
337 )
338 proc = subprocess.run(
339 base_cmd + args,
340 stdout=subprocess.PIPE,
341 stderr=subprocess.PIPE,
342 env=env,
343 text=True,
344 )
345 if proc.returncode:
346 print(proc.stderr, file=sys.stderr)
347 raise ValueError(f"Perf failed with return code {proc.returncode}")
348
349 if use_jit:
350 jit_output_file = cwd + "/jit_output.dump"
351 command = ("perf", "inject", "-j", "-i", output_file, "-o", jit_output_file)
352 proc = subprocess.run(
353 command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True
354 )
355 if proc.returncode:
356 print(proc.stderr, file=sys.stderr)
357 raise ValueError(f"Perf failed with return code {proc.returncode}")
358 # Copy the jit_output_file to the output_file
359 os.rename(jit_output_file, output_file)
360
361 base_cmd = ("perf", "script")
362 proc = subprocess.run(
363 ("perf", "script", "-i", output_file),
364 stdout=subprocess.PIPE,
365 stderr=subprocess.PIPE,
366 env=env,
367 check=True,
368 text=True,
369 )
370 return proc.stdout, proc.stderr
371
372
373 class TestPerfProfilerMixin:
374 def run_perf(self, script_dir, perf_mode, script):
375 raise NotImplementedError()
376
377 def test_python_calls_appear_in_the_stack_if_perf_activated(self):
378 with temp_dir() as script_dir:
379 code = """if 1:
380 def foo(n):
381 x = 0
382 for i in range(n):
383 x += i
384
385 def bar(n):
386 foo(n)
387
388 def baz(n):
389 bar(n)
390
391 baz(10000000)
392 """
393 script = make_script(script_dir, "perftest", code)
394 stdout, stderr = self.run_perf(script_dir, script)
395 self.assertEqual(stderr, "")
396
397 self.assertIn(f"py::foo:{script}", stdout)
398 self.assertIn(f"py::bar:{script}", stdout)
399 self.assertIn(f"py::baz:{script}", stdout)
400
401 def test_python_calls_do_not_appear_in_the_stack_if_perf_deactivated(self):
402 with temp_dir() as script_dir:
403 code = """if 1:
404 def foo(n):
405 x = 0
406 for i in range(n):
407 x += i
408
409 def bar(n):
410 foo(n)
411
412 def baz(n):
413 bar(n)
414
415 baz(10000000)
416 """
417 script = make_script(script_dir, "perftest", code)
418 stdout, stderr = self.run_perf(
419 script_dir, script, activate_trampoline=False
420 )
421 self.assertEqual(stderr, "")
422
423 self.assertNotIn(f"py::foo:{script}", stdout)
424 self.assertNotIn(f"py::bar:{script}", stdout)
425 self.assertNotIn(f"py::baz:{script}", stdout)
426
427 @unittest.skipUnless(perf_command_works(), "perf command doesn't work")
428 @unittest.skipUnless(
429 is_unwinding_reliable_with_frame_pointers(),
430 "Unwinding is unreliable with frame pointers",
431 )
432 class TestPerfProfiler(unittest.TestCase, TestPerfProfilerMixin):
433 def run_perf(self, script_dir, script, activate_trampoline=True):
434 if activate_trampoline:
435 return run_perf(script_dir, sys.executable, "-Xperf", script)
436 return run_perf(script_dir, sys.executable, script)
437
438 def setUp(self):
439 super().setUp()
440 self.perf_files = set(pathlib.Path("/tmp/").glob("perf-*.map"))
441
442 def tearDown(self) -> None:
443 super().tearDown()
444 files_to_delete = (
445 set(pathlib.Path("/tmp/").glob("perf-*.map")) - self.perf_files
446 )
447 for file in files_to_delete:
448 file.unlink()
449
450 def test_pre_fork_compile(self):
451 code = """if 1:
452 import sys
453 import os
454 import sysconfig
455 from _testinternalcapi import (
456 compile_perf_trampoline_entry,
457 perf_trampoline_set_persist_after_fork,
458 )
459
460 def foo_fork():
461 pass
462
463 def bar_fork():
464 foo_fork()
465
466 def foo():
467 import time; time.sleep(1)
468
469 def bar():
470 foo()
471
472 def compile_trampolines_for_all_functions():
473 perf_trampoline_set_persist_after_fork(1)
474 for _, obj in globals().items():
475 if callable(obj) and hasattr(obj, '__code__'):
476 compile_perf_trampoline_entry(obj.__code__)
477
478 if __name__ == "__main__":
479 compile_trampolines_for_all_functions()
480 pid = os.fork()
481 if pid == 0:
482 print(os.getpid())
483 bar_fork()
484 else:
485 bar()
486 """
487
488 with temp_dir() as script_dir:
489 script = make_script(script_dir, "perftest", code)
490 with subprocess.Popen(
491 [sys.executable, "-Xperf", script],
492 universal_newlines=True,
493 stderr=subprocess.PIPE,
494 stdout=subprocess.PIPE,
495 ) as process:
496 stdout, stderr = process.communicate()
497
498 self.assertEqual(process.returncode, 0)
499 self.assertNotIn("Error:", stderr)
500 child_pid = int(stdout.strip())
501 perf_file = pathlib.Path(f"/tmp/perf-{process.pid}.map")
502 perf_child_file = pathlib.Path(f"/tmp/perf-{child_pid}.map")
503 self.assertTrue(perf_file.exists())
504 self.assertTrue(perf_child_file.exists())
505
506 perf_file_contents = perf_file.read_text()
507 self.assertIn(f"py::foo:{script}", perf_file_contents)
508 self.assertIn(f"py::bar:{script}", perf_file_contents)
509 self.assertIn(f"py::foo_fork:{script}", perf_file_contents)
510 self.assertIn(f"py::bar_fork:{script}", perf_file_contents)
511
512 child_perf_file_contents = perf_child_file.read_text()
513 self.assertIn(f"py::foo_fork:{script}", child_perf_file_contents)
514 self.assertIn(f"py::bar_fork:{script}", child_perf_file_contents)
515
516 # Pre-compiled perf-map entries of a forked process must be
517 # identical in both the parent and child perf-map files.
518 perf_file_lines = perf_file_contents.split("\n")
519 for line in perf_file_lines:
520 if f"py::foo_fork:{script}" in line or f"py::bar_fork:{script}" in line:
521 self.assertIn(line, child_perf_file_contents)
522
523
524 def _is_perf_vesion_at_least(major, minor):
525 # The output of perf --version looks like "perf version 6.7-3" but
526 # it can also be perf version "perf version 5.15.143", or even include
527 # a commit hash in the version string, like "6.12.9.g242e6068fd5c"
528 #
529 # PermissionError is raised if perf does not exist on the Windows Subsystem
530 # for Linux, see #134987
531 try:
532 output = subprocess.check_output(["perf", "--version"], text=True)
533 except (subprocess.CalledProcessError, FileNotFoundError, PermissionError):
534 return False
535 version = output.split()[2]
536 version = version.split("-")[0]
537 version = version.split(".")
538 version = tuple(map(int, version[:2]))
539 return version >= (major, minor)
540
541
542 @unittest.skipUnless(perf_command_works(), "perf command doesn't work")
543 @unittest.skipUnless(_is_perf_vesion_at_least(6, 6), "perf command may not work due to a perf bug")
544 class TestPerfProfilerWithDwarf(unittest.TestCase, TestPerfProfilerMixin):
545 def run_perf(self, script_dir, script, activate_trampoline=True):
546 if activate_trampoline:
547 return run_perf(
548 script_dir, sys.executable, "-Xperf_jit", script, use_jit=True
549 )
550 return run_perf(script_dir, sys.executable, script, use_jit=True)
551
552 def setUp(self):
553 super().setUp()
554 self.perf_files = set(pathlib.Path("/tmp/").glob("jit*.dump"))
555 self.perf_files |= set(pathlib.Path("/tmp/").glob("jitted-*.so"))
556
557 def tearDown(self) -> None:
558 super().tearDown()
559 files_to_delete = set(pathlib.Path("/tmp/").glob("jit*.dump"))
560 files_to_delete |= set(pathlib.Path("/tmp/").glob("jitted-*.so"))
561 files_to_delete = files_to_delete - self.perf_files
562 for file in files_to_delete:
563 file.unlink()
564
565
566 if __name__ == "__main__":
567 unittest.main()