summaryrefslogtreecommitdiffstats
path: root/tools/perf/util/setup.py
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2026-08-30 09:22:00 -0700
committerLinus Torvalds <torvalds@linux-foundation.org>2026-08-30 09:22:00 -0700
commit034dd340b08be1f2f0477ad16131d609f9dbd53c (patch)
tree2536f4b2d7893ccd916b5abdf3c454ad6edc03c2 /tools/perf/util/setup.py
downloadlinux-stable-034dd340b08be1f2f0477ad16131d609f9dbd53c.tar.gz
linux-stable-034dd340b08be1f2f0477ad16131d609f9dbd53c.zip
Merge tag 'trace-v7.3-2' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-tracegrafted
Pull tracing fixes from Steven Rostedt: - Fix error output of boot instance creation failure Currently if a boot instance creation fails, instead of printing out the name of the instance that failed, it prints "(null)". That is because it prints "cur_str" that had already been processed by strsep(). Print the saved name instead. While at it, print the error code of the failure. - Fix use-after-free for same named historgrams Histograms can be named so that they can be used in multiple events. But if the named histogram has a variable attached, the second event that uses the named histogram which duplicates it and needs to free the original after duplication leaves the old variable in place and still visible. If another histogram uses than variable, it will use the stale one which will try to reference the freed duplicate histogram and crash the kernel. Free the duplicate variables along with the duplicated histogram data. - Check return value of kthread_run() in event self test The events self tests uses a kthread for testing but does not check if it succeeded in creating a kthread. If the kthread creation were to fail, the code will still try to call kthread_stop() on the error returned. - Fix race between reading trace_pipe and updating subbuffer size If a user is reading the trace_pipe file at the same time they update the ring buffer sub-buffer size, can cause the trace_pipe read to read stale data. Add trace_access_lock() around updating the ring buffer sub-buffer size. - Fix eventfs_inode on failure path in creation of the events directory In the creation of the "events" directory, if after allocating the eventfs_inode a failure is detected, it calls cleanup_ei() which calls free_ei(). The free_ei() will test if eventfs_inode being freed has no children. It is a bug if it does. But on the failure case of the creation of the "events" directory, the children lists have not yet been initialized and the free will trigger a warning because list_empty() on an uninitialized list returns false. Move the initialization into init_ei() where it makes more sense and makes sure that a created eventfs_inode has its lists initialized upon creation. - Check return value of kthread_run() in ftrace direct sample code The sample code that shows how to use the ftrace direct calls does not test the return of kthread_run() to see if it succeeds. Return a failure if the kthread_run() doesn't succeed. - Clear user events state on fork in case of alloc failure On fork, the child gets a pointer to the parent's user events state. It makes a copy of it then updates the child's pointer to it. But if the allocation fails, the duplication function leaves the child with a pointer to its parent's descriptor. When the child cleans up its data, it will free the parent's descriptor while the parent is still using it. In the duplication function, set the child's user_event_mm to NULL before testing if the allocation succeeded, and when it exits it will not free the parent's descriptor. - Fix retry exhaustion in simple ring buffer reader swap simple_ring_buffer_swap_reader_page() starts with retry set to 8 and post-decrements it only after a failed link replacement. On the final attempt, a successful replacement leaves retry at zero, while a failed replacement leaves it at -1. But the check for success expects the retry value to be non-zero and exits with an error on zero. This is the opposite result. Fix it. - Fail nicely when the remote swap_reader_page() returns an error Currently, if the swap_reader_page() of a remote buffer fails, it triggers a WARN_ON_ONCE() and continues normally. Instead, have it exit with an error and a pr_warn() print instead of a full WARNING. * tag 'trace-v7.3-2' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-trace: ring-buffer: Stop remote reader update when page swap fails tracing: Fix retry exhaustion in simple ring buffer reader swap tracing/user_events: Clear copied tracing state before fork duplication samples/ftrace: Fix kthread_stop() on ERR_PTR in ftrace-direct-multi-modify samples/ftrace: Fix kthread_stop() on ERR_PTR in ftrace-direct-modify eventfs: Initialize ei->children and ei->list in init_ei() tracing: Fix use-after-free in trace_pipe read on sub-buffer order change tracing: Fix crash passing ERR_PTR to kthread_stop() tracing: Fix use-after-free with same-name named triggers tracing: Fix logged instance name on creation failure
Diffstat (limited to 'tools/perf/util/setup.py')
-rw-r--r--tools/perf/util/setup.py194
1 files changed, 194 insertions, 0 deletions
diff --git a/tools/perf/util/setup.py b/tools/perf/util/setup.py
new file mode 100644
index 000000000..8380980ad
--- /dev/null
+++ b/tools/perf/util/setup.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: GPL-2.0
+"""Setup script for perf python extension.
+
+This script is used to build and install the perf python binding.
+It handles compiler-specific flags, especially for clang, and configures
+the setuptools Extension.
+"""
+
+import os
+import shlex
+import shutil
+import subprocess
+import sysconfig
+
+from setuptools import setup, Extension
+from setuptools.command.build_ext import build_ext as _build_ext
+from setuptools.command.install_lib import install_lib as _install_lib
+
+
+def clang_has_option(cc: str, cc_args: list[str], src_feature_tests: str, option: str) -> bool:
+ """Check if clang supports a specific option.
+
+ Args:
+ cc: The compiler executable.
+ cc_args: Compiler arguments from CC environment variable.
+ src_feature_tests: Path to the feature tests directory.
+ option: The compiler option to check (e.g., "-mcet").
+
+ Returns:
+ True if the option is supported, False otherwise.
+ """
+ error_substrings = (
+ b"unknown argument",
+ b"is not supported",
+ b"unknown warning option"
+ )
+ cmd = [cc] + cc_args + [
+ option,
+ "-o", "/dev/null",
+ os.path.join(src_feature_tests, "test-hello.c")
+ ]
+ try:
+ res = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, check=False)
+ cc_output = res.stderr.splitlines()
+ except OSError:
+ return False
+ return not any(any(error in line for error in error_substrings) for line in cc_output)
+
+
+def filter_clang_options(cc: str, cc_args: list[str], src_feature_tests: str) -> None:
+ """Filter out unsupported clang options from sysconfig CFLAGS and OPT.
+
+ Args:
+ cc: The compiler executable.
+ cc_args: Compiler arguments from CC environment variable.
+ src_feature_tests: Path to the feature tests directory.
+ """
+ config_vars = sysconfig.get_config_vars()
+ for var in ('CFLAGS', 'OPT'):
+ if var not in config_vars:
+ continue
+
+ # Split into individual flags using shlex to preserve quoted arguments
+ flags = shlex.split(config_vars[var])
+
+ # Remove -specs=...
+ flags = [f for f in flags if not f.startswith("-specs=")]
+
+ options = (
+ "-mcet",
+ "-fcf-protection",
+ "-fstack-clash-protection",
+ "-fstack-protector-strong",
+ "-fno-semantic-interposition",
+ "-ffat-lto-objects",
+ "-ftree-loop-distribute-patterns",
+ "-gno-variable-location-views"
+ )
+ for option in options:
+ if not clang_has_option(cc, cc_args, src_feature_tests, option):
+ # Remove the option and any variant (e.g. -option=...)
+ flags = [f for f in flags if not f.startswith(option)]
+
+ # Re-join flags preserving quoting
+ config_vars[var] = shlex.join(flags)
+
+
+class BuildExt(_build_ext):
+ """Custom build_ext command to set output directories."""
+
+ def __init__(self, *args, **kwargs):
+ self.build_lib = None
+ self.build_temp = None
+ super().__init__(*args, **kwargs)
+
+ def finalize_options(self) -> None:
+ _build_ext.finalize_options(self)
+ build_lib = os.getenv('PYTHON_EXTBUILD_LIB')
+ build_tmp = os.getenv('PYTHON_EXTBUILD_TMP')
+ if build_lib:
+ self.build_lib = build_lib
+ if build_tmp:
+ self.build_temp = build_tmp
+
+
+class InstallLib(_install_lib):
+ """Custom install_lib command to set output directory."""
+
+ def __init__(self, *args, **kwargs):
+ self.build_dir = None
+ super().__init__(*args, **kwargs)
+
+ def finalize_options(self) -> None:
+ _install_lib.finalize_options(self)
+ build_lib = os.getenv('PYTHON_EXTBUILD_LIB')
+ if build_lib:
+ self.build_dir = build_lib
+
+ def run(self):
+ _install_lib.run(self)
+ srctree = os.getenv('srctree', '.')
+ src_perf = os.path.join(srctree, 'tools/perf')
+ shutil.copy2(os.path.join(src_perf, 'python/perf.pyi'), self.install_dir)
+
+
+def main() -> None:
+ """Main entry point for the setup script."""
+ cc_env = os.getenv("CC")
+ assert cc_env, "Environment variable CC not set"
+
+ # Safe parsing of CC environment variable which might contain options/quotes
+ cc_tokens = shlex.split(cc_env)
+ cc = cc_tokens[0]
+ cc_args = cc_tokens[1:]
+
+ # Run CC -v to check if it is clang.
+ try:
+ cc_info = subprocess.run(
+ [cc, "-v"], stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, check=False
+ )
+ cc_is_clang = b"clang version" in cc_info.stderr
+ except OSError as e:
+ raise RuntimeError(f"Failed to execute compiler '{cc}': {e}") from e
+
+ srctree = os.getenv('srctree')
+ assert srctree, "Environment variable srctree, for the Linux sources, not set"
+ src_feature_tests = f'{srctree}/tools/build/feature'
+
+ if cc_is_clang:
+ filter_clang_options(cc, cc_args, src_feature_tests)
+
+ # switch off several checks (need to be at the end of cflags list)
+ cflags = [
+ '-fno-strict-aliasing',
+ '-Wno-write-strings',
+ '-Wno-unused-parameter',
+ '-Wno-redundant-decls'
+ ]
+ if cc_is_clang:
+ cflags += ["-Wno-unused-command-line-argument"]
+ if clang_has_option(
+ cc, cc_args, src_feature_tests, "-Wno-cast-function-type-mismatch"
+ ):
+ cflags += ["-Wno-cast-function-type-mismatch"]
+ else:
+ cflags += ['-Wno-cast-function-type']
+
+ # The python headers have mixed code with declarations (decls after asserts, for instance)
+ cflags += ["-Wno-declaration-after-statement"]
+
+ src_perf = f'{srctree}/tools/perf'
+
+ perf = Extension(
+ 'perf',
+ sources=[os.path.join(src_perf, 'util/python.c')],
+ include_dirs=['util/include'],
+ extra_compile_args=cflags,
+ )
+
+ setup(
+ name='perf',
+ version='0.1',
+ description='Interface with the Linux profiling infrastructure',
+ author='Arnaldo Carvalho de Melo',
+ author_email='acme@redhat.com',
+ license='GPLv2',
+ url='http://perf.wiki.kernel.org',
+ ext_modules=[perf],
+ cmdclass={'build_ext': BuildExt, 'install_lib': InstallLib},
+ )
+
+
+if __name__ == '__main__':
+ main()