Linux Perf Users
 help / color / mirror / Atom feed
From: Jens Remus <jremus@linux.ibm.com>
To: Ian Rogers <irogers@google.com>,
	Arnaldo Carvalho de Melo <acme@kernel.org>,
	Namhyung Kim <namhyung@kernel.org>,
	Peter Zijlstra <peterz@infradead.org>,
	Ingo Molnar <mingo@redhat.com>
Cc: Jens Remus <jremus@linux.ibm.com>,
	Jan Polensky <japo@linux.ibm.com>,
	Sumanth Korikkar <sumanthk@linux.ibm.com>,
	Heiko Carstens <hca@linux.ibm.com>,
	Vasily Gorbik <gor@linux.ibm.com>,
	Alexander Gordeev <agordeev@linux.ibm.com>,
	linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org
Subject: [PATCH 5/5] perf python: Honor perf script --max-stack
Date: Fri,  4 Dec 2026 17:24:32 +0100	[thread overview]
Message-ID: <20261204162426.4171717-12-jremus@linux.ibm.com> (raw)
In-Reply-To: <20261204162426.4171717-7-jremus@linux.ibm.com>

The perf.session binding resolves callchains with a fixed maximum depth
of PERF_MAX_STACK_DEPTH, ignoring the --max-stack option of perf script,
which is also raised to the callchain size of --itrace if larger.

Add a max_stack keyword argument to perf.session.  When not given, it
defaults to the PERF_MAX_STACK environment variable, which perf script
sets from its effective maximum stack depth when running a Python
script.  Otherwise it defaults to PERF_MAX_STACK_DEPTH, as before.

Signed-off-by: Jens Remus <jremus@linux.ibm.com>
---
 .../perf/Documentation/perf-script-python.txt | 11 ++--
 tools/perf/builtin-script.c                   |  3 +
 tools/perf/python/perf.pyi                    |  6 +-
 tools/perf/util/python.c                      | 65 +++++++++++++++++--
 4 files changed, 75 insertions(+), 10 deletions(-)

diff --git a/tools/perf/Documentation/perf-script-python.txt b/tools/perf/Documentation/perf-script-python.txt
index e2f05f5d526c..108deafeada3 100644
--- a/tools/perf/Documentation/perf-script-python.txt
+++ b/tools/perf/Documentation/perf-script-python.txt
@@ -20,10 +20,11 @@ With the removal of embedded Python interpreter from `perf`, scripts
 are now run as standalone Python programs that import the `perf`
 module to access trace data. Symbol configuration options (`--vmlinux`,
 `--kallsyms`, `--symfs`, `--inline`/`--no-inline`, `--show-kernel-path`,
-`--demangle`/`--no-demangle` and `--demangle-kernel`)
-and `--itrace` options passed to `perf script` are forwarded via
-`PERF_SYMBOL_*` and `PERF_ITRACE` environment variables to `perf.session`,
-and can also be passed directly to `perf.session`.
+`--demangle`/`--no-demangle` and `--demangle-kernel`),
+`--max-stack` and `--itrace` options passed to `perf script`
+are forwarded via `PERF_SYMBOL_*`, `PERF_MAX_STACK` and `PERF_ITRACE`
+environment variables to `perf.session`, and can also be passed directly to
+`perf.session`.
 Trace filtering command-line
 options (`-C`, `-c`, `--pid`, `--tid`, `--time`, `--dlfilter`, `--dlarg`) passed
 to `perf script` are not applied to standalone scripts.
@@ -120,7 +121,7 @@ perf.session
 
 Manages a trace session.
 
