summaryrefslogtreecommitdiff
path: root/tools/perf/util
AgeCommit message (Collapse)Author
12 daysperf evlist: Warn when 'sleep' workload is used without system-wide (-a) optionIan Rogers
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 <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add function view browser UI and cacheline detailJiebin Sun
Add the browser front end: create/run/delete the hist_browser and add the title. The d shortcut opens the existing per-cacheline detail view for the selected level-3 cacheline. Level-3 entries retain the source cacheline index, so the shortcut can locate the original entry without relying on a potentially ambiguous virtual address. Report a warning when the common model rejects a cacheline coalescing field list without `iaddr`. Without it, the detail histograms may already have merged samples from different functions and cannot support reliable function attribution. Keep visible-row accounting local to the function view by wrapping the generic browser refresh callback and recounting the currently reachable hierarchy before each redraw. This keeps navigation correct when a level-1 row is collapsed while level-3 descendants remain expanded, without adding C2C-specific hooks to the shared hist_browser. Also handle Ctrl-C like the other function-view exit keys. Keep callchains hidden while the function browser runs, restoring the user's setting while opening the cacheline detail view. Wire the builder into perf_c2c__browse_function_view(). Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: build and finalize the function view hierarchyJiebin Sun
Add the builder that walks the top-level cacheline entries and, for each read-side function, correlates the functions that write the same lines (level 2) and the specific cachelines they contend over (level 3) within each retained detail histogram. Aggregate the write traffic per contending function, resort by store count, and prune writers/functions with no contention. The finalize pass then computes the Cycles % denominator from the surviving level-1 entries after pruning, so the column shows each function's share of the functions retained in the table rather than of the whole recording -- the semantics documented for Cycles % in perf-c2c.txt. Expose c2c_function__build() and c2c_function__reset() for the TUI front end added by the next patch. The builder requires iaddr in the cacheline coalescing fields and returns the completed hists through an output argument. Validate the inputs before replacing an existing model. Function-view entries do not carry callchains. Suppress callchain handling while building and tearing down the model so the common API does not depend on the caller's current callchain setting. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add function view hierarchy entry creationJiebin Sun
Add the entry-creation layer: owned-reference child allocation and insertion, and the level-1/2/3 lookup-or-create functions keyed by function symbol (level 1 read-side, level 2 writer) and by the source cacheline's existing index (level 3). Give synthetic children normal entry operations and acquire their thread and map-symbol references. This lets the hierarchy teardown use hist_entry__delete() for the common fields while the function-view free callback handles the private child tree and containing allocation. Reuse cacheline_idx to preserve the source entry identity without adding function-view-only state. Add c2c_function__find_cacheline() to locate the original cacheline entry by the same index. These are driven by the hierarchy builder in the next patch and are __maybe_unused until then. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add function view stats merge and memory managementJiebin Sun
Add the per-entry stats/cstats aggregation helpers and hierarchy teardown. Child common fields are released through hist_entry__delete(), while the function-view free callback handles the private child tree and containing allocation. Also add a helper for pruning writer entries with no stores or cacheline children. These are used by the entry-creation and builder patches that follow and are __maybe_unused until then. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add HPP list parsing for function view columnsJiebin Sun
Add the parser that builds the function view's local HPP output and sort lists from field strings. This includes dimension lookup, comparator wrappers, c2c_fmt allocation, and the initialization entry points used by the hierarchy builder. The generic perf_hpp__setup_output_field() registers formats on the global perf_hpp_list. Using it here would leave the function view's local list without output columns and modify the cacheline view's list instead. Add c2c_function_hists__setup_output_field() to append sort keys to the local output list. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add column rendering for function viewJiebin Sun
Add renderers for the function view's Cycles %, Store count, and hierarchy identity columns. The identity column renders the read-side function, contending writer, or cacheline, with indentation for the hierarchy level. Also add width and header helpers, estimated-cycle calculation, comparators, and the dimension table that ties them together. Clamp the identity renderer's returned length to its local buffer before using it for pointer and padding calculations. This handles snprintf-style would-have-been lengths without changing normal output. The next patch connects these dimensions to the view's HPP lists, so the symbols used only there are temporarily marked __maybe_unused. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: add function view model skeletonJiebin Sun
Add the initial common model for the c2c function view: model state and small helpers shared by the hierarchy construction and formatting added in later patches. Build the model from util/ so it remains independent of the TUI and command-private symbols. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
12 daysperf c2c: extract shared data structures into util/c2c.hJiebin Sun
The function browser belongs in libperf-ui.a, but that archive is also linked into python/perf.so, where builtin command objects are unavailable. The browser therefore cannot depend on types or callbacks owned by builtin-c2c.c. Move c2c_hists, compute_stats, c2c_hist_entry, and the shared column formatting definitions from builtin-c2c.c to a new util/c2c.h. Move c2c_fmt_free() and c2c_fmt_equal() to a new util/c2c.c. Keep struct perf_c2c, the command instance, and perf_c2c__browse_cacheline() private to builtin-c2c.c. No functional change. Signed-off-by: Jiebin Sun <jiebin.sun@intel.com> Reviewed-by: Tianyou Li <tianyou.li@intel.com> Reviewed-by: Wangyang Guo <wangyang.guo@intel.com> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Dapeng Mi <dapeng1.mi@linux.intel.com> Cc: James Clark <james.clark@linaro.org> Cc: Thomas Falcon <thomas.falcon@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
14 daysperf dso: Replace assert with runtime check in dso__read_symbol()Arnaldo Carvalho de Melo
dso__read_symbol() asserts that len <= jited_prog_len, where len comes from sym->end - sym->start (parsed from PERF_RECORD_KSYMBOL in perf.data). Both values originate from untrusted file input. With NDEBUG (production builds), the assert is compiled out, allowing an out-of-bounds heap read when the BPF program buffer is accessed. Without NDEBUG, a crafted perf.data crashes perf with an assertion failure. Replace the assert with a runtime bounds check that returns NULL with an appropriate error code, matching the existing error handling pattern in this function. Fixes: aa04707f507e ("perf dso: Support BPF programs in dso__read_symbol()") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Reviewed-by: Ian Rogers <irogers@google.com> Cc: Song Liu <song@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
14 daysperf dso: Guard against cache underflow on short reads in dso_cache__memcpy()Arnaldo Carvalho de Melo
dso_cache__memcpy() computes cache_offset = offset - cache->offset, then cache_size = min(cache->size - cache_offset, size). The RB tree lookup in __dso_cache__find() matches using the full DSO__DATA_CACHE_SIZE window, but cache->size reflects the actual pread return value from dso_cache__populate(). A short pread (e.g. near end-of-file) makes cache->size smaller than DSO__DATA_CACHE_SIZE. If a subsequent access targets an offset past cache->offset + cache->size but within the DSO__DATA_CACHE_SIZE window, the cache entry is found but cache_offset exceeds cache->size. Since both are u64, the subtraction cache->size - cache_offset wraps to a large value, min() selects the caller's size, and memcpy reads out of bounds. Return 0 for an offset past the valid cached data. For a regular file a short pread only happens at end-of-file, so 0 is what a direct pread() at that offset would return: cached_io() stops its read loop as on EOF. Re-reading from the backing file would not help — a second pread at the same offset returns the same short count. Fixes: 366df72657e0 ("perf dso: Refactor dso_cache__read()") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
14 daysperf dso: Use stored fd error instead of stale errno in file_read() and ↵Arnaldo Carvalho de Melo
file_size() file_read() and file_size() use ret = -errno when dso__data(dso)->fd is negative after try_to_open_dso() fails. By this point errno has been through mutex_lock(), nsinfo__mountns_enter(), and multiple open() attempts inside try_to_open_dso() — it no longer reflects the actual open failure. If errno happens to be 0, ret = 0 looks like EOF rather than an error, and file_size() callers like dso__data_size() would then report a zero-sized file instead of failing. dso__data(dso)->fd is always negative on failure — -errno from __open_dso() when no filename could be built (e.g. -EINVAL, -ENOENT), or -1 when do_open() itself failed — and never 0, so use it directly instead of reading the stale global errno. No assert() or comment is needed after the assignment: the enclosing if (dso__data(dso)->fd < 0) already guarantees ret < 0 [Namhyung Kim review]. Fixes: 33bdedcea2d7 ("perf tools: Protect dso cache fd with a mutex") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
14 daysperf dso: Guard close() against invalid fd in dso__decompress_kmodule_path()Arnaldo Carvalho de Melo
dso__decompress_kmodule_path() unconditionally calls close(fd) on the return value of decompress_kmodule(). When decompression fails or the DSO is not compressed, decompress_kmodule() returns -1. close(-1) fails with EBADF and clobbers errno, which callers up the chain (dso__get_filename → __open_dso) depend on for error propagation. Guard the close() call with fd >= 0 so only valid file descriptors are closed. Fixes: 42b3fa670825 ("perf tools: Introduce dso__decompress_kmodule_{fd,path}") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
14 daysperf dso: Guard against errno==0 when dso__get_filename() returns NULLArnaldo Carvalho de Melo
__open_dso() computes fd = -errno when dso__get_filename() returns NULL. Some failure paths in dso__get_filename() (e.g. binary type mismatch) return NULL without making a syscall, leaving errno at 0 from a prior successful call. fd = -0 = 0, which is stdin — subsequent code treats it as a valid file descriptor. Fall back to ENOENT when errno is 0, ensuring fd is always negative on failure. The forced ENOENT stays in errno for the callers that check it after a negative fd. It must not misdirect the try_to_open_dso() fallback loop, though: dso__get_filename()'s chroot fallback used to accept a stale ENOENT even when stat() succeeded on a non-regular file (e.g. a directory). Re-stat() there and only take the chroot path when stat() actually failed with ENOENT [sashiko-bot review of PATCH 1/5]. Fixes: eba5102d2f0b ("perf tools: Add global list of opened dso objects") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf synthetic-events: Fix divide by zero in perf_event__synthesize_threadsIan Rogers
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: 340b47f510bb ("perf top: Implement multithreading for perf_event__synthesize_threads") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Fix memory leak in pyrf__metrics_cbIan Rogers
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: 47b3e95728eb ("perf python: Add metrics function") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Fix count_values memory leak in pyrf_evsel__readIan Rogers
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: 739621f65702 ("perf python: Add evsel read method") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Add thread and PMU uninitialized checksIan Rogers
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 <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Zero initialize perf_data in pyrf_data__initIan Rogers
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 <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Validate attribute setters in pyrf_evselIan Rogers
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: 877108e42b1b ("perf tools: Initial python binding") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Validate CPU and thread maps in pyrf_evsel__openIan Rogers
Add explicit Py_TYPE checks to ensure the arguments passed are actually of the correct pyrf_thread_map and pyrf_cpu_map types. Fixes: 877108e42b1b ("perf tools: Initial python binding") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Check counts_values size in set_valuesIan Rogers
The set_values function incorrectly assumed the list contained exactly 5 elements. Add a check to prevent out-of-bounds access. Fixes: 877108e42b1b ("perf tools: Initial python binding") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf synthetic-events: Fix uninitialized pthread_joinIan Rogers
In perf_event__synthesize_threads(), fix an uninitialized pthread_join() call when thread creation fails by only joining the successfully created threads. Assisted-by: Antigravity:gemini-3.1-pro Fixes: 340b47f510bb ("perf top: Implement multithreading for perf_event__synthesize_threads") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-09perf python: Fix memory leak in pyrf_evlist__get_pollfdIan Rogers
Fix a Python list object leak in pyrf_evlist__get_pollfd() by adding a missing Py_DECREF on the error exit path. Assisted-by: Antigravity:gemini-3.1-pro Fixes: 877108e42b1b ("perf tools: Initial python binding") Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf synthetic-events: Fix bounds and union member access in mmap2 build_id ↵Ian Rogers
synthesis Modify bounds and union member access in mmap2 build_id synthesis. Bound max_filename_len against the minimum of filename array capacity and the outer union stack layout minus sample ID trailers. This prevents both -E2BIG overruns and _FORTIFY_SOURCE array bounds aborts on strlcpy even if the enclosing union expands. Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf synthetic-events: Fix bounds, stale state, and misc flags in kernel ↵Ian Rogers
module synthesis Clamp long DSO names to mmap/mmap2 filename boundaries accounting for sample ID headers to prevent buffer overruns in perf_event__synthesize_modules_maps_cb(). Explicitly clear misc flags and union padding to prevent stale Build-ID state from leaking between module synthesis events, and cast event buffer pointers to avoid _FORTIFY_SOURCE array bounds aborts when zeroing padding trailers. Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf synthetic-events: Fix stack buffer overflow and bounds in cgroup synthesisIan Rogers
Fix a pre-existing stack buffer overflow bug in perf_event__synthesize_cgroup() where an in-place null padding loop wrote bytes past the end of the cgrp_root stack array buffer during cgroup tree traversal. Eliminate in-place path mutation, use PERF_ALIGN for path_len, clamp raw_path_len to prevent sample ID header trailer overruns, and use strlcpy with combined zero padding for alignment and sample ID headers. Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf synthetic-events: Fix line synchronization, bounds, and truncation bugs ↵Ian Rogers
in proc maps reader Fix critical logic and boundary bugs in read_proc_maps_line() and caller. Ensure any mid-line hex/dec/char parsing failure invokes io__drain_line() safely, using a do-while loop to read and discard remaining characters until a newline or EOF is reached. Clamp pathname extraction size to account for trailing sample ID headers, use standard '//toolong' fallback literal for over-length pathnames, emit timeout flags for truncated entries securely via goto out;, and cast event buffer pointers to avoid _FORTIFY_SOURCE array bounds aborts across synthesis handlers. Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf find-map: Remove PATH_MAX 128-byte stack array restrictionIan Rogers
Use getline() to dynamically allocate the required line buffer for maps parsing, guaranteeing bounds safety and avoiding compiler warnings by evaluating the return value in the loop condition directly. Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf trace-event: Fix infinite loop in skip()Tanushree Shah
skip() ignores do_read()'s return value and unconditionally subtracts the requested chunk size from 'size' on every iteration. This was previously bounded by size being 'int': a maliciously large 64-bit value was truncated on assignment, capping the loop early by accident. Now that size is size_t, a crafted file supplying a very large size causes skip() to keep requesting BUFSIZ-sized reads and subtracting BUFSIZ from size regardless of whether do_read() actually succeeds, spinning indefinitely even after EOF or a read error. Check do_read()'s return value and break out of the loop on failure or EOF, so forward progress is only counted when a read actually succeeds. Signed-off-by: Tanushree Shah <tshah@linux.ibm.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf trace-event: Fix heap overflows in ↵Tanushree Shah
read_ftrace_printk()/read_saved_cmdline() Both functions read an attacker-controlled size directly from the input file and pass size + 1 to malloc() before reading size bytes into the result: read_ftrace_printk(): size is an unsigned int from read4(). When size == UINT_MAX, size + 1 overflows to 0, so malloc(0) returns a minimal allocation while size itself remains UINT_MAX. read_saved_cmdline(): size is an unsigned long long from read8(). When size == ULLONG_MAX, size + 1 overflows to 0 the same way. In both cases, do_read(buf, size) then attempts to read the full, unwrapped size into the tiny allocated buffer, a heap buffer overflow. This was previously masked by do_read()'s size parameter being 'int': passing these values truncated them, which the read() syscall's own boundary checks rejected before any data was read. Fixing that truncation (widening do_read() to size_t) is correct on its own, but it removes this accidental protection and exposes the pre-existing missing bounds check in both functions. Reject the one value that causes the overflow before it's used, in each function. Signed-off-by: Tanushree Shah <tshah@linux.ibm.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf trace-event: Avoid double free and leak in ↵Tanushree Shah
trace_event__cleanup()/trace_event__init() trace_event__cleanup() frees t->pevent but never clears the pointer. It can be called twice on the same trace_event: once from trace_report()'s error path, and again from perf_session__delete() during session teardown, resulting in a double free / use-after-free. Separately, trace_event__init() overwrites t->pevent/t->plugin_list without releasing any existing handle, leaking memory if it's called more than once on the same struct. eg. via a perf.data file with multiple PERF_RECORD_HEADER_TRACING_DATA headers. Guard against re-entry by returning early if t->pevent is already NULL, and clear it after cleanup so a repeat call is a safe no-op. Call trace_event__cleanup() at the start of trace_event__init(), so a repeated init releases any existing handle before allocating a new one. Signed-off-by: Tanushree Shah <tshah@linux.ibm.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-07perf trace-event: Fix integer truncation in do_read() and skip()Tanushree Shah
The do_read() and skip() functions use 'int' for size parameters, truncating 64-bit sizes from callers. This causes two issues: 1. Uninitialized memory dump: do_read() reads fewer bytes than allocated, leaving uninitialized heap memory that gets written to output files. 2. Out-of-bounds read: Parsing functions process the full 64-bit size while only partial data was read into the buffer. Change do_read(), __do_read(), and skip() to use size_t for size parameters and ssize_t for return values (where applicable), matching read()/write() system calls. Update callers to use ssize_t for storing return values. Fixes: 4a31e56599d4 ("perf tools: Get rid of read_or_die() in trace-event-read.c") Signed-off-by: Tanushree Shah <tshah@linux.ibm.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-06perf trace-event: Fix buffer overflow in read_string()Tanushree Shah
read_string() writes into buf[BUFSIZ] one byte at a time without checking 'size' against the buffer bound before each write. A string longer than BUFSIZ in the input overflows the stack buffer. Add a bounds check before each write to prevent overflow. On overflow the function returns NULL, matching its other error paths. Fixes: 9215545e99d8 ("perf: Convert perf tracing data into a tracing_data event") Signed-off-by: Tanushree Shah <tshah@linux.ibm.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-05perf c2c: Fix error masking, OOM, and unchecked caller errors in ↵Arnaldo Carvalho de Melo
hpp_list__parse() hpp_list__parse() has three bugs: 1. The PARSE_LIST macro resets ret = 0 at the start of each invocation, so an error from output parsing is silently overwritten when the sort parsing block runs. The function returns success with partially initialized state. 2. When the caller passes a non-NULL output_ or sort_ string, but strdup() returns NULL due to OOM, NULL is passed to PARSE_LIST which treats it as empty input (the "if (!_list) break" branch). No error is returned. 3. When the called _fn function fails and returns something other than -ESRCH or -EINVAL (-ENOMEM, for instance) it was not bailing out of the strtok loop. Fix them by checking strdup() return values before proceeding and adding a cleanup label so that ret from each PARSE_LIST call is checked before the next runs, preserving the first error. The early exits now skip perf_hpp__setup_output_field(), which means c2c_hists__reinit() can return a non-zero value in cases that previously always succeeded silently. Both callers discarded its return: resort_cl_cb() continued into hists__collapse_resort() on a broken list, and perf_c2c__report() proceeded with uninitialised hists. Fix the full chain: check and propagate the error in resort_cl_cb() -- hists__iterate_cb() already stops iteration and returns the callback error -- and check both c2c_hists__reinit() and hists__iterate_cb() in perf_c2c__report(). Also turn PARSE_LIST into a function, using a switch to catch other errors, converting the called functions to return an appropriate errno instead of -1 on failure. Also make the two callers that iterate sort_dimension__add() and output_field_add() handle the newly propagated errors: setup_sort_list() and setup_output_list() only checked for -EINVAL and -ESRCH, so an -ENOMEM from a failed allocation was silently overwritten by the next loop iteration. Break out of the loop and propagate any other error. The hpp_list__parse() fixes were developed with AI assistance from Claude:claude-sonnet-4.6, and the setup_sort_list()/setup_output_list() caller fixes with AI assistance from Opencode:mimo-v2.5-free and Opencode:DeepSeek-V4-Flash-free. Fixes: 2d388bd0c9d3 ("perf c2c report: Add stdio output support") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Jiri Olsa <jolsa@kernel.org> Assisted-by: Claude:claude-sonnet-4.6 Assisted-by: Opencode:mimo-v2.5-free Assisted-by: Opencode:DeepSeek-V4-Flash-free Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: Ian Rogers <irogers@google.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-05perf libbfd: Fix memory leaks and NULL fclose in BPF disassemblyArnaldo Carvalho de Melo
symbol__disassemble_bpf_libbfd() has four resource management bugs: 1. free(prog_linfo) leaks internal arrays. bpf_prog_linfo contains raw_linfo, raw_jited_linfo, nr_jited_linfo_per_func, and jited_linfo_func_idx pointers that are only freed by the proper destructor bpf_prog_linfo__free(). 2. open_memstream(&buf, &buf_size) allocates a dynamic buffer that the caller must free after fclose(). The function calls fclose(s) but never free(buf), leaking the stream buffer on every call. 3. args->line = strdup(srcline) is immediately consumed by disasm_line__new(args) which internally calls strdup(args->line) again via annotation_line__init(). The first strdup result is then overwritten by args->line = buf + prev_buf_size without being freed. 4. If open_memstream() fails, the error path jumps to 'out:' which calls fclose(s) with s == NULL — undefined behavior. Fix by using bpf_prog_linfo__free(), initializing buf to NULL, adding free(buf) after fclose(s), guarding fclose() against NULL, and removing the redundant strdup since annotation_line__init() makes its own copy. Fixes: 6987561c9e86eace ("perf annotate: Enable annotation of BPF programs") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Song Liu <songliubraving@fb.com> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-05perf bpf: Add PROG_TAGS to required arrays in __bpf_event__print_bpf_prog_info()Arnaldo Carvalho de Melo
synthesize_bpf_prog_name() unconditionally dereferences prog_tags[sub_id] (line: u8 (*prog_tags)[BPF_TAG_SIZE] = (void *)(uintptr_t)(info->prog_tags)) but __bpf_event__print_bpf_prog_info() only requires JITED_KSYMS and JITED_FUNC_LENS in its required_arrays bitmask. If a crafted perf.data has the PROG_TAGS bit cleared (or the array was invalidated by bpil_offs_to_addr() bounds checking), info->prog_tags contains either zero or a raw file offset. Dereferencing it causes a NULL pointer dereference or an arbitrary memory read. Add PERF_BPIL_PROG_TAGS to required_arrays so the function returns early when prog_tags was not present or failed validation. Fixes: f8dfeae009effc0b ("perf bpf: Show more BPF program info in print_bpf_prog_info()") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Song Liu <songliubraving@fb.com> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-05perf header: Use write lock when translating BPF prog info pointersArnaldo Carvalho de Melo
write_bpf_prog_info() holds a read lock while temporarily mutating info_linear via bpil_addr_to_offs()/bpil_offs_to_addr(). Between these two calls, the pointers in info_linear contain file offsets instead of heap addresses. Concurrent readers holding the same read lock see the file offsets and dereference them as pointers. Use down_write()/up_write() instead of down_read()/up_read() to exclude concurrent readers during the addr-to-offset-to-addr translation window. Fixes: 63ac7968a1fb ("perf bpf: Save bpf_prog_info information as headers to perf.data") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Song Liu <songliubraving@fb.com> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-05perf libbfd: Validate BPF prog info arrays before pointer castArnaldo Carvalho de Melo
symbol__disassemble_bpf_libbfd() casts info_linear->info.jited_prog_insns and info_linear->info.jited_ksyms to pointers without checking whether bpil_offs_to_addr() actually converted the file offsets. A crafted perf.data with PERF_BPIL_* bits unset but non-zero counts causes raw file offsets to be dereferenced as pointers. Add bitmask checks for PERF_BPIL_JITED_INSNS and PERF_BPIL_JITED_KSYMS before the casts, matching the validation added to bpf-event.c call sites. Fixes: 6987561c9e86 ("perf annotate: Enable annotation of BPF programs") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Song Liu <songliubraving@fb.com> Reviewed-by: Ian Rogers <irogers@google.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-03perf arm-spe: Reject zero nr_cpu in metadata to prevent division by zeroArnaldo Carvalho de Melo
arm_spe__alloc_metadata() reads nr_cpu from the auxtrace_info priv array without validation. When a crafted perf.data provides nr_cpu=0, the per_cpu_sz calculation divides by zero: per_cpu_sz = (metadata_size - (hdr_sz * sizeof(u64))) / (*nr_cpu); Reject nr_cpu <= 0 early, before the division. The caller already treats NULL return with metadata_ver != 1 as a parse failure. Fixes: 7842a4b6ff698 ("perf arm-spe: Support metadata version 2") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: James Clark <james.clark@linaro.org> Reviewed-by: Adrian Hunter <adrian.hunter@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-03perf intel-bts: Fix off-by-one in auxtrace_info minimum size checkArnaldo Carvalho de Melo
Same pattern as the Intel PT fix: min_sz is set to sizeof(u64) * INTEL_BTS_SNAPSHOT_MODE, but the code accesses auxtrace_info->priv[INTEL_BTS_SNAPSHOT_MODE], which requires at least INTEL_BTS_SNAPSHOT_MODE + 1 elements. Use (INTEL_BTS_SNAPSHOT_MODE + 1) to ensure the highest accessed index is within bounds. Fixes: d0170af7004dce9c ("perf tools: Add Intel BTS support") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: James Clark <james.clark@linaro.org> Reviewed-by: Adrian Hunter <adrian.hunter@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-03perf intel-pt: Fix off-by-one in auxtrace_info minimum size checkArnaldo Carvalho de Melo
min_sz is set to sizeof(u64) * INTEL_PT_PER_CPU_MMAPS, but the code accesses auxtrace_info->priv[INTEL_PT_PER_CPU_MMAPS], which requires at least INTEL_PT_PER_CPU_MMAPS + 1 elements. A file with exactly min_sz bytes of priv data passes the size check but the access reads one u64 past the validated region. Use (INTEL_PT_PER_CPU_MMAPS + 1) to ensure the highest accessed index is within bounds. Fixes: 90e457f7be087005 ("perf tools: Add Intel PT support") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: James Clark <james.clark@linaro.org> Reviewed-by: Adrian Hunter <adrian.hunter@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-03perf auxtrace: Fix queue grow overflow and old array leakArnaldo Carvalho de Melo
auxtrace_queues__grow() has two bugs: 1. When idx is UINT_MAX, the caller passes new_nr_queues = idx + 1 = 0. The function skips growing (since any nr_queues >= 0), returns success, and the caller accesses queue_array[UINT_MAX] — an OOB heap write. Fix by rejecting new_nr_queues == 0 up front. 2. The function allocates a new queue_array via calloc and copies elements from the old array, but never frees the old array. Fix by saving the old pointer and freeing it after the copy. Fixes: e502789302a6ece9 ("perf auxtrace: Add helpers for queuing AUX area tracing data") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: James Clark <james.clark@linaro.org> Reviewed-by: Adrian Hunter <adrian.hunter@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-03perf thread-stack: Fix heap buffer overflow on branch stack wrap copyArnaldo Carvalho de Melo
thread_stack__br_sample() copies the wrap-around portion of the branch stack ring buffer with: nr = min(ts->br_stack_pos, sz); memcpy(be, &src->entries[0], bsz * ts->br_stack_pos); 'nr' is correctly bounded to min(br_stack_pos, sz) but the memcpy uses the unbounded ts->br_stack_pos directly. When br_stack_pos exceeds the remaining destination space 'sz', this writes past the destination buffer. Use 'nr' (the bounded value) in the memcpy size, matching the pattern of the first memcpy in the same function. Fixes: 86d67180b920 ("perf thread-stack: Add branch stack support") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Reviewed-by: James Clark <james.clark@linaro.org> Reviewed-by: Adrian Hunter <adrian.hunter@intel.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-02perf build: Fix a build error on 32-bit x86Namhyung Kim
The commit d7507a94a072 ("KVM: SVM: Treat exit_code as an unsigned 64-bit value through all of KVM") added "ull" suffix to SVM exit codes and it makes the 32-bit build fail like below. In file included from util/kvm-stat-arch/kvm-stat-x86.c:4: util/kvm-stat-arch/../../../arch/x86/include/uapi/asm/svm.h:137:32: error: conversion from 'long long unsigned int' to 'long unsigned int' changes value from '18446744073709551615' to '4294967295' [-Werror=overflow] 137 | #define SVM_EXIT_ERR -1ull | ^ util/kvm-stat-arch/../kvm-stat.h:131:17: note: in definition of macro 'define_exit_reasons_table' 131 | symbols, { -1, NULL } \ | ^~~~~~~ util/kvm-stat-arch/../../../arch/x86/include/uapi/asm/svm.h:249:11: note: in expansion of macro 'SVM_EXIT_ERR' 249 | { SVM_EXIT_ERR, "invalid_guest_state" } | ^~~~~~~~~~~~ util/kvm-stat-arch/kvm-stat-x86.c:12:45: note: in expansion of macro 'SVM_EXIT_REASONS' 12 | define_exit_reasons_table(svm_exit_reasons, SVM_EXIT_REASONS); | ^~~~~~~~~~~~~~~~ As the exit_code was unsigned long, the compiler complained about the truncation. Let's convert it to u64 to suppress the error. Fixes: fac520e43a60 ("tools headers: Sync KVM headers with the kernel sources") Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-08-02perf symbols: Skip dynamic symbols with invalid section indexesZhanpeng Zhang
RISC-V post-link processing can remove relocation sections from the final vmlinux while some .dynsym entries retain stale section indexes. perf aborts the whole ELF symbol load when elf_getscn() rejects one of them, discarding otherwise valid .symtab symbols. Skip only dynamic symbols whose normal section index is outside the final section table. Keep the existing error path for .symtab, reserved indexes, and other libelf failures. On an affected system, the vmlinux symtab matches kallsyms test changes from Skip to Ok. [unknown] rows in the same perf.data change from 41 to 0. Signed-off-by: Zhanpeng Zhang <zhangzhanpeng.jasper@bytedance.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-07-31perf machine: Check snprintf truncation for guest kallsyms pathArnaldo Carvalho de Melo
machines__create_guest_kernel_maps() builds the guest kallsyms path with snprintf() without checking the return value. A truncated path could pass the access() check if a prefix directory happens to contain a file named "kallsyms", leading to the wrong file being used for symbol resolution. Check for truncation and skip the directory. Fixes: a1645ce12adb ("perf: 'perf kvm' tool for monitoring guest performance from host") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Zhang, Yanmin <yanmin_zhang@linux.intel.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-07-31perf machine: Free scandir entries in guest kernel map creationArnaldo Carvalho de Melo
machines__create_guest_kernel_maps() calls scandir() which allocates both the namelist array and each individual dirent entry. The code frees the namelist array but not the individual entries, leaking memory proportional to the number of directories under guestmount. Free each namelist[i] after it is no longer needed. Fixes: a1645ce12adb ("perf: 'perf kvm' tool for monitoring guest performance from host") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Zhang, Yanmin <yanmin_zhang@linux.intel.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-07-31perf machine: Reset errno before strtol in guest kernel map creationArnaldo Carvalho de Melo
machines__create_guest_kernel_maps() checks errno == ERANGE after strtol() to detect overflow, but does not clear errno first. A stale ERANGE from an earlier library call (e.g. scandir internals) causes valid numeric directory names to be incorrectly skipped. Set errno = 0 before strtol() so only the current conversion can trigger the ERANGE check. Fixes: a1645ce12adb ("perf: 'perf kvm' tool for monitoring guest performance from host") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Zhang, Yanmin <yanmin_zhang@linux.intel.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>
2026-07-31perf machine: Don't abort guest map creation on first inaccessible dirArnaldo Carvalho de Melo
machines__create_guest_kernel_maps() jumps to the failure label when one guest directory's kallsyms file fails access(), skipping all remaining valid guest directories. An inaccessible directory is not fatal — other guests may still be reachable. Replace 'goto failure' with 'continue' so the loop processes all directories, and remove the now-unreferenced failure label. Fixes: a1645ce12adb ("perf: 'perf kvm' tool for monitoring guest performance from host") Reported-by: sashiko-bot <sashiko-bot@kernel.org> Cc: Zhang, Yanmin <yanmin_zhang@linux.intel.com> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Namhyung Kim <namhyung@kernel.org>