From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from bombadil.infradead.org (bombadil.infradead.org [198.137.202.133]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 77202FF885C for ; Sat, 25 Apr 2026 17:53:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=lists.infradead.org; s=bombadil.20210309; h=Sender:List-Subscribe:List-Help :List-Post:List-Archive:List-Unsubscribe:List-Id:Content-Type:Cc:To:From: Subject:Message-ID:References:Mime-Version:In-Reply-To:Date:Reply-To: Content-Transfer-Encoding:Content-ID:Content-Description:Resent-Date: Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID:List-Owner; bh=nQeNxtOSoOXwV2zRr64LvO5u7apubipAzZoDUg3KnRw=; b=keqFcq/2A7hWzXi5ehFCSXimGR qQJrBIMtgD+XQz6jEBtdH18Ddlrld5DNvuBvD05N1PHCEstUOCP15RBD2fYuhi85gDx2vSDuhteYS MhSVZqjqjFvm4J+hMMTobWL5iojNx4pFOo784N74NtwYgNEIkFr7gzwh4qMVZrdB75ls4jH/DGHME b9IoT+DGxQm6LJNTH7fYBTGBq5qmp5yHNuIYwBQ4If0S41xCHVHk9AHtzZt/YAJq+EYmsgn/FzuXT j7npbg4VHnpGsK1fkiE+VGmfjzH49onS+dsuFTwiIhgfSbHbYqse1///R8JTnQzoa/qmH5LNgoOsc Si9UPR7w==; Received: from localhost ([::1] helo=bombadil.infradead.org) by bombadil.infradead.org with esmtp (Exim 4.98.2 #2 (Red Hat Linux)) id 1wGhBY-0000000EfIb-2b3s; Sat, 25 Apr 2026 17:52:56 +0000 Received: from mail-dl1-x124a.google.com ([2607:f8b0:4864:20::124a]) by bombadil.infradead.org with esmtps (Exim 4.98.2 #2 (Red Hat Linux)) id 1wGh9F-0000000EdaO-0mYS for linux-arm-kernel@lists.infradead.org; Sat, 25 Apr 2026 17:50:50 +0000 Received: by mail-dl1-x124a.google.com with SMTP id a92af1059eb24-12db37213daso14336770c88.1 for ; Sat, 25 Apr 2026 10:50:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1777139431; x=1777744231; darn=lists.infradead.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=nQeNxtOSoOXwV2zRr64LvO5u7apubipAzZoDUg3KnRw=; b=H279U0Qycms/FOBjkAhc46LRBEHDptp/bYuzlm8kri0wUbfFREWnR5dD0FwSwgGHS9 WuA2FJt8fkeXzdJ8g+l55TPu5TjJQi8puTXv1ElVUsiB3ullrxRO7Ysujxnyvq0vcumI boXJuUhMwtbMwyCPdCFOf7HbZOVXMNqmuGYQ5NfK8ewFjqUAPN9yxi6GsPepien1+Vxf 8rLam/d6IyBkVlti1Kuiruz+kFhcf+SLhS5Er/1Rh7rcAywbA2kbaO8Rk1dMNgv8eaZP 2/09VhCCF+i2/8kYzb1fAFiW037JV+hhHl+dAVz4Dl+XE4f0hnXOMw3sAT5rw+MTrUEl G3Gw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1777139431; x=1777744231; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=nQeNxtOSoOXwV2zRr64LvO5u7apubipAzZoDUg3KnRw=; b=o0m1Bbj6kCWWgx0qbSqGAh2DePEXXmw1FBVHo7/Z1wxwms89lgbSWZO0LRLecnpXpQ A4cE0REj7bKcVBcy3caMlre+uzHT0O/1YZWkwnSQaZI9Nkos05nRN4RYgGHAvr6mqwee bqdgAQtKZrYcYdpEDiMuknC0XGJO4GJU1od3i48tSQF+lGCj2Z3m67Yp8NuOE4+TK5IR R+8/mGmK7wZ2qYPIpDiCfGJUoJL7G9oZA3ZgqUm1CiOq12jcvi7WNk3XXDrU2R9WYXk8 GDzl/cgequPRhdV5vWODZ7Tns5YUN0l6vuFI+e4MbqR90zelyEriYnBDts5Z2kapkqmh QI/A== X-Forwarded-Encrypted: i=1; AFNElJ9Pqvn8yWBQz1bU9qgXMJ8k4l/mNIdBxX8XBpQLhEq4VCpolunmiqMP2NR272IBKLqN5aO/P9thee1dgq42Mio6@lists.infradead.org X-Gm-Message-State: AOJu0Yx9D0O2kpLG9p43lBDQKy9GPN8wp+IiR+Iqa8ezFQBR7LWgPYAS 6NBHpoBE1Vy2Phu8TLpG0QXD+9ZLsb5a8+ziEiL3t1WkBFPFig5LotRji+Ht1RW3cr7wTzIoKzo 7ZtPBSdWHig== X-Received: from dlbrl2.prod.google.com ([2002:a05:7022:f502:b0:12d:c3dd:4fba]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:90a:b0:119:e56b:958a with SMTP id a92af1059eb24-12c73f82134mr19877993c88.15.1777139431153; Sat, 25 Apr 2026 10:50:31 -0700 (PDT) Date: Sat, 25 Apr 2026 10:48:43 -0700 In-Reply-To: <20260425174858.3922152-1-irogers@google.com> Mime-Version: 1.0 References: <20260424164721.2229025-1-irogers@google.com> <20260425174858.3922152-1-irogers@google.com> X-Mailer: git-send-email 2.54.0.545.g6539524ca2-goog Message-ID: <20260425174858.3922152-46-irogers@google.com> Subject: [PATCH v6 45/59] perf stackcollapse: Port stackcollapse to use python module From: Ian Rogers To: acme@kernel.org, adrian.hunter@intel.com, james.clark@linaro.org, leo.yan@linux.dev, namhyung@kernel.org, tmricht@linux.ibm.com Cc: alice.mei.rogers@gmail.com, dapeng1.mi@linux.intel.com, linux-arm-kernel@lists.infradead.org, linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org, mingo@redhat.com, peterz@infradead.org, Ian Rogers Content-Type: text/plain; charset="UTF-8" X-CRM114-Version: 20100106-BlameMichelson ( TRE 0.8.0 (BSD) ) MR-646709E3 X-CRM114-CacheID: sfid-20260425_105033_436716_AFA229A7 X-CRM114-Status: GOOD ( 16.61 ) X-BeenThere: linux-arm-kernel@lists.infradead.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Sender: "linux-arm-kernel" Errors-To: linux-arm-kernel-bounces+linux-arm-kernel=archiver.kernel.org@lists.infradead.org Modernize the legacy stackcollapse.py trace script by refactoring it into a class-based architecture (StackCollapseAnalyzer). The script uses perf.session for event processing and aggregates call stacks to produce output suitable for flame graphs. Assisted-by: Gemini:gemini-3.1-pro-preview Signed-off-by: Ian Rogers --- v2: - Fixed Callchain Check: Replaced hasattr(sample, "callchain") with getattr(sample, "callchain", None) and checked if it is not None . This avoids attempting to iterate over None when a sample lacks a callchain, which would raise a TypeError. - Fixed Comm Resolution: The code already used self.session.process(sample.sample_pid).comm() to resolve the command name using the session object (if available), avoiding the missing comm attribute on perf.sample_event. - Code Cleanup: Broke a long line in process_event to satisfy pylint. --- tools/perf/python/stackcollapse.py | 126 +++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100755 tools/perf/python/stackcollapse.py diff --git a/tools/perf/python/stackcollapse.py b/tools/perf/python/stackcollapse.py new file mode 100755 index 000000000000..996c73246ebc --- /dev/null +++ b/tools/perf/python/stackcollapse.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 +""" +stackcollapse.py - format perf samples with one line per distinct call stack + +This script's output has two space-separated fields. The first is a semicolon +separated stack including the program name (from the "comm" field) and the +function names from the call stack. The second is a count: + + swapper;start_kernel;rest_init;cpu_idle;default_idle;native_safe_halt 2 + +The file is sorted according to the first field. + +Ported from tools/perf/scripts/python/stackcollapse.py +""" + +import argparse +from collections import defaultdict +import sys +import perf + + +class StackCollapseAnalyzer: + """Accumulates call stacks and prints them collapsed.""" + + def __init__(self, args: argparse.Namespace) -> None: + self.args = args + self.lines: dict[str, int] = defaultdict(int) + + def tidy_function_name(self, sym: str, dso: str) -> str: + """Beautify function names based on options.""" + if sym is None: + sym = "[unknown]" + + sym = sym.replace(";", ":") + if self.args.tidy_java: + # Beautify Java signatures + sym = sym.replace("<", "") + sym = sym.replace(">", "") + if sym.startswith("L") and "/" in sym: + sym = sym[1:] + try: + sym = sym[:sym.index("(")] + except ValueError: + pass + + if self.args.annotate_kernel and dso == "[kernel.kallsyms]": + return sym + "_[k]" + return sym + + def process_event(self, sample: perf.sample_event) -> None: + """Collect call stack for each sample.""" + stack = [] + callchain = getattr(sample, "callchain", None) + if callchain is not None: + for node in callchain: + stack.append(self.tidy_function_name(node.symbol, node.dso)) + else: + # Fallback if no callchain + sym = getattr(sample, "symbol", "[unknown]") + dso = getattr(sample, "dso", "[unknown]") + stack.append(self.tidy_function_name(sym, dso)) + + if self.args.include_comm: + if hasattr(self, 'session') and self.session: + comm = self.session.find_thread(sample.sample_pid).comm() + else: + comm = "Unknown" + comm = comm.replace(" ", "_") + sep = "-" + if self.args.include_pid: + comm = f"{comm}{sep}{getattr(sample, 'sample_pid', 0)}" + sep = "/" + if self.args.include_tid: + comm = f"{comm}{sep}{getattr(sample, 'sample_tid', 0)}" + stack.append(comm) + + stack_string = ";".join(reversed(stack)) + self.lines[stack_string] += 1 + + def print_totals(self) -> None: + """Print sorted collapsed stacks.""" + for stack in sorted(self.lines): + print(f"{stack} {self.lines[stack]}") + + +def main(): + """Main function.""" + ap = argparse.ArgumentParser( + description="Format perf samples with one line per distinct call stack" + ) + ap.add_argument("-i", "--input", default="perf.data", help="Input file name") + ap.add_argument("--include-tid", action="store_true", help="include thread id in stack") + ap.add_argument("--include-pid", action="store_true", help="include process id in stack") + ap.add_argument("--no-comm", dest="include_comm", action="store_false", default=True, + help="do not separate stacks according to comm") + ap.add_argument("--tidy-java", action="store_true", help="beautify Java signatures") + ap.add_argument("--kernel", dest="annotate_kernel", action="store_true", + help="annotate kernel functions with _[k]") + + args = ap.parse_args() + + if args.include_tid and not args.include_comm: + print("requesting tid but not comm is invalid", file=sys.stderr) + sys.exit(1) + if args.include_pid and not args.include_comm: + print("requesting pid but not comm is invalid", file=sys.stderr) + sys.exit(1) + + analyzer = StackCollapseAnalyzer(args) + + try: + session = perf.session(perf.data(args.input), sample=analyzer.process_event) + analyzer.session = session + session.process_events() + except IOError as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(1) + except KeyboardInterrupt: + pass + + analyzer.print_totals() + + +if __name__ == "__main__": + main() -- 2.54.0.545.g6539524ca2-goog