-- `__init__(data, sample=None, stat=None, context_switch=None, call_return=None, itrace=None, vmlinux=None, kallsyms=None, symfs=None, inline=False, show_kernel_path=True, demangle=True, demangle_kernel=False)`: Creates a new session. `data` is a `perf.data` object. `sample` is a callback function called for each sample event. `vmlinux`, `kallsyms`, and `symfs` configure symbol resolution paths. `inline` resolves inlined functions in callchains, which are then flagged by `callchain_node.inlined`. `show_kernel_path` reports the kernel DSO by its vmlinux path rather than `[kernel.kallsyms]`. `demangle` and `demangle_kernel` demangle user space and kernel symbol names. When run by `perf script`, the defaults of `inline`, `show_kernel_path`, `demangle` and `demangle_kernel` are the values of `--inline`/`--no-inline`, `--show-kernel-path`, `--demangle`/`--no-demangle` and `--demangle-kernel`.
+- `__init__(data, sample=None, stat=None, context_switch=None, call_return=None, itrace=None, vmlinux=None, kallsyms=None, symfs=None, inline=False, show_kernel_path=True, demangle=True, demangle_kernel=False, max_stack=127)`: Creates a new session. `data` is a `perf.data` object. `sample` is a callback function called for each sample event. `vmlinux`, `kallsyms`, and `symfs` configure symbol resolution paths. `inline` resolves inlined functions in callchains, which are then flagged by `callchain_node.inlined`. `show_kernel_path` reports the kernel DSO by its vmlinux path rather than `[kernel.kallsyms]`. `demangle` and `demangle_kernel` demangle user space and kernel symbol names. `max_stack` limits the number of resolved callchain entries. When run by `perf script`, the defaults of `inline`, `show_kernel_path`, `demangle`, `demangle_kernel` and `max_stack` are the values of `--inline`/`--no-inline`, `--show-kernel-path`, `--demangle`/`--no-demangle`, `--demangle-kernel` and `--max-stack`.
 - `process_events()`: Reads the trace data and calls the sample callback for each event.
 - `find_thread(pid, tid=-1)`: Returns the thread associated with a PID/TID.
 - `e_machine`: ELF machine architecture ID (`EM_*`) of the session.
diff --git a/tools/perf/builtin-script.c b/tools/perf/builtin-script.c
index 0936cf711e8c..c1e6ce1f0eaf 100644
--- a/tools/perf/builtin-script.c
+++ b/tools/perf/builtin-script.c
@@ -4435,6 +4435,7 @@ int cmd_script(int argc, const char **argv)
 		};
 		struct sigaction old_int, old_quit, old_term;
 		sigset_t block_mask, old_mask;
