Commit Graph
100 Commits
Author SHA1 Message Date
Ian Rogers d4ce72e9e2 perf python: Port intel-pt-events and libxed to perf module
Port intel-pt-events.py and libxed.py from tools/perf/scripts/python/
to standalone modules in tools/perf/python/:
- Refactor intel-pt-events.py into an IntelPTAnalyzer class with full
  type annotations to encapsulate trace state and stashed output.
- Configure instruction trace decoding directly via perf.session's
  itrace option and context_switch callback.
- Dynamically select 32-bit vs 64-bit disassembly mode in libxed.py
  using session.is_64_bit and annotate instructions with source lines
  via sample.srccode().
- Rename methods in libxed.py to snake_case (instruction, set_mode,
  disassemble_one) and remove Python 2 compatibility code.

Add a shell test (test_intel_pt_events_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers d5934ca319 perf python: Port powerpc-hcalls to perf module
Port powerpc-hcalls.py from tools/perf/scripts/python/ to a standalone
script in tools/perf/python/:
- Refactor the script into an HCallAnalyzer class with full type
  annotations to encapsulate per-CPU hypervisor call entry/exit state.
- Use perf.session for event processing to track hypervisor call entry
  and exit timestamps and aggregate min/max/average duration statistics
  against HCALL_TABLE.
- Add argparse CLI support (-i/--input) and remove Python 2
  compatibility code.

Add a shell test (test_powerpc_hcalls_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 279b402e51 perf python: Port arm-cs-trace-disasm to perf module
Port arm-cs-trace-disasm.py to a standalone script in tools/perf/python/
using the perf module directly.

Improvements compared to the legacy script:
- Encapsulate trace disassembly state in a TraceDisasm class.
- Default to itrace="b" when creating perf.session() (overridable via
  --itrace or PERF_ITRACE) so all CoreSight branch samples are
  synthesized without requiring --itrace=b on the command line.
- Automatically search standard kernel debug paths (find_vmlinux())
  when -k/--vmlinux is not specified, and query
  perf.config_get("annotate.objdump") for the default objdump binary.
- Bound DISASM_CACHE memory consumption by evicting the cache at 1024
  entries and skipping caching of oversized (> 512 lines) objdump
  outputs.
- Use sample.srccode() from the perf extension module to annotate
  disassembly output with source filenames, line numbers, and source
  lines.

Update the ARM CoreSight disassembly shell test
(test_arm_coresight_disasm.sh) to invoke the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Reviewed-by: James Clark <[email protected]>
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 8c302c9140 perf python: Port check-perf-trace to perf module
Port check-perf-trace.py to a standalone script in tools/perf/python/
using the perf module directly.

Improvements compared to the legacy script:
- Access tracepoint fields directly as attributes on perf.sample_event
  instead of per-event dictionaries and legacy Perf-Trace-Util helpers.
- Decode symbolic flag and enum masks for irq:softirq_entry and
  kmem:kmalloc directly in Python and add -i/--input CLI support via
  argparse.
- Add full type annotations and clean up Python 2 idioms.

Add a shell test (test_check_perf_trace_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers b08e799dee perf python: Port netdev-times to perf module
Port netdev-times.py from tools/perf/scripts/python/ to a standalone
script in tools/perf/python/:
- Refactor the script into a NetDevTimesAnalyzer class with full type
  annotations to encapsulate state.
- Collect events via perf.session and sort them in timestamp order
  before analysis so multi-CPU TX and RX packet timelines are
  reconstructed deterministically.
- Replace custom argument parsing with argparse (-i/--input, --tx,
  --rx, --dev, --debug), extract tracepoint fields directly from sample
  attributes, and remove Python 2 compatibility artifacts.

Add a shell test (test_netdev_times_python.sh) to verify the standalone
script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers c1864af54c perf python: Port net_dropmonitor to perf module
Port net_dropmonitor.py from tools/perf/scripts/python/ to a standalone
script in tools/perf/python/:
- Refactor the script into a DropMonitor class with full type
  annotations to encapsulate state.
- Use perf.session for skb:kfree_skb event processing and add argparse
  CLI support (-i/--input and -k/--kallsyms).
- Resolve kernel drop addresses via perf.session symbols/callchains and
  binary search over /proc/kallsyms, ignoring zeroed kptr_restrict
  addresses with graceful fallback when kallsyms is unavailable.
- Remove Python 2 compatibility code.

Add a shell test (test_net_dropmonitor_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 45266bbeea perf python: Port compaction-times to perf module
Port compaction-times.py to a standalone script in tools/perf/python/
using the perf module directly to analyze mm_compaction tracepoints.

Improvements compared to the legacy script:
- Replace Python 2 constructs (such as sys.maxint and raw integer
  bitmasks) with Python 3 enum.IntEnum (Popt) and enum.IntFlag (Topt)
  types.
- Access tracepoint fields directly on perf.sample_event and add
  -i/--input CLI option support via argparse.
- Add full type annotations passing mypy and pylint without suppression
  comments.

Add a shell test (test_compaction_times_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 97c70711fc perf python: Port wakeup-latency from Perl to perf module
Replace the legacy Perl script wakeup-latency.pl with a standalone
Python script in tools/perf/python/wakeup-latency.py using the perf
Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Track wakeup timestamps per-task (keyed by the wakee PID on
  sched:sched_wakeup and matched against next_pid on sched:sched_switch)
  rather than per-CPU, avoiding mixed latencies when multiple wakeups
  occur on a CPU before a context switch.
- Guard print_totals() when total_wakeups == 0 (printing 'N/A' instead
  of dividing by zero when a trace contains no matched wakeup/switch
  pairs).
- Add argparse CLI options (-i/--input) and full type annotations.

Add a shell test
(test_wakeup_latency_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 56d9f05dce perf python: Port sched-migration and SchedGui to perf module
Port sched-migration.py and SchedGui.py from tools/perf/scripts/python/
to standalone modules in tools/perf/python/:
- Refactor sched-migration.py into a SchedMigrationAnalyzer class using
  perf.session for event processing and add argparse CLI support
  (-i/--input, -v/--verbose, --gui, --no-gui).
- Port SchedGui.py to tools/perf/python/ as a local module dependency.
- Load wxPython dynamically via importlib only when GUI mode (--gui) is
  requested so text-mode analysis, testing on headless systems, and
  static analysis (mypy/pylint) succeed without wx installed.
- Remove Python 2 compatibility code.

Add a shell test (test_sched_migration_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers 164c7edd80 perf python: Port task-analyzer to perf module
Port task-analyzer.py from tools/perf/scripts/python/ to a standalone
script in tools/perf/python/ refactored into a class-based architecture.

Improvements compared to the legacy script:
- Support both offline perf.data file analysis (using perf.session) and
  live trace capture (using evlist.read_on_cpu), accessing
  sched:sched_switch tracepoint fields directly from sample objects.
- Automatically disable ANSI terminal color escape sequences when --csv
  or --csv-summary is enabled so CSV column headers ('Comm,',
  'Time Out-Out,', etc.) are never polluted by color codes when running
  interactively on a TTY (e.g. as root).
- Sanitize non-printable characters and leading CSV formula characters
  (=, +, -, @) in task comm strings.
- Emit a one-time warning to stderr if sched:sched_switch samples are
  missing tracepoint fields (such as when recorded without libtraceevent
  support).

Update test_task_analyzer.sh to invoke the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:30 +02:00
Ian Rogers b103b3338b perf python: Port futex-contention to perf module
Port tools/perf/scripts/python/futex-contention.py to a standalone
script in tools/perf/python/ using the perf module. Avoiding the
embedded interpreter overhead improves execution speed by ~3.2x:

```
$ perf record -e syscalls:sys_*_futex -a sleep 1
...
$ time perf script tools/perf/scripts/python/futex-contention.py
...
real    0m1.007s
user    0m0.935s
sys     0m0.072s
$ time python3 tools/perf/python/futex-contention.py
...
real    0m0.314s
user    0m0.259s
sys     0m0.056s
```

Additional improvements compared to the legacy script:
- Consolidate per-(tid, uaddr) contention count, total_time, min_time,
  and max_time into a single LockStats class instead of maintaining
  three separate dictionaries.
- Validate that uaddr and op tracepoint attributes are present on
  syscalls:sys_enter_futex samples rather than silently attributing
  missing fields to uaddr=0, op=0 (FUTEX_WAIT).
- Add -i/--input CLI option support via argparse and full type
  annotations.

Add a shell test (test_futex_contention_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers 605fd1c8b7 perf python: Port rwtop from Perl to perf module
Replace the legacy Perl script rwtop.pl with a standalone Python script
in tools/perf/python/rwtop.py using the perf Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Support both offline perf.data files (via perf.session) and live
  recording (via LiveSession with --live), driving periodic interval
  summaries from event timestamps rather than wall-clock SIGALRM timers
  so both live and offline runs produce deterministic output.
- Convert unsigned 32-bit and 64-bit error return values
  (0xfffff000..0xffffffff and >= 0x8000000000000000) to negative errnos
  so failed read/write syscalls are recorded in the error table rather
  than inflating bytes_read / bytes_written.
- Sanitize non-printable characters in /proc/<pid>/comm to prevent
  terminal control sequence injection.

Add a shell test
(test_rwtop_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers d935308817 perf python: Port rw-by-pid from Perl to perf module
Replace the legacy Perl script rw-by-pid.pl with a standalone Python
script in tools/perf/python/rw-by-pid.py using the perf Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Convert unsigned 32-bit and 64-bit error return values
  (0xfffff000..0xffffffff and >= 0x8000000000000000) to negative errnos
  so failed read/write syscalls are recorded in the error table rather
  than inflating bytes_read / bytes_written.
- Add argparse CLI support (-i/--input) and full type annotations.

Add a shell test
(test_rw_by_pid_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers 47b00c3878 perf python: Port rw-by-file from Perl to perf module
Replace the legacy Perl script rw-by-file.pl with a standalone Python
script in tools/perf/python/rw-by-file.py using the perf Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Encapsulate per-file-descriptor read/write byte and call count
  aggregation in an RwByFile class using perf.session and resolve thread
  command names via session.find_thread(pid, sample_tid).
- Add argparse CLI support (-i/--input and target program filter) and
  full type annotations.

Add a shell test
(test_rw_by_file_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers b83f0bacf5 perf python: Port sctop to perf module
Port sctop.py from tools/perf/scripts/python/ to a standalone script in
tools/perf/python/ using an SCTopAnalyzer class structure.

Improvements compared to the legacy script:
- Support both offline perf.data analysis (via perf.session, advancing
  display intervals deterministically using event timestamps) and live
  monitoring (via LiveSession with automatic tracepoint fallback from
  raw_syscalls:sys_enter to syscalls:sys_enter_*).
- Resolve architecture-aware syscall names via
  perf.syscall_name(id, session.e_machine) without requiring
  python-audit.
- Replace unsafe signal.SIGALRM dictionary mutation and os.popen("clear")
  subshell spawning with a synchronized threading.Lock / threading.Event
  timer and direct ANSI terminal escape sequences ('\x1b[2J\x1b[H').

Add a shell test (test_sctop_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers 4e3fe6987c perf python: Port failed-syscalls from Perl to perf module
Replace the legacy Perl script failed-syscalls.pl with a standalone
Python script in tools/perf/python/failed-syscalls.py using the perf
Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Support both syscalls:sys_exit_* and raw_syscalls:sys_exit events (the
  legacy script only handled raw_syscalls::sys_exit).
- Use session.is_64_bit to distinguish 32-bit vs 64-bit unsigned error
  return ranges (0xfffff000..0xffffffff vs >= 0xfffffffffffff000) so
  valid 64-bit syscalls returning ~4GB values are not misclassified as
  32-bit negative errors.
- Add argparse CLI support (-i/--input and optional comm filter) and
  full type annotations.

Add a shell test
(test_failed_syscalls_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers b76c43d09b perf python: Port failed-syscalls-by-pid to perf module
Port failed-syscalls-by-pid.py to a standalone script in
tools/perf/python/ using the perf module:
- Resolve architecture-aware syscall names using
  perf.syscall_name(id, session.e_machine) instead of host python-audit
  tables, supporting cross-architecture perf.data files without external
  dependencies.
- Translate negative syscall return values into symbolic E* error names
  using perf.arch_strerrno(ret, session.e_machine), leveraging the
  auto-generated trace beauty architecture errno tables.
- Encapsulate aggregation in a SyscallAnalyzer class using
  collections.defaultdict and add argparse filtering by comm, PID, and
  -i/--input.

Add a shell test (test_failed_syscalls_by_pid_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers 712af96a53 perf python: Port syscall-counts-by-pid to perf module
Port tools/perf/scripts/python/syscall-counts-by-pid.py to a standalone
script in tools/perf/python/ using the perf module. Avoiding the
embedded interpreter and per-event dictionary overhead improves
execution speed by ~3.8x:

```
$ perf record -e raw_syscalls:sys_enter -a sleep 1
...
$ time perf script tools/perf/scripts/python/syscall-counts-by-pid.py perf
...
real    0m3.852s
user    0m3.512s
sys     0m0.336s
$ time python3 tools/perf/python/syscall-counts-by-pid.py perf
...
real    0m1.011s
user    0m0.963s
sys     0m0.048s
```

Additional improvements compared to the legacy script:
- Resolve architecture-specific syscall names via
  perf.syscall_name(id, session.e_machine) instead of host python-audit
  tables.
- Support both raw_syscalls:sys_enter and individual syscalls:sys_enter_*
  tracepoints, and filter out invalid (> 0xffff or negative) syscall IDs.
- Support filtering by numeric PID as well as command name (comm), and
  resolve process command names via session.find_thread(pid).

Add a shell test (test_syscall_counts_by_pid_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers 3d69731960 perf python: Port syscall-counts to perf module
Port tools/perf/scripts/python/syscall-counts.py to a standalone script
in tools/perf/python/ using the perf module. Avoiding the embedded
interpreter and per-event dictionary allocation overhead improves
execution speed by ~4x:

```
$ perf record -e raw_syscalls:sys_enter -a sleep 1
...
$ time perf script tools/perf/scripts/python/syscall-counts.py perf
...
real    0m3.887s
user    0m3.578s
sys     0m0.308s
$ time python3 tools/perf/python/syscall-counts.py perf
...
real    0m0.953s
user    0m0.905s
sys     0m0.048s
```

Additional improvements compared to the legacy script:
- Resolve syscall names using perf.syscall_name(id, session.e_machine)
  instead of host python-audit / Util.py tables, enabling accurate
  cross-architecture perf.data analysis without external dependencies.
- Support both raw_syscalls:sys_enter (sample.id) and individual
  syscalls:sys_enter_* tracepoints (sample.__syscall_nr / sample.nr),
  filtering out invalid/corrupt (> 0xffff or negative) syscall numbers.
- Add argparse CLI options (-i/--input and optional comm filter).

Add a shell test (test_syscall_counts_python.sh) to verify the
standalone script. The legacy script and its bin wrapper are retained
temporarily during the transition to maintain bisectability and are
removed once all scripts are migrated.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers eeb70645a8 perf python: Port event_analyzing_sample to perf module
Port event_analyzing_sample.py to a standalone script in
tools/perf/python/ using the perf module and standard library sqlite3
module.

Improvements compared to the legacy script:
- Encapsulate database state in a _DB container instead of mutating
  module-level globals, and ensure temporary SQLite database files are
  cleaned up on exit.
- Add argparse CLI options (-i/--input and -d/--db) while preserving
  PerfEvent, PebsEvent, and PebsNHM binary raw_buf unpacking and
  symbol/DSO histogram reporting.
- Remove Python 2 compatibility code and add type annotations.

Add a shell test (test_event_analyzing_sample_python.sh) to verify the
standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:29 +02:00
Ian Rogers e1e4bd6f8b perf python: Port gecko to perf module
Port gecko.py to a standalone script in tools/perf/python/ that uses
the perf module directly to convert perf.data profiles into Firefox
Gecko profile format.

Improvements compared to the legacy script:
- Encapsulate profiler state in GeckoCLI and CategoryData classes with
  full type annotations, removing global variables.
- Harden the local HTTP server in _write_and_launch(): write the
  temporary profile to an isolated tempfile.TemporaryDirectory() with a
  randomized UUID filename instead of the current working directory,
  bind HTTPServer exclusively to 127.0.0.1 on an OS-assigned ephemeral
  port (0), restrict CORS Access-Control-Allow-Origin to
  'https://profiler.firefox.com' instead of '*', and restrict HTTP GET
  requests exclusively to the randomized profile filename (returning
  HTTP 403 for directory listings and any other path).
- Add -i/--input and -e/--event CLI options via argparse.

Add a shell test (test_gecko_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers eb08738a7f perf python: Port flamegraph to perf module
Port flamegraph.py to a standalone script in tools/perf/python/ that
uses the perf module directly, avoiding intermediate dictionary
allocations for event fields.

Improvements compared to the legacy script:
- Add Subresource Integrity (integrity="sha256-...") and
  crossorigin="anonymous" attributes to external CDN stylesheet and
  script tags in MINIMAL_HTML.
- Upgrade CDN HTML template hash verification from weak MD5
  (hashlib.md5) to cryptographic SHA-256 (hashlib.sha256).
- Escape '<', '>', and '&' ('\u003c', '\u003e', '\u0026') in embedded
  JSON payloads (stacks_json and options_json) to prevent HTML script
  injection / XSS when rendering untrusted symbol or command names.
- Skip invoking 'perf report --header-only' when the input is stdin
  ('-'), a FIFO pipe, or a character device (S_ISFIFO / S_ISCHR) so
  non-seekable streams do not hang or fail.

Add a shell test (test_flamegraph_python.sh) to verify the standalone
script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers c3034e70c6 perf python: Port stackcollapse to perf module
Port stackcollapse.py from tools/perf/scripts/python/ to a standalone
script in tools/perf/python/ refactored into a StackCollapseAnalyzer
class.

Improvements compared to the legacy script:
- Traverse sample.callchain directly from perf.session without
  allocating per-event dictionaries, and fall back to sample.symbol when
  a sample has no callchain.
- Replace deprecated optparse with argparse, adding -i/--input alongside
  --include-tid, --include-pid, --no-comm, --tidy-java, and --kernel.
- Handle BrokenPipeError cleanly when output is piped into downstream
  tools (such as head or flamegraph.pl).

Add a shell test (test_stackcollapse_python.sh) using a CPU workload
(perf test -w noploop) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers 6ceccefad0 perf python: Port mem-phys-addr to perf module
Port mem-phys-addr.py to a standalone script in tools/perf/python/
using the perf.session API to read perf.data files and profile physical
memory access types against /proc/iomem.

Improvements compared to the legacy script:
- Parse the full indentation hierarchy of /proc/iomem into a parent-child
  tree of frozen IomemEntry dataclasses (instead of only top-level
  indent-0 ranges), resolving physical addresses to the most specific
  sub-range (such as Kernel code/data/bss inside System RAM) and rolling
  child counts up into parent totals.
- Support profiling multiple memory events in a single perf.data session
  (keyed by evsel name) instead of assuming a single global event.
- Add argparse CLI options (-i/--input and --iomem to allow supplying an
  offline /proc/iomem snapshot from a target system).

Add a shell test (test_mem_phys_addr_python.sh) to verify the standalone
script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers 4425182d42 perf python: Port stat-cpi to perf module
Port stat-cpi.py from the legacy embedded scripting framework to a
standalone Python script in tools/perf/python/ to calculate Cycles Per
Instruction (CPI) per interval per CPU or thread.

Improvements compared to the legacy script:
- Support both perf.data file mode (via perf.session stat callbacks)
  and live counter collection mode (using perf.parse_events,
  evlist.open, and evsel.read across intervals), with automatic fallback
  to user-space (:u) and self-process monitoring when perf_event_paranoid
  restricts system-wide events (EACCES).
- Compute per-interval counter deltas (val, ena, run) keyed by raw event
  name so cumulative PERF_RECORD_STAT snapshots and hybrid PMU events
  (e.g. cpu_core/cycles/, cpu_atom/cycles/) are accumulated accurately,
  and scale counts by time_enabled / time_running when multiplexed.
- Replace hard-coded CPU ([0, 1]) and thread ([0]) arrays with dynamic
  CPU and thread discovery so arbitrary system topologies work
  automatically.
- Add CLI option handling (-i, -I, -p) via argparse and type annotations
  passing mypy and pylint.

Add a shell test (test_stat_cpi_python.sh) to verify the standalone
script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers af2f226e8c perf Makefile: Install standalone Python scripts during transition
Install the newly ported standalone Python scripts (python/*.py), type
stubs (python/perf.pyi), and compiled perf Python extension module
(python/perf*.so, when built) into $(perfexec_instdir_SQ)/python
alongside the legacy scripts during the transition phase so that newly
ported scripts can import perf directly from the installation directory
before legacy support is removed.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers 5fe83fb352 perf build: Make pylint build test opt-out (NO_PYLINT=1)
Commit 8a54784e70 ("perf build: Add pylint build tests") added a
compile-time pylint check for Python files in tools/perf, but left it
opt-in via PYLINT=1.

Now that pylint issues across tools/perf/python, tools/perf/pmu-events,
and tools/perf/tests/shell/lib have been cleaned up, enable the pylint
check by default when pylint is installed on the system, with an opt-out
via NO_PYLINT=1 (matching NO_SHELLCHECK=1, NO_MYPY=1, and other perf
build feature flags).

Configure PYTHONPATH in Makefile.perf so pylint resolves perf.pyi type
stubs and pmu-events modules, enable error and warning categories
(--disable=all --enable=E,W --disable=W0123,W0311,W0511,W0603,W0622,W0718
--ignored-modules=textual,setproctitle) appropriate for perf's standalone
CLI and test scripts, and require pylint >= 2.16.0 (skipping with a
warning if an older version is installed).

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers b3e9c396d0 perf build: Make mypy build test opt-out (NO_MYPY=1)
Commit 168910d0f9 ("perf build: Add mypy build tests") added a
compile-time mypy type check for Python files in tools/perf, but left it
opt-in via MYPY=1.

Now that mypy issues across tools/perf/python, tools/perf/pmu-events,
and tools/perf/tests/shell/lib have been cleaned up, enable the mypy
check by default when mypy is installed on the system, with an opt-out
via NO_MYPY=1 (matching NO_SHELLCHECK=1 and other perf build feature
flags). Also configure MYPYPATH in Makefile.perf so scripts can resolve
perf.pyi type stubs and local modules, pass --ignore-missing-imports so
optional third-party packages do not fail default builds, and remove
*.mypy_log files during `make clean`.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers 1331150d7d perf test: Clean up mypy and pylint issues in shell test libraries
Clean up mypy type errors and pylint errors/warnings in
tools/perf/tests/shell/lib/ (attr.py, perf_json_output_lint.py, and
perf_metric_validation.py):
- Fix E0606 (possibly-used-before-assignment) in perf_metric_validation.py
  by importing sys at module level.
- Add type annotations for stack, second_results, collectlist,
  get_bounds(), and main() in perf_metric_validation.py.
- Avoid assigning -1 to list[int] expected_items in
  perf_json_output_lint.py, rename shadowing variables, and remove
  redundant lambdas.
- Remove unnecessary semicolons, use lazy logging arguments, specify
  exception types and file encodings, and initialize module-level logger
  in attr.py.

Also update tools/perf/tests/shell/lib/setup_python.sh to:
- Avoid x-prefix string comparisons.
- Export PYTHON and resolve PYTHONPATH and PERF_EXEC_PATH from
  BASH_SOURCE[0], ../../../python (for nested test directories such as
  coresight/), and the directory containing the perf binary so out-of-tree
  builds and standalone perf python scripts work seamlessly.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers db5a607501 perf pmu-events: Clean up mypy and pylint issues
Clean up mypy type errors and pylint warnings across the pmu-events Python
scripts (amd_metrics.py, intel_metrics.py, jevents.py,
make_legacy_cache.py,
and metric.py) in preparation for making MYPY and PYLINT build tests
opt-out.

In addition to type annotations and unused import/variable cleanups, fix
three bugs in intel_metrics.py exposed by static analysis:
- Fix references to undefined 'args.model' (instead of '_args.model')
  inside
  try/except blocks in IntelL2() and UncoreMemBw(), which previously threw
  NameError and silently disabled Skylake/CascadeLake L2 silent eviction
  adjustments and uncore memory bandwidth JSON loading.
- Define DC_WB_U and DC_WB_D before their first use in IntelL2(), fixing
  an UnboundLocalError that silently dropped the l2_out_rate, wbn, and isd
  metrics.
- Fix Event-to-string comparison and addition in IntelFp() by comparing
  and modifying 'f_assist.name' instead of the Event object 'f_assist'.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:28 +02:00
Ian Rogers ca23ecf8ee perf python: Allow KeyboardInterrupt to propagate in LiveSession
LiveSession.run() synchronously blocks while polling evlist for events.
When running interactive tools or scripts from the terminal,
KeyboardInterrupt exceptions raised via Ctrl-C must propagate so the
caller can break out of the polling loop.

Previously, LiveSession caught KeyboardInterrupt with an empty pass
statement, swallowing the exception and preventing calling scripts from
detecting the interrupt cleanly. Remove the empty handler so calling
scripts receive KeyboardInterrupt and can perform clean teardown.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers f66944587d perf python: Add Intel PT call_return and itrace capability
Add support for Intel PT call_return events and itrace options to the
perf Python extension so standalone Python scripts can decode and
inspect low-level instruction traces.

Specifically:
- Add a call_return callback parameter and itrace option string to
  perf.session, treating explicit None (Py_None) callbacks as omitted.
- Expose the perf.call_return object with db_id, parent_id, insn_count,
  cyc_count, comm, pid, tid, call_time, return_time, branch_count,
  call_ref, return_ref, flags, and call_path (resolved as a
  perf.callchain ordered from outermost caller to callee, populating
  frame->map and frame->sym so call_path entries expose resolved symbol
  and DSO names).
- Export perf.CALL_RETURN_NO_CALL, perf.CALL_RETURN_NO_RETURN, and
  perf.CALL_RETURN_NON_CALL flag constants.
- Expose session.e_machine and session.is_64_bit properties, preferring
  recorded thread ELF machines (perf_session__e_machine) over perf_env
  so pipe-mode traces do not prematurely cache host bitness.
- Support optional vmlinux, kallsyms, and symfs symbol configuration
  parameters (and PERF_SYMBOL_VMLINUX, PERF_SYMBOL_KALLSYMS,
  PERF_SYMBOL_SYMFS environment fallbacks) in perf.session, resetting
  symbol_conf pointers and freeing vm_tm_corr_args, cpu_bitmap, and
  ptime_range in pyrf_session__delete().

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 7a481f6c71 perf python: Expose addr location, transaction, and context_switch
Expose destination address location components (addr_dso, addr_symbol,
addr_sym_offset), branch/transaction metrics (branch_type, in_tx,
flags, transaction), machine_pid, vcpu, sym_offset, and context_switch
callbacks directly to the Python extension.

Also include supporting fixes and infrastructure updates in
util/python.c and perf.pyi:
- Support fetching sym_offset on resolved sample symbols.
- Populate sample machine_pid and vcpu from evlist__id2sid() when
  perf_guest is enabled, and resolve samples against the matching guest
  or host machine.
- Expose next_prev_pid and next_prev_tid on switch_event only for
  PERF_RECORD_SWITCH_CPU_WIDE records (returning None otherwise).
- Wire up tracing_data in pyrf_session__new() and update perf.pyi type
  stubs (including srccode() and insn() return types).

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 4b15226c14 perf python: Improve perf script -l descriptions
Add module docstrings to counting.py, tracepoint.py, and twatch.py. This
satisfies pylint's missing-module-docstring check and prepares these
existing standalone scripts in tools/perf/python/ for the later commit
in this series ("perf script: Support standalone scripts and remove
embedded scripting"), which updates 'perf script -l' to scan
tools/perf/python/ and display each script's module docstring:

```
$ perf script -l
List of available scripts:
...
  counting
    Example for counting perf events.
...
  tracepoint
    Example showing how to enable a tracepoint and access its fields.
  twatch
    Example to show how to enable a software event and track
    context switches.
...
```

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers abbcb48f33 perf python: Clean up pylint warnings in twatch.py
Clean up pylint warnings in twatch.py so that it passes pylint without
warning suppression comments:
- Convert tab indentation to 4 spaces (W0311: bad-indentation).
- Remove unnecessary trailing semicolon (W0301: unnecessary-semicolon)
  after evsel.open().
- Convert floating multi-line string comments to '#' comments (W0105:
  pointless-string-statement).

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 62dfb55494 perf python: Clean up pylint warnings in tracepoint.py
Clean up pylint warnings in tracepoint.py so that it passes pylint
without warning suppression comments:
- Catch ImportError instead of bare 'except:' (W0702: bare-except) when
  importing setproctitle.
- Remove unnecessary trailing semicolon (W0301: unnecessary-semicolon)
  after evlist.enable().

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 2997739214 perf python: Clean up pylint warnings in treport.py
Clean up pylint warnings in treport.py so that it passes pylint without
warning suppression comments:
- Replace broad 'except Exception:' clauses (W0718:
  broad-exception-caught) with specific exception tuples.
- Pass both pid and sample_tid to session.find_thread() so guest and
  process threads are resolved accurately.
- Rename parameter 'args' to 'pos_args' in FlameGraph.__init__() to
  avoid shadowing the outer scope variable 'args' (W0621:
  redefined-outer-name).
- Clear session = None in a finally block after session.process_events()
  to break the C perf_session reference cycle before launching the TUI.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 2dfe9eaec5 perf python: Clean up pylint warnings in ilist.py
Replace bare 'except:' clauses (pylint W0702: bare-except) in ilist.py
with specific exception tuples (OSError, ValueError, RuntimeError,
TypeError, KeyError) and use a safe '.get("name", "")' sort key in
IListApp.compose() so that ilist.py passes pylint without warning
suppression comments and handles unnamed PMU events gracefully.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 514ecdfd00 perf python: Update callchain stubs and session thread lookup
Update pyrf_session__find_thread() in util/python.c to accept an
optional tid parameter (defaulting to pid) and return None instead of
raising TypeError when a thread is not found in the session machines.

Update perf.pyi to match:
- Set session.find_thread() signature to (pid: int, tid: int = -1) ->
  Optional[thread].
- Update callchain_node.symbol and callchain_node.dso to str (the C
  getters return "[unknown]" fallback strings rather than None) and add
  __iter__() to callchain.

Also update treport.py to handle Optional[thread] returned by
session.find_thread().

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers c4925cc8b8 perf python: Update syscall helpers and expose arch_strerrno
Update the PyArg_ParseTupleAndKeywords format string for
pyrf__syscall_name() and pyrf__syscall_id() from "i|$i" to "i|i" (and
"s|$i" to "s|i"), allowing elf_machine to be passed as an optional
positional argument as well as a keyword argument. Update syscall_id()
and syscall_name() in perf.pyi to match, and set the return type of
syscall_name() to Optional[str] as unknown syscall numbers return None.

Also expose perf_env__arch_strerrno() as perf.arch_strerrno(err,
elf_machine=None) so standalone Python scripts can resolve
architecture-specific errno names directly from the auto-generated
trace beauty tables instead of maintaining duplicate errno dictionaries
in Python. Tighten the macro pattern in arch_errno_names.sh to
E[A-Z0-9]+ so compiler -D flags containing underscores (such as LLVM's
-DEXPERIMENTAL_KEY_INSTRUCTIONS=1) do not shadow EPERM (1), and add
EM_SPARC32PLUS alongside EM_SPARC and EM_SPARCV9.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-26 20:49:27 +02:00
Ian Rogers 906af9e1c9 perf test stat metrics cgroup: Strip possible slash from cgroup name
The grep to match cgroup name in metric output assumes no leading / on
the cgroup name, however, cgroups in /proc/self/cgroup may have a
leading /. Strip the / if it exists to avoid failures to match the
cgroup name in the perf stat output.

Signed-off-by: Ian Rogers <[email protected]>
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 17:42:21 +02:00
Ian Rogers 8c74fcecb4 tools include: Add missing stdarg.h include
Header file makes use of varargs but doesn't directly include stdarg.h.

Closes: https://lore.kernel.org/linux-perf-users/[email protected]/
Reported-by: [email protected]
Signed-off-by: Ian Rogers <[email protected]>
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 15:04:50 +02:00
Ian Rogers 5d0e31779b perf thread: Free the comm read from procfs
procfs__read_str() allocates the buffer it hands back and
thread__set_comm() only stores an interned copy of the string, so the
caller owns the buffer. thread__set_comm_from_proc() freed it when the
read came back empty but not once it had been used, leaking it on
every successful call.

Free it on both paths. The empty read still returns -1, err being
untouched in that case.

Found with leak sanitizer while running 'perf trace':

  Direct leak of 7 byte(s) in 1 object(s) allocated from:
      #1 io__getdelim fs/../io.h:179
      #2 filename__read_str fs/fs.c:365
      #3 procfs__read_str fs/fs.c:402
      #4 thread__set_comm_from_proc util/thread.c:297
      #5 syscall_arg__scnprintf_pid trace/beauty/pid.c:15

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 15:00:03 +02:00
Ian Rogers 0cf5416f48 perf trace: Free the host machine allocation
trace__symbols_init() creates the host machine with machine__new_host(),
which allocates a struct machine, but trace__symbols__exit() released it
with machine__exit(). That tears down the contents of the machine and
leaves the allocation itself behind, so use machine__delete(), which
does both. The replay path points trace->host at the machine embedded in
the session and never reaches here, so nothing else is affected.

The leak was hidden from leak sanitizer because trace__symbols_init()
passes the machine to trace_event__register_resolver(), which stores it
as the private pointer of the global tep handle. The handle kept the
machine reachable for as long as the process lived, so it was only once
the handle started being freed that this was reported:

  Direct leak of 1256 byte(s) in 1 object(s) allocated from:
      #1 __machine__new_host util/machine.c:135
      #2 machine__new_host util/machine.c:155
      #3 trace__symbols_init builtin-trace.c:2105
      #4 trace__run builtin-trace.c:4759
      #5 cmd_trace builtin-trace.c:6091

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 14:59:28 +02:00
Ian Rogers 5a3d7afdfb perf trace-event: Free the global trace_event when a command ends
The tep handle behind trace_event__tp_format() is a process wide cache
of the running kernel's tracepoint formats and nothing ever released
it, as the comment above it had noted since the code was added.

Add trace_event__exit() and call it from run_builtin() next to the
existing perf_config__exit(). By then the builtin has returned, so the
tep_event pointers it handed out, such as the ones cached in
evsel->tp_format, are no longer reachable.

Note that this does not silence every libtraceevent report under
leak sanitizer. Parsing a print fmt drops a token inside the library
itself, and as those allocations are not linked into the handle,
freeing the handle cannot reclaim them.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 14:58:03 +02:00
Ian Rogers d9eba1d5b5 perf trace-event: Reuse an already parsed tracepoint format
tp_format() read and parsed the format file on every call. Each parse
registers another tep_event with the global tep handle, and
libtraceevent has no way to free an individual event, only the whole
handle, so a repeated lookup of the same tracepoint both redoes the
work of reading and parsing the file and leaves a duplicate behind for
the rest of the session.

Ask the handle for the event first with tep_find_event_by_name() and
only fall back to reading the format file when it has not been parsed
yet. The handle holds formats for the running kernel alone, so a name
that is found is the same format that would have been read.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 14:57:52 +02:00
Ian Rogers e223a41c42 perf trace-event: Report tracepoint format errors with NULL and errno
trace_event__tp_format() encoded failure with ERR_PTR() while
trace_event__tp_format_id() returned a plain NULL when tep_find_event()
found nothing, and tp_format() itself returned NULL when
tep_parse_format() failed, as its return value was discarded. Callers
test with IS_ERR(), which NULL does not satisfy, so those two failures
were taken for success. In syscall__read_info() that leads straight to:

	if (IS_ERR(sc->tp_format)) {
		...
		return err;
	}
	if (syscall__alloc_arg_fmts(sc, sc->tp_format->format.nr_fields - 1))

which dereferences NULL when a format file fails to parse.

Mixing encoded error pointers with pointers that are compared against
NULL is what allows that to happen, so drop ERR_PTR() here and report
failures the way the rest of these paths already expect, by returning
NULL with errno set. evsel__tp_format() no longer has to translate the
error back into errno before printing it with %m, and the remaining
callers become NULL tests.

syscall__scnprintf_args() gains back its fallback of printing raw
arguments: it asked for IS_ERR(sc->tp_format), but syscall__read_info()
had already replaced the error pointer with NULL, so the branch could
never be taken.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 14:57:39 +02:00
Ian Rogers d227b45fc1 perf machine: Add session back pointer to fix out of bounds read
thread__e_machine_endian() decides whether a thread is live, and so
whether to read /proc/pid/exe rather than fall back to the perf.data
environment, by recovering the session from the machine:

	session = container_of(machine->machines, struct perf_session,
			       machines);
	is_live = !session->data;

That only holds when the struct machines is the one embedded in a struct
perf_session. It is not the only one. aslr_tool keeps its own in struct
aslr_tool, and hists_cumulate, hists_filter, hists_link, hists_output
and thread-maps-share each put one on the stack. For those the
container_of subtracts offsetof(struct perf_session, machines) from an
address that was never inside a session, and the following load of
session->data reads outside the object, which is what ASan reports.

Replace the derivation with an explicit link. machines__init() takes the
owning session, or NULL when the machines is standalone, and
thread__e_machine_endian() reads it back through machines__session().

A NULL session is treated as live. The tests use synthetic pids that
have no /proc entry, so the read fails there and the e_machine falls
back to EM_HOST as before, rather than being decided by whatever the
out of bounds read happened to return. perf inject registers its
session with the aslr tool once the session exists, before any event is
processed, so that tool keeps reporting file based threads as not live.

Fixes: 70351029b5 ("perf thread: Add support for reading the e_machine type for a thread")
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 14:08:40 +02:00
Ian Rogers 97e94e5c5a perf test: Fix PMU metric parsing tests for unknown literals
On ARM the #slots literal may or may not be present, it won't be present
on x86. As it is missing it causes the ampereone and ampereonex PMU
metric tests to fail when run say on x86.

Extend the fake_pmu logic so that in these test cases we fake the
unknown literals like #slots as 1.0.

When building with JEVENTS_ARCH=all the ampere metric tests no longer
fail.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-25 12:51:49 +02:00
Ian Rogers edd8a9fe2e perf evsel: Report an allocation failure as ENOMEM when setting filters
evsel__set_filter() and evsel__append_filter() return -1 when the strdup()
or asprintf() that builds the new filter string fails, and
evlist__set_tp_filter() and evlist__append_tp_filter() do the same when
handed the NULL that asprintf__tp_filter_pids() returns for the same
reason. In every case the only thing that can have gone wrong is an
allocation.

Callers all test the result with "< 0" or for being non-zero, so -1 has
been as good as any other error so far, but it is not an errno and so
cannot be printed as one. A caller that does, such as

	str_error_r(-err, errbuf, sizeof(errbuf))

turns it into EPERM and reports a failure to allocate as "Operation not
permitted", which is no help to anyone trying to work out what happened.

Return -ENOMEM instead, which is what these failures are.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 15:00:48 +02:00
Ian Rogers 1865b4164b perf trace: Free the whole evsel_trace in evsel__put_and_free_priv
Every evsel->priv in builtin-trace.c is a struct evsel_trace, allocated
by evsel_trace__new(). It holds a syscall_arg_fmt array in its fmt
member, which evsel__syscall_arg_fmt() allocates on demand for the
syscalls:sys_{enter,exit}_SYSCALL tracepoints and for every other
tracepoint that gets its arguments pretty printed.

evsel__put_and_free_priv() only did zfree(&evsel->priv), releasing the
evsel_trace itself and leaking that array. Use evsel_trace__delete(),
which frees fmt first, exactly as the out_delete path of
evsel__syscall_arg_fmt() already does.

The current callers are all error paths that run before fmt can have
been allocated, so nothing leaks in practice today, but the helper is
the obvious thing to reach for whenever an evsel is discarded and it
should be safe for that.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 15:00:23 +02:00
Ian Rogers 1b9822a297 perf trace: Include the headers declaring pid_t, strcmp and assert
trace_augment.h uses pid_t in the augmented_syscalls__set_filter_pids()
prototype and in the !HAVE_BPF_SKEL stub. bpf_trace_augment.c calls
strcmp() in augmented_syscalls__find_by_title() and assert() in
augmented_syscalls__create_bpf_output(), but neither pulls in the header
that declares what it uses. Both happen to build today only because
something else in the include chain drags <sys/types.h>, <string.h> and
<assert.h> in first, which is not guaranteed and does not hold on libcs
such as musl that keep the POSIX namespaces strictly separated.

Include <sys/types.h>, <string.h> and <assert.h> explicitly.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:59:58 +02:00
Ian Rogers 551fbfaa06 perf test: Add build tests for clang and libbfd demangling
Three build configurations broke recently without the build test suite
noticing, as none of them were covered:

  - "CC=clang" on its own. CXX is only set to clang++ by "make LLVM=1",
    so CXX stays as g++ and used to be passed clang's flags.
  - "CC=clang BUILD_NONDISTRO=1", where libbfd.c failed clang's
    -Wthread-safety analysis.
  - "BUILD_NONDISTRO=1 NO_DEMANGLE=1", the only combination that
    compiles the libbfd demangling in symbol.c, which referred to
    identifiers nothing declared.

Add the three. The clang ones need clang installed, and the libbfd ones
reuse the existing binutils check.

Testing that perf was built isn't enough for the first one. Feature
tests are allowed to fail, so a broken C++ compiler command line doesn't
fail the build, it silently turns off every feature needing a C++
compiler and the build still produces a working perf. Check that libLLVM
is still built in, which is the C++ dependent feature perf can report
on, so the test fails instead of quietly producing a perf with less in
it than the default build has.

Only make that check when libLLVM can be built in the first place. The
llvm-perf feature test compiles and links against the llvm-devel/llvm-dev
headers and libraries and needs version 13 or newer, so the presence of
llvm-config on its own says nothing. Probe the same way the feature test
does and fall back to only testing that perf was built when the probe
fails, rather than turning a machine without the LLVM development files
into a spurious failure.

For the same reason the clang tests must not reuse a feature dump made
with the default compiler, so exclude them from REUSE_FEATURES_DUMP.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:46:31 +02:00
Ian Rogers a5cac2df8b perf build: Remove leftovers of removed build options
NO_LIBDW_DWARF_UNWIND, NO_SYSCALL_TABLE and the embedded clang/LLVM
support were all removed, but each removal left the matching entry in
the build test suite behind:

  run += make_no_libdw_dwarf_unwind
  run += make_no_syscall_tbl
  run += make_with_clangllvm

None of these have a make_* variable defining what to build, so $($@)
expands to nothing and each one silently repeats the plain "make_pure"
build. The suite therefore spends six builds, as every test is also run
with O=, appearing to cover options that no longer exist.

Remove them, along with the NO_LIBDW_DWARF_UNWIND comment that is still
in Makefile.perf.

Fixes: 2e9191573a ("perf build: Remove NO_LIBDW_DWARF_UNWIND option")
Fixes: 3cc550f5bb ("perf tools: Remove dependency on libaudit")
Fixes: 56b11a2126 ("perf bpf: Remove support for embedding clang for compiling BPF events (-e foo.c)")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:46:02 +02:00
Ian Rogers 4f4387a07f perf build: Check the version of the compiler that is used
The flex and bison flags are adjusted for clang older than 13.0.0, which
doesn't grok -Wno-unused-but-set-variable. The test is reached because
CC_NO_CLANG says CC is clang, but the version comes from $(CLANG), which
defaults to plain "clang" and needn't be the compiler in use:

  $ make CC=clang-19 CLANG=clang-12
  version from $(CLANG) -> 12.0.0, flag stripped
  version from $(CC)    -> 19.1.7, flag kept

Dropping the flag lets the warnings it suppresses in the generated flex
and bison code through, and those are errors under -Werror.

Ask $(CC) instead, as that is what compiles the code.

Fixes: 878460e8d0 ("perf build: Remove -Wno-unused-but-set-variable from the flex flags when building with clang < 13.0.0")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:45:48 +02:00
Ian Rogers bd874cd835 perf build: Use the given CC rather than clang in clang builds
The clang block is entered when CC_NO_CLANG has determined that CC is
clang, but it then ignores CC and hard codes $(CLANG), which defaults to
plain "clang". Building with a versioned compiler silently switches
compiler:

  $ make CC=clang-19		# actually builds with "clang"

Worse, the target triple is probed with $(CLANG) too, so on a machine
that only has versioned binaries installed the probe produces nothing
and the build stops:

  $ make CC=clang-19
  *** Specify CROSS_COMPILE or add CLANG_TARGET_FLAGS for x86_64

Use $(CC) in both places. Within the block CC is known to be clang, and
for "make LLVM=1" CC is already $(CLANG), so nothing changes there.

$(CLANG) is left as it is for BPF skeletons, as bpf_skel.mak builds
those with "$(CLANG) --target=bpf" whatever CC happens to be.

Fixes: 4772e66cb4 ("perf build: Support build with clang")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:45:33 +02:00
Ian Rogers c8592f8da8 perf build: Only pass clang flags to CXX when CXX is clang
Building with "make CC=clang" appends clang's --target= and
-fintegrated-as to CXX, but CXX is only set to clang++ by "make LLVM=1".
With just CC=clang, CXX is still g++ and every C++ feature test dies:

  g++: error: unrecognized command-line option '--target=...'
  g++: error: unrecognized command-line option '-fintegrated-as'

The failures are silent, as feature tests are allowed to fail, so the
build quietly loses libllvm and C++ demangling support:

  $ make CC=clang && grep LIBLLVM .config-detected
  (nothing, whereas a gcc build reports CONFIG_LIBLLVM=y)

The block is entered when CC_NO_CLANG says CC is clang, which says
nothing about CXX. Probe CXX the same way tools/scripts/Makefile.include
probes CC, and only add the flags when CXX really is clang++.

Mixing a clang-built C with a g++-built C++ is fine here, the C++ code
is linked with -lstdc++ already.

Fixes: 4772e66cb4 ("perf build: Support build with clang")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:45:16 +02:00
Ian Rogers cd1f5f952a perf pmu: Include the headers that are used
pmu.c uses errno, free() and the str*() functions but declares none of
them directly. <string.h> arrives by way of <linux/string.h>, and
<errno.h> and <stdlib.h> come from whatever the other headers happen to
drag in, which is fragile and breaks on C libraries that don't nest
their headers the same way.

Include the three directly.

<ctype.h> is deliberately not added. The isdigit(), tolower() and
toupper() used here are the macros from <linux/ctype.h>, which is
included on purpose and documents that it doesn't handle EOF the way the
standard C library does, so pulling in <ctype.h> would change which
implementation is used.

size_t is left alone too, as <stdio.h> is already included directly and
declares it.

No functional change.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:45:12 +02:00
Ian Rogers f963226016 perf libbfd: Include the headers that are used
libbfd.c uses errno, PATH_MAX, strdup(), strlen(), strcmp(), memcpy()
and pthread_once() but relies on other headers to drag in <errno.h>,
<limits.h>, <string.h> and <pthread.h>. The BPF disassembly code needs
<inttypes.h> for PRIx64 and <stdint.h> for uintptr_t for the same
reason.

Include them directly and group the includes so that the system ones
come before perf's own.

No functional change.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:45:02 +02:00
Ian Rogers ecbc5aac7d perf symbol: Fix the build when demangling with libbfd
cxx_demangle_sym() calls bfd_demangle() with the DMGL_PARAMS and
DMGL_ANSI flags, but nothing declares them. The
"#define PACKAGE 'perf'", "#include <bfd.h>" and the DMGL_ definitions
were left behind in symbol-elf.c when the demangling code moved to
symbol.c, and libiberty's demangle.h that defines the flags isn't
installed by every binutils package. The cplus_demangle() variant is
missing a declaration for the same reason.

The code is only built when the C++ ABI's __cxa_demangle() is
unavailable, so most builds never compile it:

  $ make BUILD_NONDISTRO=1 NO_DEMANGLE=1
  util/symbol.c:2714: error: 'DMGL_PARAMS' undeclared
  util/symbol.c:2714: error: 'DMGL_ANSI' undeclared
  util/symbol.c:2716: error: implicit declaration of 'bfd_demangle'

Move the libbfd demangling into libbfd.c, which already includes bfd.h,
and declare in symbol.c the libiberty interfaces the cplus_demangle()
variant needs.

Fixes: 4d9b5146f0 ("perf symbol: Move demangling code out of symbol-elf.c")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:44:33 +02:00
Ian Rogers c4c4334350 perf libbfd: Fix the clang -Wthread-safety build failure
perf_bfd_lock() and perf_bfd_unlock() are the callbacks given to
bfd_thread_init(), so by design they acquire and release the lock on
libbfd's behalf and the lock state differs between entry and exit.
clang's thread safety analysis, which perf builds with as an error,
flags both:

  util/libbfd.c:56:1: error: mutex 'bfd_mutex' is still held at the end of function [-Werror,-Wthread-safety-analysis]
  util/libbfd.c:60:2: error: releasing mutex 'bfd_mutex' that was not held [-Werror,-Wthread-safety-analysis]

Mark both functions NO_THREAD_SAFETY_ANALYSIS so that libbfd.c compiles
with "make CC=clang BUILD_NONDISTRO=1".

Fixes: b72b8132d8 ("perf libbfd: Ensure libbfd is initialized prior to use")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Acked-by: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-22 14:44:13 +02:00
Ian Rogers 63394d0664 perf test: Isolate test suite from user .perfconfig natively
Running 'perf test' should not inherit the user's ~/.perfconfig
environment as customizing core properties (like core.hybrid-merge)
will trivially break stdout matching checks across the shell suite.

Explicitly set PERF_CONFIG to /dev/null inside cmd_test to globally
sandbox the environment for the entire test workflow. Test specific
config, like annotate.objdump, is read before the sandboxing so that
'perf test' still honors it.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:38:50 -03:00
Ian Rogers 06aa9ab061 perf test: Expand tests for --hybrid-merge
Add a "Hybrid event merging" test that checks evlist__can_merge_hybrid()
and evlist__merge_hybrid() directly, covering the events a wildcard
expanded to over two core PMUs, the same over three, and events that
must not be merged.

Add a report_hybrid_merge.sh shell test that records and then reports
with --hybrid-merge, and extend top.sh to cover perf top with it.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:38:26 -03:00
Ian Rogers 5c8edd351d perf config: Add core.hybrid-merge to configure event merging
Provide a core.hybrid-merge configuration option in .perfconfig to allow
enabling hybrid event aggregation by default, avoiding the need to pass
--hybrid-merge explicitly on every invocation.

The config value is a default rather than an explicit request, so with
--hierarchy it is ignored with a warning, while giving both --hierarchy
and --hybrid-merge on the command line remains an error.  For the same
reason it is silently ignored when there are no events to merge, as
would be the case on any machine with a single core PMU, whereas an
explicit --hybrid-merge still warns. Record whether the option came from
the command line in symbol_conf so both can tell the two apart.

'perf stat' has its own merging options for counting, the sampling
core.hybrid-merge deliberately doesn't alter it and its --hybrid-merge
must still be given explicitly.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:37:45 -03:00
Ian Rogers 59eca52494 perf tools: Add TUI hints for --hybrid-merge
Add dynamic TUI hints prompting users to restart with --hybrid-merge
when heterogeneous core PMU events are populated in the sample view.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Tested-by: Arnaldo Carvalho de Melo <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:37:04 -03:00
Ian Rogers a25262fb16 perf evlist: Toggle merged_hybrid_group properly in enable/disable
Merging makes the merged event the leader of the events of the other
core PMUs so their histograms can be linked, but the result isn't a real
event group. Each event keeps its own file descriptor and has to be
enabled and disabled in its own right.

__evlist__enable(), __evlist__disable() and evlist__is_enabled() skip
anything that isn't a group leader, and the first two then walk the
group members of the events they do act on. For a merged set that is
backwards: the members are skipped by the leader test, so their file
descriptors are never touched, and the walk over the leader's members
only updates the bookkeeping in evsel->disabled.

Treat an evsel with merged_hybrid_group set as a leader so that it is
enabled and disabled in its own right via its own file descriptors.

'perf top' enables and disables by event name. A merged member carries
the name of its own PMU rather than the name that was asked for, so also
match it against its leader's name, otherwise naming the event toggles
only part of the merged set.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:36:30 -03:00
Ian Rogers aa2bad59fd perf Documentation: Add tip for hybrid event merging
Add informative text outlining the IPC imbalances associated with
merging cross-hybrid core events like cycles.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Tested-by: Arnaldo Carvalho de Melo <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:35:55 -03:00
Ian Rogers 6fa291f805 perf tools: Expose opt-in --hybrid-merge
Add --hybrid-merge to perf report and perf top. It merges the events a
wildcard expanded to across the core PMUs, and their histograms, so
that a symbol which ran on more than one kind of core is reported once
with the total rather than once per PMU.

evlist__merge_hybrid() links the events and evlist__merge_hists_hybrid()
links the histograms. There is nothing to merge on a machine with a
single core PMU, or when the events didn't come from a wildcard, so
warn in that case rather than quietly producing an unmerged report.

Merging collapses the per-PMU entries into one set, which doesn't
combine with the per-level breakdown of --hierarchy, so asking for both
is an error.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Tested-by: Arnaldo Carvalho de Melo <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:29:34 -03:00
Ian Rogers bcb89e6320 perf ui hist: Add support for aggregated total_period and merging entries
Add the histogram side of hybrid event merging.

When events are merged the entries of the other events are linked to
the leader's entries as pairs, and a row is then displayed as the sum
over an entry and its pairs. Teach the hpp code to work on that sum:

 - The formatting and sorting routines add up the value of an entry and
   of each of its pairs, so a row shows, and is sorted by, the total
   across the core PMUs rather than the leader's value alone.
 - Percentages are taken against the summed total_period of the merged
   hists. Computing each event's share against its own PMU's total
   would leave the column not adding up to 100%.
   hist_entry__get_percent_limit_merged() does the same for
   --percent-limit, which would otherwise compare against the wrong
   total and filter out the wrong entries.
 - A header and column width are reserved for the "Total" the merged
   value is shown under.

evlist__merge_hists_hybrid() links the hists together and resorts the
result so that it is ordered by the merged total.

hists__link() is run once for every event merged into the leader, so an
entry can be offered as a pair more than once. hist_entry__add_pair()
used list_add_tail() unconditionally, which corrupts the list when the
entry is already on one. Return early if the entry is already paired
with this one, and use list_move_tail() so that an entry linked
elsewhere is moved rather than added a second time.

Merging is never combined with --hierarchy, which the merge_entries
tests rely on.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:28:52 -03:00
Ian Rogers ce7948448d perf evlist: Implement evlist__can_merge_hybrid using first_wildcard_match
Add logic to dynamically identify mergeable events spawned from the
same wildcard alias via first_wildcard_match. first_wildcard_match is
populated when events are parsed, in `perf report` the events come
from a file and so the first_wildcard_match is computed by matching
event names.

evlist__can_merge_hybrid only tests whether merging is possible and
doesn't modify the evlist, so that it may be used as a predicate, for
example, to decide whether to display a hint. The linking of all the
matching events is done by evlist__merge_hybrid.

is_pmu_core_len identifies core PMUs using the hybrid topology of the
perf.data file. Should the file lack the topology, the PMUs of this
machine are scanned but only when the file was recorded on the same
architecture, as PMU names like "cpu_core" are architecture specific.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:26:41 -03:00
Ian Rogers 3d8fb5a4a1 perf libbfd: Report success when an address is found
libbfd__addr2line() only reports success when the caller asked for a file
name. addr2inlines() passes a NULL file as it just wants the inline_node
populating, so libbfd__addr2line() returns 0 for it unless
bfd_find_inliner_info() happened to find an inline frame.

addr2line() in srcline.c treats 0 as a failure and tries the next
addr2line implementation, which appends its own frames to the
inline_node libbfd already appended to.

Every frame that isn't inlined is then reported twice, which happens by
default when perf is built with libbfd but without libdw as the fallback
order is then libbfd followed by the addr2line command:

  $ perf record --call-graph dwarf -- perf test -w inlineloop 1
  $ perf script --fields +srcline
  ...
	    56051a994f8e parent+0x2e (perf)
    inlineloop.c:32
	    56051a99503a inlineloop+0x8a (perf)
    inlineloop.c:47
	    56051a99503a inlineloop+0x8a (perf)
    inlineloop.c:47
	    56051a95841a cmd_test+0xb7a (perf)
    ??:0
	    56051a95841a cmd_test+0xb7a (perf)
    ??:0
  ...

Report success whenever the address is found, like libdw__addr2line()
does, and clear the frames appended so far when appending fails so that a
following implementation starts from an empty node.

Fixes: 257046a367 ("perf srcline: Fallback between addr2line implementations")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Cc: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:24:49 -03:00
Ian Rogers f651c02755 perf dso: Separate libbfd and cmd addr2line caches to fix confusion
When a dso executes addr2line via libbfd it instantiates an a2l_data
pointer. If the DSO later executes via the command-line fallback due
to an inlined bug, the a2l pointer is unconditionally populated with a
child_process process wrapper.

If libbfd is queried again, the offline reader attempts to cast struct
a2l_data into child_process, coercing random arbitrary instruction
addresses and causing silent aborts. This cleanly splits the caches.

Fixes: 257046a367 ("perf srcline: Fallback between addr2line implementations")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:23:59 -03:00
Ian Rogers bf96e296d5 perf libdw: Fix Dwfl discovery with split files
dso__libdw_dwfl() opens the Dwfl with dso__long_name(), the file the
samples came from. When the debug information lives in a separate file,
symbol loading finds it and records it as the dso's symsrc filename, but
the Dwfl still refers to the original file, so libdw has no DWARF to
resolve addresses against.

Open the Dwfl with the symsrc filename when one is known and fall back
to the long name when it isn't.

The symsrc file is found while symbols are loaded, which can happen
after the Dwfl has been created and cached, so drop the cached Dwfl and
the addr2line cache built from it when the symsrc filename is set.  That
teardown can run while another thread is using the cache, so take the
dso lock across both the teardown and the Dwfl accessors, and re-read
dso__symsrc_filename() under the dso lock in libbfd__addr2line() and
cmd__addr2line() to prevent a TOCTOU race with cache invalidation.

Fixes: b7a2b011e9 ("perf powerpc: Unify the skip-callchain-idx libdw with that for addr2line")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-18 17:23:16 -03:00
Ian Rogers 3cbb16ccd7 perf record: Fix unhandled POLLHUP on non_perf_event descriptors
When processing POLLHUP on a non_perf_event control descriptor,
evlist__finalize_ctlfd() is invoked to finalize the setup, correctly
setting the core evlist's poll array file descriptor to -1. However,
this finalized teardown state is never propagated back to the
individual thread's local replica of the pollfd array.

Consequently, on the next iteration of the main recording loop,
record__update_evlist_pollfd_from_thread() performs a strict
equivalence check between the core evlist's array and the thread's
localized poll array, detecting that the fd values no longer match.
This causes an immediate -EINVAL abort and a premature teardown.

Fix the underlying logic within
record__update_evlist_pollfd_from_thread() to sustainably propagate
the finalized teardown statuses (-1) originating from the core evlist
back to the thread's localized poll structure. This correctly
maintains synchronization and entirely prevents the unhandled
index mismatch crashes.

Additionally, add a unit test that explicitly validates that
fdarray__filter() preserves its invariants regarding
fdarray_flag__nonfilterable items to guard against regressions.

Fixes: fb4751e79c ("perf record: Fix teardown hang on system-wide multi-threaded sessions")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Gemini:gemini-3.1-pro
Cc: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-17 12:27:34 -03:00
Ian Rogers 5a8e536e5f perf jevents: Add mesh bandwidth saturation for CWF, EMR, GRR, SNR, SPR, SRF
Extend the mesh bandwidth saturation's list of events to include events
from clearwaterforest, emeraldrapids, grandridge, graniterapids,
sapphirerapids and sierraforest. This makes the lpm_mem_sat metric
available for those CPU models.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-13 21:43:20 -03:00
Ian Rogers f945859da4 perf header: Transition WARN macros to debug.h equivalents
Avoid a checkpatch.pl warning on the use of asm/bug.h by switching the
use of WARN macros to explicit tests and then using pr_warning from
debug.h.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-13 18:42:16 -03:00
Ian Rogers d964ffba01 perf header: Fix potential memory corruption in cpu_cache_level__read
strim() may advance the pointer assigned to cache->size which causes
later frees to crash.

Fix by performing the strim and then memmove-ing the potentially shifted
string back over the original string.

The bug was introduced by the transition from rtrim() to strim(), as
rtrim() wouldn't move on the left.

Fixes: 13c230ab6e ("perf tools: Ditch rtrim(), use strim() from tools/lib")
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-13 18:41:36 -03:00
Ian Rogers 811d1ddf97 perf header: Fix HEADER_COMPRESSED validation for comp_mmap_len
This commit updates process_compressed() to ignore comp_mmap_len == 0
when validating the compressed header. A zero size is valid and may
occur during testing.

Sashiko review flagged string.h was missing (preexisting problem) and
so I opportunistically fixed this and sorted the header files.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-13 18:41:05 -03:00
Ian Rogers dd93c3b939 perf python: Fix ilist TreeNode string type drift
Updates Tree type hints to correctly use TreeNode[TreeValue]
across all assignments preventing mypy strictness mismatches.

Address some other minor stylistic issues reported by mypy, pylint and
Sashiko.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-13 18:39:12 -03:00
Ian Rogers c5429ac2d1 tools build: Fix timerfd feature detection with clang
Clang's uninitialized-const-pointer warning causes a feature test to
fail when building perf with clang. This disables support for 'perf
kvm stat live'. Add default initialization to new_value as a
workaround.

  test-timerfd.c:15:30: error: variable 'new_value' is uninitialized when passed
			       as a const pointer argument here
			       [-Werror,-Wuninitialized-const-pointer]
     15 |         if (timerfd_settime(fd, 0, &new_value, NULL) != 0)
        |                                     ^~~~~~~~~
  1 error generated.

Signed-off-by: Ian Rogers <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-12 17:22:18 -03:00
Ian Rogers 9d527dc79e perf test x86: Fix missing __msan_unpoison
__msan_unpoison may need the sanitizer header including for its
definition.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-10 11:08:10 -03:00
Ian Rogers 26c137421f perf tool: Align structs in arrays in .clang-format
Configure clang-format to ensure structs within arrays maintain left
alignment inside tools/perf/.clang-format. This prevents standard
formatting runs from arbitrarily squashing tabbed initialization pillars.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-09 17:03:35 -03:00
Ian Rogers 1572ba36fb perf tests: Improvements to build-test performance
Replace hardcoded 'make' calls with '$(MAKE)' within tests/make
to ensure GNU Make jobserver file descriptors are properly inherited
by nested builds.

Additionally, remove the notorious 'unexport MAKEFLAGS' from
tools/perf/Makefile. This hack was originally added to prevent
the wrapper's internal '-j$(JOBS)' override from crashing when parent
jobserver tokens were present. Instead, use proper GNU Make conditionals
to check for '-j' or 'jobserver' strings within MAKEFLAGS. If a jobserver
is already orchestrating the build, gracefully back off and let GNU Make
manage parallelism natively.

Finally, optimize the 'out' target (which processes 'run_O' out-of-tree
builds) by stripping sequential bottlenecks like $(call clean) from
isolated tmp directories, and wrapping the target list in a parallel
sub-make call.

These combined changes enable 'build-test' out-of-tree targets to
build completely concurrently without severing jobserver tokens.

Unscientifically measured the change lowered the build-test from
around 15 minutes to 10 minutes on a 28 threaded Alderlake CPU. Fixing
the jobserver issues meant the machine remained somewhat usable while
running the test.

Tested-by: Arnaldo Carvalho de Melo <[email protected]>
Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-09 17:00:36 -03:00
Ian Rogers 93fd7adf1a perf stat: Avoid uninitialized memory read on error
If has_supported_counters fails then msg was passed to ui__error
regardless of whether an error was written into msg leading to reading
uninitialized memory. Avoid this by always terminating msg at
initialization.

Opportunistically reduce the scope of msg to make its use clearer.

Fixes: c9a8c343ef ("perf stat: When no events, don't report an error if there is none")
Signed-off-by: Ian Rogers <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-09 08:10:17 -03:00
Ian Rogers 4bbcb0fb9b perf test: Avoid call to missing cleanup function
Cleanup function was removed by writing to /dev/null rather than
temporary files. The exit path still had a call.

Fixes: 44f6b44027 ("perf test: Fix hybrid testing of event fallback test")
Reviewed-by: Dapeng Mi <[email protected]>
Signed-off-by: Ian Rogers <[email protected]>
Cc: Namhyung Kim <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 18:13:52 -03:00
Ian Rogers 537ff9c427 perf hist: Remove keysym.h include from hist.h
hist.h isn't related to UI and so remove the UI inclusion. Fix the
transitive dependency issues this exposes.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:37 -03:00
Ian Rogers d845187d47 perf tool: Add fallback stubs for missing dependencies
Declare stubs directly inside perf.c for commands that have library
dependencies sometimes omitted at build time, such as libtraceevent
(timechart, sched, kmem, lock, trace, kwork) and libelf (probe).

By unconditionally including these commands in the commands[] array,
users will receive a clear, unified warning indicating the missing
dependency instead of the command silently being absent.

Running `perf trace` with libtraceevent missing. Before:
```
perf: 'trace' is not a perf-command. See 'perf --help'.

Did you mean this?
        ftrace
```

After:
```
'trace' command not available: missing libtraceevent devel package at build time.
```

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:34 -03:00
Ian Rogers c6b40a6425 perf tool: Move usage strings and functions to perf.c
The code is mostly used by perf.c with additional unused functionality
such as function pointers derived from early git code. Moving it into
perf.c directly reduces the code footprint, drops the util/util.h
dependence from perf.c, and allows us to remove util/usage.c entirely.

The string constants are exposed in builtin.h, as they are used
in builtin-help.c.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:32 -03:00
Ian Rogers bc8af6295a perf tool: Remove unused includes in perf.c
Remove perf-sys.h, internal/lib.h (page_size), signal.h, and perf.h
since their exports are not used directly in perf.c.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:30 -03:00
Ian Rogers 583ba92ef0 perf tool: Tidy up util/cache.h header file users
Use git clang-format to sort header files. Review header file includes
removing those that were unnecessary or adding explicit includes in
cases where transitive dependencies were be using.

Signed-off-by: Ian Rogers <[email protected]>
Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:28 -03:00
Ian Rogers 7071a2871c perf tool: Remove util/cache.h
Move definitions to places they are used, or path.h in the case of
path.c's mkpath function. Remove unused definitions. Fix transitive
include dependencies.

Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
2026-09-08 17:50:25 -03:00
Ian Rogers 78148c8529 perf evlist: Warn when 'sleep' workload is used without system-wide (-a) option
A common mistake when trying to record system-wide profiles for a given
duration is running commands like 'perf record sleep 1' or 'perf stat
sleep 1' without passing '-a' / '--all-cpus'. When '-a' is omitted, perf
defaults to per-process monitoring of the sleep process itself, which
does not collect system-wide activity and records very few events.

Add a warning in evlist__prepare_workload() when the workload executable
is 'sleep' and system-wide mode is not enabled.

Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-17 16:04:06 -07:00
Ian Rogers 16a12a54e9 perf synthetic-events: Fix divide by zero in perf_event__synthesize_threads
If scandir() finds no matching tasks in /proc, n is 0. If thread_nr is > 1,
we bypass the single-thread fast path and then clamp thread_nr to n, making
it 0. This results in a divide by zero when calculating num_per_thread.

Handle n <= 1 early to use the single-thread fast path and prevent the
crash.

Fixes: 340b47f510 ("perf top: Implement multithreading for perf_event__synthesize_threads")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 22:02:42 -07:00
Ian Rogers 1ec13016ba perf python: Fix memory leak in pyrf__metrics_cb
In pyrf__metrics_cb, PyDict_SetItem does not steal the reference of the
key and value, so they need to be decref'ed after successful insertion
to avoid memory leaks.

Fixes: 47b3e95728 ("perf python: Add metrics function")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 22:02:41 -07:00
Ian Rogers cb45ede21d perf python: Fix count_values memory leak in pyrf_evsel__read
In pyrf_evsel__read, if PyArg_ParseTuple fails, the allocated count_values
is leaked. Move the allocation of count_values after the PyArg_ParseTuple
call to prevent the memory leak.

Fixes: 739621f657 ("perf python: Add evsel read method")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 22:02:41 -07:00
Ian Rogers b9514a9a13 perf python: Fix MetricGroup return type in perf.pyi
The metrics() function can return a dictionary where the value is either
a string or a list of strings, so the type signature in the stub file
should be Union[str, List[str]].

Fixes: 430da3cd03b4 ("perf python: Add perf.pyi stubs file")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 22:02:41 -07:00
Ian Rogers b3d7c6c1a9 perf python: Add thread and PMU uninitialized checks
Add CHECK_INITIALIZED checks to the thread attribute getters
(get_pid, get_tid, get_ppid) to prevent crashes if they are accessed
before being properly initialized.

Fixes: 3b96bf7af60d ("perf python: Add python session abstraction wrapping perf's session")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 22:02:38 -07:00
Ian Rogers b365402cd5 perf python: Zero initialize perf_data in pyrf_data__init
Replace path clearing with memset so the entire struct is zeroed,
preventing uninitialized fields from causing errors later.

Fixes: 4cd0142f7dec ("perf python: Add wrapper for perf_data file abstraction")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 21:58:11 -07:00
Ian Rogers 0b274050c4 perf python: Validate attribute setters in pyrf_evsel
If val is NULL when setting an attribute, PyErr_SetString should be
called as deleting the attribute isn't supported. In addition, ensure
PyErr_Occurred is checked before setting the attribute to avoid setting
a garbage value.

Fixes: 877108e42b ("perf tools: Initial python binding")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 21:58:11 -07:00
Ian Rogers 9a142beb1e perf python: Validate CPU and thread maps in pyrf_evsel__open
Add explicit Py_TYPE checks to ensure the arguments passed are
actually of the correct pyrf_thread_map and pyrf_cpu_map types.

Fixes: 877108e42b ("perf tools: Initial python binding")
Signed-off-by: Ian Rogers <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-08-09 21:58:11 -07:00