+		char max_stack_str[16];
 
 		if (is_python && is_legacy_python_script(script_name)) {
 			pr_err("Error: '%s' uses the removed legacy embedded Python scripting API.\n"
@@ -4543,6 +4544,8 @@ int cmd_script(int argc, const char **argv)
 			setenv("PERF_SYMBOL_DEMANGLE", symbol_conf.demangle ? "1" : "0", 1);
 			setenv("PERF_SYMBOL_DEMANGLE_KERNEL",
 			       symbol_conf.demangle_kernel ? "1" : "0", 1);
+			snprintf(max_stack_str, sizeof(max_stack_str), "%u", scripting_max_stack);
+			setenv("PERF_MAX_STACK", max_stack_str, 1);
 
 			execvp(__argv[0], (char **)__argv);
 			{
diff --git a/tools/perf/python/perf.pyi b/tools/perf/python/perf.pyi
index c7f43deb84bf..d1604ab50092 100644
--- a/tools/perf/python/perf.pyi
+++ b/tools/perf/python/perf.pyi
@@ -492,7 +492,8 @@ class session:
         inline: bool = ...,
         show_kernel_path: bool = ...,
         demangle: bool = ...,
-        demangle_kernel: bool = ...
+        demangle_kernel: bool = ...,
+        max_stack: int = ...
     ) -> None:
         """Initialize a perf session.
 
@@ -513,6 +514,9 @@ class session:
             demangle_kernel: Demangle kernel symbol names. Defaults to the
                 PERF_SYMBOL_DEMANGLE_KERNEL environment variable set by perf
                 script, otherwise False.
+            max_stack: Maximum number of callchain entries to resolve.
+                Defaults to the PERF_MAX_STACK environment variable set by
+                perf script, otherwise 127.
         """
         ...
     e_machine: int
diff --git a/tools/perf/util/python.c b/tools/perf/util/python.c
index fe468a0f0aa4..7ddc127e3ef6 100644
--- a/tools/perf/util/python.c
+++ b/tools/perf/util/python.c
@@ -1088,6 +1088,12 @@ static PyTypeObject pyrf_callchain__type = {
 	.tp_as_sequence	= &pyrf_callchain__sequence_methods,
 };
 
+/*
+ * Maximum number of callchain entries to resolve, set from the active
+ * perf.session like the symbol_conf settings.
+ */
+static int pyrf_max_stack = PERF_MAX_STACK_DEPTH;
+
 static int pyrf_sample_event__resolve_callchain(struct pyrf_event *pevent)
 {
 	struct callchain_cursor *cursor;
@@ -1102,7 +1108,7 @@ static int pyrf_sample_event__resolve_callchain(struct pyrf_event *pevent)
 
 	cursor = get_tls_callchain_cursor();
 	if (thread__resolve_callchain(pevent->al.thread, cursor, pevent->sample,
-				      NULL, NULL, PERF_MAX_STACK_DEPTH) != 0)
+				      NULL, NULL, pyrf_max_stack) != 0)
 		return 0;
 
 	callchain_cursor_commit(cursor);
@@ -4252,6 +4258,7 @@ struct pyrf_session {
 	bool show_kernel_path;
 	bool demangle;
 	bool demangle_kernel;
+	int max_stack;
 };
 
 struct pyrf_call_return {
@@ -4979,6 +4986,26 @@ static bool pyrf_getenv_bool(const char *name, bool def)
 	return strcmp(str, "0") != 0;
 }
 
+/* Return @def when the environment variable is unset or empty. */
+static long pyrf_getenv_long(const char *name, long min, long max, long def)
+{
+	const char *str = getenv(name);
+	char *end;
+	long val;
+
+	if (str && str[0]) {
+		errno = 0;
+		val = strtol(str, &end, 10);
+		if (*end || errno || val < min || val > max) {
+			PyErr_Format(PyExc_ValueError, "invalid %s value: %s",
+				     name, str);
+			return -1;
+		}
+		return val;
+	}
+	return def;
+}
+
 static PyObject *pyrf_session__new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
 {
 	struct pyrf_data *pdata;
@@ -4988,22 +5015,39 @@ static PyObject *pyrf_session__new(PyTypeObject *type, PyObject *args, PyObject
 	char *vmlinux_str = NULL, *kallsyms_str = NULL, *symfs_str = NULL;
 	int inline_arg = -1, show_kernel_path_arg = -1;
 	int demangle_arg = -1, demangle_kernel_arg = -1;
+	PyObject *max_stack_obj = NULL;
+	long max_stack_arg = -1;
 	static char *kwlist[] = { "data", "sample", "stat", "context_switch",
 				  "call_return", "itrace", "vmlinux", "kallsyms",
 				  "symfs", "inline", "show_kernel_path",
-				  "demangle", "demangle_kernel", NULL };
+				  "demangle", "demangle_kernel", "max_stack",
+				  NULL };
 	struct pyrf_session *psession;
 	struct perf_session *session;
 
-	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|OOOOzzzzpppp", kwlist,
+	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|OOOOzzzzppppO", kwlist,
 					 &pyrf_data__type, &pdata,
 					 &sample, &stat, &context_switch,
 					 &call_return, &itrace_str,
 					 &vmlinux_str, &kallsyms_str, &symfs_str,
 					 &inline_arg, &show_kernel_path_arg,
-					 &demangle_arg, &demangle_kernel_arg))
+					 &demangle_arg, &demangle_kernel_arg,
+					 &max_stack_obj))
 		return NULL;
 
+	if (max_stack_obj) {
+		max_stack_arg = PyLong_AsLong(max_stack_obj);
+
+		if (max_stack_arg == -1 && PyErr_Occurred())
+			return NULL;
+		if (max_stack_arg < 0 || max_stack_arg > INT_MAX) {
+			PyErr_Format(PyExc_ValueError,
+				     "invalid max_stack value: %ld",
+				     max_stack_arg);
+			return NULL;
+		}
+	}
+
 	psession = PyObject_New(struct pyrf_session, type);
 	if (!psession)
 		return NULL;
@@ -5027,6 +5071,7 @@ static PyObject *pyrf_session__new(PyTypeObject *type, PyObject *args, PyObject
 	psession->show_kernel_path = true;
 	psession->demangle = true;
 	psession->demangle_kernel = false;
+	psession->max_stack = PERF_MAX_STACK_DEPTH;
 	psession->pdata = NULL;
 	memset(&psession->itrace_opts, 0, sizeof(psession->itrace_opts));
 
@@ -5152,6 +5197,16 @@ static PyObject *pyrf_session__new(PyTypeObject *type, PyObject *args, PyObject
 	psession->demangle_kernel = demangle_kernel_arg >= 0 ? demangle_kernel_arg :
 		pyrf_getenv_bool("PERF_SYMBOL_DEMANGLE_KERNEL", psession->demangle_kernel);
 
+	if (max_stack_arg >= 0)
+		psession->max_stack = max_stack_arg;
+	else {
+		long val = pyrf_getenv_long("PERF_MAX_STACK", 0, INT_MAX, psession->max_stack);
+
+		if (val == -1 && PyErr_Occurred())
+			goto err_out;
+		psession->max_stack = val;
+	}
+
 	if (pyrf_session__active) {
 		PyErr_SetString(PyExc_RuntimeError,
 				"Another perf.session is currently active");
@@ -5166,6 +5221,7 @@ static PyObject *pyrf_session__new(PyTypeObject *type, PyObject *args, PyObject
 	symbol_conf.show_kernel_path = psession->show_kernel_path;
 	symbol_conf.demangle = psession->demangle;
 	symbol_conf.demangle_kernel = psession->demangle_kernel;
+	pyrf_max_stack = psession->max_stack;
 
 	/* Reading the header of a pipe may block, let other python threads run. */
 	pyrf_session__active = psession;
@@ -5240,6 +5296,7 @@ static PyObject *pyrf_session__find_thread_events(struct pyrf_session *psession)
 	symbol_conf.show_kernel_path = psession->show_kernel_path;
 	symbol_conf.demangle = psession->demangle;
 	symbol_conf.demangle_kernel = psession->demangle_kernel;
+	pyrf_max_stack = psession->max_stack;
 
 	psession->callback_raised = false;
 	/* Callbacks that use python acquire the GIL, see pyrf_session_tool__sample(). */
-- 
2.53.0


  parent reply	other threads:[~2026-12-04 16:25 UTC|newest]

Thread overview: 11+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-04 16:24 [PATCH 0/5] perf python: Honor more perf script options Jens Remus
2026-12-04 16:24 ` [PATCH 1/5] perf python: Support inlined frames in callchains Jens Remus
2026-12-04 16:46   ` sashiko-bot
2026-12-04 16:24 ` [PATCH 2/5] perf python: Export inlined symbol flag in DB export scripts Jens Remus
2026-12-04 16:59   ` sashiko-bot
2026-12-04 16:24 ` [PATCH 3/5] perf python: Honor perf script --show-kernel-path Jens Remus
2026-12-04 17:13   ` sashiko-bot
2026-12-04 16:24 ` [PATCH 4/5] perf python: Honor perf script --demangle and --demangle-kernel Jens Remus
2026-12-04 16:24 ` Jens Remus [this message]
2026-12-04 17:35   ` [PATCH 5/5] perf python: Honor perf script --max-stack sashiko-bot
2026-12-04 17:35 ` [PATCH 0/5] perf python: Honor more perf script options sashiko-bot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261204162426.4171717-12-jremus@linux.ibm.com \
    --to=jremus@linux.ibm.com \
    --cc=acme@kernel.org \
    --cc=agordeev@linux.ibm.com \
    --cc=gor@linux.ibm.com \
    --cc=hca@linux.ibm.com \
    --cc=irogers@google.com \
    --cc=japo@linux.ibm.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-perf-users@vger.kernel.org \
    --cc=mingo@redhat.com \
    --cc=namhyung@kernel.org \
    --cc=peterz@infradead.org \
    --cc=sumanthk@linux.ibm.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox