Skip to contentSkip to conversation

perf coverage: A harness for perf, and the fixes it found

PATCH New Arnaldo Carvalho de Melo 2 participants 27 messages Nov 18 perf events

lore
Share & tools
lore

Arnaldo Carvalho de Melo

author maintainer
#0 lore raw

v8 cover perf coverage: A harness for perf, and the fixes it found

From: Arnaldo Carvalho de Melo <[email protected]>

Hi,

Nothing measured how much of perf the test suite reaches. Patch 1 links the jvmti agent and the GTK UI with EXTRA_CFLAGS, without which the coverage build never saw the agent's counters; patch 2 adds tools/perf/scripts/coverage.sh: it builds perf with clang source based coverage, runs the complete perf test suite and reports line and function coverage, optionally against a baseline. Also as 'make -C tools/perf coverage', 'coverage-prep' and 'coverage-table'.

The useful output is the list of files with the most uncovered lines, computed over the whole tree and not only the files the tests already
touch: that is where new tests should try to get more coverage. Namhyung asked what the table is, so this is what coverage-table shows by default:

make -C tools/perf coverage-table
make: Entering directory '/home/acme/git/perf-tools-next/tools/perf' tools/perf (no tests/ or bench/), 100+ executable lines:
the 20 biggest uncovered gaps, start here when adding coverage tests. --all for every file: make -C tools/perf coverage-table COVERAGE_ARGS="--all"

┌──────────────────────────────────────────┬────────┬────────┬────────┬─────────────────────────────┬─────────────┬──────────┐
│ File                                     │  Lines │    Hit │   Miss │        Line Coverage        │       Funcs │  FuncCov │
├──────────────────────────────────────────┼────────┼────────┼────────┼─────────────────────────────┼─────────────┼──────────┤
│ ui/browsers/hists.c                      │   2730 │      0 │   2730 │ ░░░░░░░░░░░░░░░░░░░░   0.0% │     0/124   │    0.00% │
│ builtin-sched.c                          │   3737 │   1542 │   2195 │ ████████░░░░░░░░░░░░  41.3% │    62/141   │   43.97% │
│ builtin-script.c                         │   3212 │   1118 │   2094 │ ██████░░░░░░░░░░░░░░  34.8% │    51/124   │   41.13% │
│ util/intel-pt-decoder/intel-pt-decoder.c │   3208 │   1201 │   2007 │ ███████░░░░░░░░░░░░░  37.4% │    70/119   │   58.82% │
│ util/intel-pt.c                          │   3237 │   1426 │   1811 │ ████████░░░░░░░░░░░░  44.0% │    79/142   │   55.63% │
│ util/python.c                            │   2984 │   1301 │   1683 │ ████████░░░░░░░░░░░░  43.6% │   128/224   │   57.14% │
│ util/sort.c                              │   2421 │    861 │   1560 │ ███████░░░░░░░░░░░░░  35.6% │    83/246   │   33.74% │
│ util/session.c                           │   2686 │   1204 │   1482 │ ████████░░░░░░░░░░░░  44.8% │    65/125   │   52.00% │
│ util/annotate.c                          │   2245 │    866 │   1379 │ ███████░░░░░░░░░░░░░  38.6% │    60/118   │   50.85% │
│ builtin-kmem.c                           │   1337 │      0 │   1337 │ ░░░░░░░░░░░░░░░░░░░░   0.0% │     0/70    │    0.00% │
│ util/arm-spe.c                           │   1330 │      0 │   1330 │ ░░░░░░░░░░░░░░░░░░░░   0.0% │     0/50    │    0.00% │
│ builtin-kvm.c                            │   1316 │      0 │   1316 │ ░░░░░░░░░░░░░░░░░░░░   0.0% │     0/90    │    0.00% │
│ util/header.c                            │   3941 │   2662 │   1279 │ █████████████░░░░░░░  67.6% │   159/180   │   88.33% │
│ util/evsel.c                             │   3326 │   2067 │   1259 │ ████████████░░░░░░░░  62.2% │   128/155   │   82.58% │
│ builtin-record.c                         │   2737 │   1501 │   1236 │ ██████████░░░░░░░░░░  54.8% │    84/120   │   70.00% │
│ util/probe-event.c                       │   2765 │   1554 │   1211 │ ███████████░░░░░░░░░  56.2% │    81/103   │   78.64% │
│ builtin-trace.c                          │   3657 │   2451 │   1206 │ █████████████░░░░░░░  67.0% │   154/198   │   77.78% │
│ builtin-inject.c                         │   2023 │    890 │   1133 │ ████████░░░░░░░░░░░░  44.0% │    37/94    │   39.36% │
│ builtin-c2c.c                            │   2027 │   1018 │   1009 │ ██████████░░░░░░░░░░  50.2% │    58/156   │   37.18% │
│ util/auxtrace.c                          │   2013 │   1009 │   1004 │ ██████████░░░░░░░░░░  50.1% │    81/126   │   64.29% │
├──────────────────────────────────────────┼────────┼────────┼────────┼─────────────────────────────┼─────────────┼──────────┤
│ TOTAL (perf)                             │ 173244 │  91059 │  82185 │ ██████████░░░░░░░░░░  52.6% │  5868/9306  │   63.06% │
└──────────────────────────────────────────┴────────┴────────┴────────┴─────────────────────────────┴─────────────┴──────────┘

make: Leaving directory '/home/acme/git/perf-tools-next/tools/perf'

--all lists every tools/perf file, tests and benches included, most covered first. The table total is the tools/perf subtotal; the run summary has the whole report.

The rest is what the first runs found, in the code, the build and the tests:

- The data type resolver missed 32-bit absolute addressing (patch 3); the DW_OP_addrx globals it also missed are fixed upstream by c3991e42f58a3650, so patch 4 only adds the test. A struct pointer kept in a register at -O2 had no test (patch 7).
- The flexible array member had no test; one showed the struct row at

    0.00% while the member said 100.00% (patches 5-6).

- --insn-stat was printed before the loop that accounts the samples, so --code-with-type showed zeros (patch 8).
- The libbfd probe printed a missing bfd.h error five times per build-test run (patch 9).
- FEATURE-DUMP didn't record the features checked outside FEATURE_TESTS (llvm-perf, rust, jvmti), disabling them in the build-test builds (patch 10).
- The Intel PT virtual LBR check lost every aux sample with a single data page (patch 11).
- The dlfilter test kept samples whose IP the kernel now zeroes on a userspace-to-kernel skid (patch 12).
- The LBR inline unwinding check failed instead of reporting Skip when the AMD PMU rejects branch sampling (patch 13).

With coverage-prep by the developer (clang DWARF 5) and the full suite as root on this AMD host, 105,466 of 205,823 lines were covered (51.24%;
v5: 50.67% of 205,810), 86,344 of 173,257 in tools/perf/ (49.84%). 168 tests passed, 28 skipped and one failed (20.2, the POLL_HUP regression, outside this series). The global variable and instruction-stats tests passed; the Intel PT hardware tests skipped here, so patch 11's 64-page AUX buffer was only tested on the Intel host below.

The same tree as root on an Intel hybrid host (i7-14700K, Fedora 45) covered 110,258 of 205,830 lines (53.57%), 91,059 of 173,244 in tools/perf/ (52.56%). 166 tests passed, 27 skipped and three failed:
20.2, and 143 (branch stacks) and 212 (vfs_getname), which passed on rerun. The Intel PT tests ran and passed there, exercising patch 11's 64-page AUX buffer.

The AMD numbers are from the v6 set; v7 and v8 change the build, the tests' diagnostics and the harness, not the code the tests measure.

The harness and the tests were developed with an AI coding assistant (OpenCode), which drafted the script and the tests and helped debug the failures; an independent local model reviewed the script and I verified its findings before folding them in. I reviewed every change and reproduced each failure before fixing it.

What changed from v7:

- 2 rejects a build or cov directory reached through a link owned by another user, runs the ownership checks for non-root runs too, and stops exempting a sticky target directory itself (sashiko-bot).
- 2 checks cov/ before reading its state file and no longer chowns the build directory itself when giving root's files back (sashiko-bot).

Best regards,

- Arnaldo

Arnaldo Carvalho de Melo (13):
perf build: Link the jvmti agent and the GTK UI with EXTRA_CFLAGS perf scripts: Add a coverage harness for perf
perf annotate: Handle absolute addressing in data type profiling perf tests: Exercise DW_OP_addrx global variables
perf tests: Exercise the flexible array member path
perf annotate-data: Count flexible array accesses for the whole struct perf tests: Exercise data type resolution from a register perf annotate: Print the stats after the annotations
perf tests: Silence the libbfd probe in build-test
perf build: Record the features checked outside FEATURE_TESTS perf tests: Fix the Intel PT virtual LBR check
perf test: Drop samples without an IP in the dlfilter test perf test: Skip the LBR inline unwinding check when unsupported

 tools/perf/.gitignore                         |    1 +
 tools/perf/Documentation/perf-annotate.txt    |    2 +-
 tools/perf/Makefile                           |   11 +-
 tools/perf/Makefile.config                    |    7 +
 tools/perf/Makefile.perf                      |    8 +-
 tools/perf/builtin-annotate.c                 |   19 +-
 tools/perf/scripts/coverage.sh                | 1142 +++++++++++++++++
 tools/perf/tests/builtin-test.c               |    3 +
 tools/perf/tests/make                         |    2 +-
 tools/perf/tests/shell/addr2line_inlines.sh   |   20 +-
 tools/perf/tests/shell/annotate_stats.sh      |   69 +
 .../perf/tests/shell/data_type_flex_array.sh  |  111 ++
 tools/perf/tests/shell/data_type_global.sh    |   73 ++
 tools/perf/tests/shell/data_type_register.sh  |   63 +
 tools/perf/tests/shell/script_dlfilter.sh     |    2 +-
 tools/perf/tests/shell/test_intel_pt.sh       |   10 +-
 tools/perf/tests/tests.h                      |    3 +
 tools/perf/tests/workloads/Build              |    6 +
 tools/perf/tests/workloads/flex_array.c       |   55 +
 tools/perf/tests/workloads/global_data.c      |   57 +
 tools/perf/tests/workloads/regptr.c           |   60 +
 tools/perf/ui/browsers/annotate-data.c        |    7 +-
 tools/perf/util/annotate-arch/annotate-x86.c  |   43 +-
 tools/perf/util/annotate-data.c               |   25 +-
 tools/perf/util/annotate-data.h               |    8 +
 tools/perf/util/annotate.c                    |   27 +-
 tools/perf/util/annotate.h                    |    7 +
 27 files changed, 1811 insertions(+), 30 deletions(-)
 create mode 100755 tools/perf/scripts/coverage.sh
 create mode 100755 tools/perf/tests/shell/annotate_stats.sh
 create mode 100755 tools/perf/tests/shell/data_type_flex_array.sh
 create mode 100755 tools/perf/tests/shell/data_type_global.sh
 create mode 100755 tools/perf/tests/shell/data_type_register.sh
 create mode 100644 tools/perf/tests/workloads/flex_array.c
 create mode 100644 tools/perf/tests/workloads/global_data.c
 create mode 100644 tools/perf/tests/workloads/regptr.c

base-commit: b7ff10b9ddec8da75304c40fe4abf1ee4f9f0a43
v1-head: 3f5465bea8f5a97a
v2-head: 9706c488afffeb6d
v3-head: f2daf1586528671a
v4-head: b9e240a1b80ecd2a
v5-head: a21454e3d055c93b
v6-head: e1315408a335617d
v7-head: 7f8dc594d77ed495
v8-head: 67fde34aeab98a91

Signature · 1 line
2.56.1
author maintainer
#1 lore raw

PATCH v8 1/13 perf build: Link the jvmti agent and the GTK UI with EXTRA_CFLAGS

From: Arnaldo Carvalho de Melo <[email protected]>

The jvmti and GTK objects are compiled with EXTRA_CFLAGS but their shared objects are linked with LDFLAGS only, so flags with link-time parts never reach them. With -fprofile-instr-generate the jvmti agent's __profc counters had no __llvm_profile runtime to write them, and its files showed 0.00% in the coverage report.

Pass EXTRA_CFLAGS at link time, as the dlfilter rule already does.

---
 tools/perf/Makefile.perf | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/perf/Makefile.perf +2 -2
index b74b534e1153ffcb..e730f1a209cb44a4 100644
@@ -640,7 +640,7 @@ $(GTK_IN): FORCE prepare
 	$(Q)$(MAKE) $(build)=gtk
 
 $(OUTPUT)libperf-gtk.so: $(GTK_IN) $(PERFLIBS)
-	$(QUIET_LINK)$(CC) -o $@ -shared $(LDFLAGS) $(filter %.o,$^) $(GTK_LIBS)
+	$(QUIET_LINK)$(CC) -o $@ -shared $(LDFLAGS) $(EXTRA_CFLAGS) $(filter %.o,$^) $(GTK_LIBS)
 
 $(SCRIPTS) : $(OUTPUT)% : %.sh
 	$(QUIET_GEN)$(INSTALL) '$<' '$@'
@@ -791,7 +791,7 @@ $(LIBJVMTI_IN): prepare FORCE
 	$(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=jvmti obj=jvmti
 
 $(OUTPUT)$(LIBJVMTI): $(LIBJVMTI_IN)
-	$(QUIET_LINK)$(CC) $(LDFLAGS) -shared -Wl,-soname -Wl,$(LIBJVMTI) -o $@ $<
+	$(QUIET_LINK)$(CC) $(LDFLAGS) $(EXTRA_CFLAGS) -shared -Wl,-soname -Wl,$(LIBJVMTI) -o $@ $<
 endif
 
 $(patsubst perf-%,%.o,$(PROGRAMS)): $(wildcard */*.h)
Signature · 1 line
2.56.1
#2 lore raw

Re: [PATCH v8 01/13] perf build: Link the jvmti agent and the GTK UI with EXTRA_CFLAGS

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

From: Arnaldo Carvalho de Melo <[email protected]>

The jvmti and GTK objects are compiled with EXTRA_CFLAGS but their shared objects are linked with LDFLAGS only, so flags with link-time parts never reach them. With -fprofile-instr-generate the jvmti agent's __profc counters had no __llvm_profile runtime to write them, and its files showed 0.00% in the coverage report.

Pass EXTRA_CFLAGS at link time, as the dlfilter rule already does.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

PATCH v8 2/13 perf scripts: Add a coverage harness for perf

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

Build perf with clang source based coverage, run the complete perf test suite, merge the raw profiles and report line and function coverage, optionally against a baseline. This is pahole's coverage/coverage.sh + coverage-diff.sh merged into one script, wired as
'make -C tools/perf coverage' and listed in 'make help'.

Without -f the report lists the tool's files with the most uncovered lines, tests and benches left out, which is where new tests should try to get more coverage; -t narrows the tests, -f focuses on specific files, --html writes a browsable report and --table/-T, also available as 'make -C tools/perf coverage-table', prints the last run as a text table with the per-file line and function coverage, like pahole's coverage_table.py.

The table defaults to the same view, biggest gap first: covering everything is not the goal, this is the list to work from. --all lists every tools/perf file, most covered first, and the table total is the tools/perf subtotal, matching the rows; the whole-report total, generated files included, stays in the run summary.

The build can be split from the test run: 'make -C tools/perf coverage-prep' builds the instrumented perf and records the build directory, and a later run as root, which needs no make, checks that build, runs the tests and renders the report, or prints the table with --table. This is for running the tests that need root on the bare metal host while the instrumented perf is built in the development container.

The report covers the whole tree, not only the paths the tests walk, so the per-file table is a map of what the suite does not reach in a given run. The uncovered line list and the failures the runs exposed are what drove the rest of this series.

  $ sudo scripts/coverage.sh
  ...
  Total: 105466 of 205823 lines covered (51.24%)
    perf: 86344 of 173257 lines covered (49.84%)

The total also counts the tools/ libraries and headers linked into perf, the perf line is the tools/perf/ files alone. The numbers above are from the split run: coverage-prep built the instrumented perf as the developer, the tests and the report ran as root. This machine has no Intel PT, so the PT tests skip and leave intel-pt.c and intel-pt-decoder.c at 0.00%; the TUI browser is in the uncovered list because the suite does not drive it.

'perf test' exits 0 even when tests fail or time out, so the script takes its status from the "Failed tests :" line that perf test prints since commit 33f20342ba525ef7 ("perf test: Add summary reporting") and the "Timed out tests :" one from commit bcb9de7e1d9bd5f8 ("perf test:
Add per-test timeout support").

168 tests passed, 28 skipped and one failed (20.2, the known POLL_HUP regression), in code this series does not change.

---
 tools/perf/.gitignore          |    1 +
 tools/perf/Makefile            |   11 +-
 tools/perf/Makefile.perf       |    4 +
 tools/perf/scripts/coverage.sh | 1142 ++++++++++++++++++++++++++++++++
 4 files changed, 1157 insertions(+), 1 deletion(-)
 create mode 100755 tools/perf/scripts/coverage.sh
tools/perf/.gitignore +1 -0
index 3b968c5158b822ce..9052f25597ac9489 100644
@@ -27,6 +27,7 @@ stats-*.csv
 cscope*
 config.mak
 config.mak.autogen
+.coverage-build-dir
 *-bison.*
 *-flex.*
 *.pyc
tools/perf/Makefile +10 -1
index 00baf90e5bda7123..8df8e9ed37f0a8f5 100644
@@ -140,6 +140,15 @@ check-headers:
 sync-headers:
 	@./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS)
 
+coverage-prep:
+	@./scripts/coverage.sh --prep $(if $(FULL_O),--build-dir=$(FULL_O)) $(COVERAGE_ARGS)
+
+coverage:
+	@./scripts/coverage.sh $(if $(FULL_O),--build-dir=$(FULL_O)) $(COVERAGE_ARGS)
+
+coverage-table:
+	@./scripts/coverage.sh --table $(if $(FULL_O),--build-dir=$(FULL_O)) $(COVERAGE_ARGS)
+
 #
 # All other targets get passed through:
 #
@@ -147,4 +156,4 @@ sync-headers:
 	$(print_msg)
 	$(make)
 
-.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers
+.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers coverage coverage-prep coverage-table
tools/perf/Makefile.perf +4 -0
index e730f1a209cb44a4..d33fe8b160ededdd 100644
@@ -873,6 +873,10 @@ help:
 	@echo '  check-headers		- check which header copies are out of sync with the kernel'
 	@echo '  sync-headers		- sync those header copies with the kernel, creating commits'
 	@echo '			  (SYNC_HEADERS_ARGS="..." passes options to the script)'
+	@echo '  coverage-prep		- build perf with clang coverage, ready for a root test run'
+	@echo '  coverage		- build perf with clang coverage, run the tests and report'
+	@echo '  coverage-table	- print a text table of the last coverage run'
+	@echo '			  (COVERAGE_ARGS="..." passes options to the script)'
 
 
 DOC_TARGETS := doc man html info pdf
tools/perf/scripts/coverage.sh new file +1142 -0

1,142 lines not on this page · raw message

Signature · 1 line
2.56.1
#4 lore raw

Re: [PATCH v8 02/13] perf scripts: Add a coverage harness for perf

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf scripts: TOCTOU race and chown on untrusted dir in mkdir_checked() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf scripts: TOCTOU race and chown on untrusted dir in mkdir_checked()
--

commit 7ab6984627c594b546b3004b18a620f69c6a9e8e
Author: Arnaldo Carvalho de Melo <[email protected]>

perf scripts: Add a coverage harness for perf

This commit adds a clang source-based coverage script for perf along with make targets to build, run tests, and report line and function coverage.

Quoted 5 lines
tools/perf/scripts/coverage.sh new file +0 -0
new file mode 100755
index 0000000000000..4176cdae79e25

[ ... ]

Quoted 24 lines
tools/perf/scripts/coverage.sh new file +24 -0
+check_trusted_path()
+{
+	local path=$1 raw=${2:-$1} leaf=$1 uid gid mode owners=root
+
+	[ "$TRUST_UID" = 0 ] || owners="root or uid $TRUST_UID"
+	# abspath() resolves links such as /home -> /var/home on Silverblue
+	# and CoreOS, so a link is gone from the resolved path by the time
+	# the walk below sees it; reject one the path as given traversed
+	# that is not root's, since anybody who can write its directory can
+	# retarget the run.
+	while :; do
+		if [ -L "$raw" ]; then
+			if ! read -r uid gid mode < \
+				<(stat -c '%u %g %a' "$raw" 2>/dev/null); then
+				die "could not stat $raw"
+			fi
+			# The mode of a link means nothing, its owner does:
+			# only whoever can write the directory can replace it.
+			[ "$uid" = 0 ] || [ "$uid" = "$TRUST_UID" ] ||
+				die "$raw is a symbolic link owned by uid $uid, not by $owners"
+		fi
+		[ "$raw" = / ] && break
+		raw=$(dirname "$raw")
+	done

[ ... ]

Quoted 18 lines
tools/perf/scripts/coverage.sh new file +18 -0
+mkdir_checked()
+{
+	local path=$1 parent missing=()
+	while [ ! -d "$path" ]; do
+		missing=("$path" "${missing[@]}")
+		parent=$(dirname "$path")
+		[ "$parent" = "$path" ] && break
+		path=$parent
+	done
+	for path in "${missing[@]+"${missing[@]}"}"; do
+		if mkdir "$path" 2>/dev/null; then
+			MKDIR_CREATED+=("$path")
+		elif [ ! -d "$path" ]; then
+			die "could not create $path"
+		fi
+	done
+	check_trusted_path "$1"
+}

[ ... ]

Quoted 11 lines
tools/perf/scripts/coverage.sh new file +11 -0
+fix_ownership()
+{
+	local uid=$TRUST_UID gid=$TRUST_GID path top=
+
+	[ "$ROOT" = 1 ] && [ "$uid" != 0 ] || return 0
+
+	for path in "${COV_WRITES[@]}"; do
+		[ -e "$COV_DIR/$path" ] || continue
+		chown -Rh "$uid:$gid" "$COV_DIR/$path" ||
+			warn "could not give $COV_DIR/$path back to uid $uid"
+	done

tools/perf/scripts/coverage.sh line 392

Quoted 10 lines
tools/perf/scripts/coverage.sh new file +10 -0
+	# The directories this run created, in creation order: chowning one
+	# covers everything below it, so skip those.
+	for path in "${MKDIR_CREATED[@]+"${MKDIR_CREATED[@]}"}"; do
+		if [ -n "$top" ]; then
+			case "$path" in "$top"/*) continue ;; esac
+		fi
+		chown -Rh "$uid:$gid" "$path" ||
+			warn "could not give $path back to uid $uid"
+		top=$path
+	done

[Severity: Low]
Can an unprivileged local user race with mkdir_checked() when /tmp/build does not exist yet and cause fix_ownership() to run chown -Rh on an untrusted path?

When /tmp/build is absent during the initial check_trusted_path() checks, only /tmp exists and passes as a root-owned sticky directory. If another local user creates /tmp/build before mkdir_checked() runs, the creation loop accepts the existing /tmp/build without checking its owner or whether it is a symlink, creates child directories such as /tmp/build/perf-coverage inside it, and appends them to MKDIR_CREATED before calling check_trusted_path().

When check_trusted_path() then calls die while the EXIT trap is installed (for example during build_perf() or write_state()), fix_ownership() runs chown -Rh on the child paths recorded in MKDIR_CREATED inside the untrusted /tmp/build directory, allowing the owner of /tmp/build to swap the child directory before chown -Rh runs.

In addition, the raw path walk in check_trusted_path() checks symlink ownership with [ -L "$raw" ] but does not verify the ownership and write permissions of the parent directory holding the symlink before abspath() resolves that parent away.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#5 lore raw

PATCH v8 3/13 perf annotate: Handle absolute addressing in data type profiling

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

32-bit x86 accesses globals with absolute addresses, like "movl %eax,0x8c73448", but the operand parser only recognized the offset(reg) forms, so the operand had no memory reference and the resolver skipped it as not a memory access.

Parse a bare hex number as an absolute memory operand, including the negative disp32 the LLVM disassembler prints for values that do not fit an int, and use the address in the resolver; calls, whose operand is a branch target, are left out. Let the instruction tracking record the type of an absolute global load in the destination register. The displacement is sign extended for 64-bit objects, as the CPU does, and zero extended for 32-bit ones. Values that do not fit the int offset, zero and the operands of relocatable objects, which are unrelocated addends, are skipped.

With bare numbers being memory operands, a frame base register of -1, "none", would also compare equal to the -1 "no register" of an absolute operand and take it for a stack access, so guard those comparisons. Operands left with no register, like a user space "%gs:imm", are no longer looked up as variables, which can change the data type stats of those samples.

---
 tools/perf/util/annotate-arch/annotate-x86.c | 43 ++++++++++++++++----
 tools/perf/util/annotate.c                   | 27 +++++++++++-
 tools/perf/util/annotate.h                   |  7 ++++
 3 files changed, 69 insertions(+), 8 deletions(-)
tools/perf/util/annotate-arch/annotate-x86.c +36 -7
index e38a4e7a54d5585c..7bcc93405b907628 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <string.h>
 #include <stdlib.h>
+#include <limits.h>
 #include <linux/compiler.h>
 #include <linux/ctype.h>
 #include <linux/zalloc.h>
@@ -230,6 +231,11 @@ static bool vtable_get_rettype(Dwarf_Die *class_die, int offset,
 	return die_get_real_type(&func_die, type_die) != NULL;
 }
 
+static bool is_stack_or_fb_reg(struct type_state *state, int fbreg, int reg)
+{
+	return (fbreg != -1 && reg == fbreg) || reg == state->stack_reg;
+}
+
 static void update_insn_state_x86(struct type_state *state,
 				  struct data_loc_info *dloc, Dwarf_Die *cu_die,
 				  struct disasm_line *dl)
@@ -437,7 +443,7 @@ static void update_insn_state_x86(struct type_state *state,
 		invalidate_reg_state(tsr);
 
 		/* Case 1: Based on stack pointer or frame pointer */
-		if (sreg == fbreg || sreg == state->stack_reg) {
+		if (is_stack_or_fb_reg(state, fbreg, sreg)) {
 			struct type_state_stack *stack;
 			int offset = src->offset - fboff;
 
@@ -626,7 +632,7 @@ static void update_insn_state_x86(struct type_state *state,
 
 retry:
 		/* Check stack variables with offset */
-		if (sreg == fbreg || sreg == state->stack_reg) {
+		if (is_stack_or_fb_reg(state, fbreg, sreg)) {
 			struct type_state_stack *stack;
 			int offset = src->offset - fboff;
 
@@ -717,13 +723,17 @@ static void update_insn_state_x86(struct type_state *state,
 			pr_debug_type_name(&tsr->type, tsr->kind);
 		}
 		/* Or check if it's a global variable */
-		else if (sreg == DWARF_REG_PC) {
+		else if (sreg == DWARF_REG_PC ||
+			 annotated_op_loc__is_abs(src, map__dso(dloc->ms->map))) {
 			struct map_symbol *ms = dloc->ms;
 			u64 ip = ms->sym->start + dl->al.offset;
 			u64 addr;
 			int offset;
 
-			addr = annotate_calc_pcrel(ms, ip, src->offset, dl);
+			if (sreg == DWARF_REG_PC)
+				addr = annotate_calc_pcrel(ms, ip, src->offset, dl);
+			else
+				addr = annotated_op_loc__abs_addr(src, map__dso(ms->map));
 
 			if (!get_global_var_type(cu_die, dloc, ip, addr, &offset,
 						 &type_die) ||
@@ -737,7 +747,7 @@ static void update_insn_state_x86(struct type_state *state,
 			tsr->offset = 0;
 			tsr->ok = true;
 
-			pr_debug_dtp("mov [%x] global addr=%"PRIx64" -> reg%d",
+			pr_debug_dtp("mov [%x] global addr=%#"PRIx64" -> reg%d",
 				     insn_offset, addr, dst->reg1);
 			pr_debug_type_name(&type_die, tsr->kind);
 		}
@@ -827,7 +837,7 @@ static void update_insn_state_x86(struct type_state *state,
 	/* Case 3. register to memory transfers */
 	if (!src->mem_ref && dst->mem_ref) {
 		/* Check stack variables with offset */
-		if (dst->reg1 == fbreg || dst->reg1 == state->stack_reg) {
+		if (is_stack_or_fb_reg(state, fbreg, dst->reg1)) {
 			struct type_state_stack *stack;
 			int offset = dst->offset - fboff;
 
@@ -931,7 +941,7 @@ static int extract_reg_offset(const struct arch *arch, const char *str,
 }
 
 static void extract_op_location_x86(const struct arch *arch,
-				    struct disasm_line *dl __maybe_unused,
+				    struct disasm_line *dl,
 				    const char *op_str, int op_idx __maybe_unused,
 				    struct annotated_op_loc *op_loc)
 {
@@ -960,6 +970,25 @@ static void extract_op_location_x86(const struct arch *arch,
 			op_loc->offset = strtol(s + 1, &p, 0);
 			if (p && p != s + 1)
 				op_loc->imm = true;
+		} else if ((*s == '-' || strstarts(s, "0x")) &&
+			   !ins__is_call(&dl->ins)) {
+			bool neg = *s == '-';
+			u64 offset = strtoull(s + neg, NULL, 0);
+
+			if (neg)
+				offset = -offset;
+			/*
+			 * Keep only what fits the int, as disp32 or as a u32;
+			 * a 64-bit absolute value is left out.  The LLVM
+			 * disassembler prints a disp32 that does not fit an
+			 * int as a negative number.
+			 */
+			if (offset != 0 && (offset <= UINT_MAX ||
+					    (s64)(int)offset == (s64)offset)) {
+				/* An absolute address: 32-bit code, or a 64-bit disp32 */
+				op_loc->mem_ref = true;
+				op_loc->offset = offset;
+			}
 		}
 	}
 }
tools/perf/util/annotate.c +26 -1
index 86a4beec6528e9bd..74e3d8e6436cad3c 100644
@@ -2605,6 +2605,21 @@ int arch__dwarf_regnum(const struct arch *arch, const char *str)
 	return reg < 0 ? -1 : reg;
 }
 
+/* A relocatable object's operand is an unrelocated addend, not an address */
+bool annotated_op_loc__is_abs(const struct annotated_op_loc *op_loc,
+			      const struct dso *dso)
+{
+	return !dso__rel(dso) && op_loc->mem_ref && op_loc->reg1 == -1 && op_loc->reg2 == -1 &&
+	       op_loc->segment == INSN_SEG_NONE && op_loc->offset != 0;
+}
+
+/* The disp32 of a 64-bit object is sign extended, a 32-bit one is not */
+u64 annotated_op_loc__abs_addr(const struct annotated_op_loc *op_loc,
+			       const struct dso *dso)
+{
+	return dso__is_64_bit(dso) ? (u64)(s64)op_loc->offset : (u32)op_loc->offset;
+}
+
 /**
  * annotate_get_insn_location - Get location of instruction
  * @arch: the architecture info
@@ -2622,7 +2637,7 @@ int arch__dwarf_regnum(const struct arch *arch, const char *str)
  *   mov  (%rax), %rcx   # src_reg1 = rax, src_mem = 1, src_offset = 0
  *                       # dst_reg1 = rcx, dst_mem = 0
  *
- *   mov  0x18, %r8      # src_reg1 = -1, src_mem = 0
+ *   mov  0x18, %r8      # src_reg1 = -1, src_mem = 1, src_offset = 0x18
  *                       # dst_reg1 = r8, dst_mem = 0
  *
  *   mov  %rsi, 8(%rbx,%rcx,4)  # src_reg1 = rsi, src_mem = 0, src_multi_regs = 0
@@ -2894,6 +2909,13 @@ __hist_entry__get_data_type(struct hist_entry *he, const struct arch *arch,
 			dloc.var_addr = annotate_calc_pcrel(ms, dloc.ip,
 							    op_loc->offset, dl);
 		}
+		/* An absolute address: 32-bit code, or a 64-bit disp32 */
+		else if (annotated_op_loc__is_abs(op_loc, map__dso(ms->map))) {
+			struct dso *dso = map__dso(ms->map);
+
+			dloc.var_addr = annotated_op_loc__abs_addr(op_loc, dso);
+			op_loc->reg1 = DWARF_REG_PC;
+		}
 
 		/* This CPU access in kernel - pretend PC-relative addressing */
 		if (dso__kernel(map__dso(ms->map)) && arch__is_x86(arch) &&
@@ -2902,6 +2924,9 @@ __hist_entry__get_data_type(struct hist_entry *he, const struct arch *arch,
 			op_loc->reg1 = DWARF_REG_PC;
 		}
 
+		if (op_loc->reg1 == -1)
+			continue;
+
 		mem_type = find_data_type(&dloc);
 
 		if (mem_type == NULL && is_stack_canary(arch, op_loc)) {
tools/perf/util/annotate.h +7 -0
index 1b47c1156b9a72e1..1b0991d4e98c911e 100644
@@ -18,6 +18,7 @@
 #include "branch.h"
 #include "evsel.h"
 
+struct dso;
 struct hist_browser_timer;
 struct hist_entry;
 struct map;
@@ -638,6 +639,12 @@ struct annotated_insn_loc {
 	     i < INSN_OP_MAX;						\
 	     i++, op_loc++)
 
+/* Bare number operand, as used by 32-bit code to access globals */
+bool annotated_op_loc__is_abs(const struct annotated_op_loc *op_loc,
+			      const struct dso *dso);
+u64 annotated_op_loc__abs_addr(const struct annotated_op_loc *op_loc,
+			       const struct dso *dso);
+
 /* Get detailed location info in the instruction */
 int annotate_get_insn_location(const struct arch *arch, struct disasm_line *dl,
 			       struct annotated_insn_loc *loc);
Signature · 1 line
2.56.1
#6 lore raw

Re: [PATCH v8 03/13] perf annotate: Handle absolute addressing in data type profiling

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

From: Arnaldo Carvalho de Melo <[email protected]>

32-bit x86 accesses globals with absolute addresses, like "movl %eax,0x8c73448", but the operand parser only recognized the offset(reg) forms, so the operand had no memory reference and the resolver skipped it as not a memory access.

Parse a bare hex number as an absolute memory operand, including the negative disp32 the LLVM disassembler prints for values that do not fit an int, and use the address in the resolver; calls, whose operand is a branch target, are left out. Let the instruction tracking record the type of an absolute global load in the destination register. The displacement is sign extended for 64-bit objects, as the CPU does, and zero extended for 32-bit ones. Values that do not fit the int offset, zero and the operands of relocatable objects, which are unrelocated addends, are skipped.

Quoted 8 lines

With bare numbers being memory operands, a frame base register of -1, "none", would also compare equal to the -1 "no register" of an absolute operand and take it for a stack access, so guard those comparisons. Operands left with no register, like a user space "%gs:imm", are no longer looked up as variables, which can change the data type stats of those samples.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#7 lore raw

PATCH v8 4/13 perf tests: Exercise DW_OP_addrx global variables

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

clang emits DW_AT_location with DW_OP_addrx for globals in DWARF 5, gcc emits DW_OP_addr. The global_data workload keeps a zero initialized struct in .bss: at run time it sits past the file backed mapping, where the by-name fallback through the thread maps cannot find it, so only the DWARF address lookup resolves it. The test checks that its three member accesses are annotated, so the DW_OP_addrx path is exercised when perf is built with clang and DWARF 5 (e.g. coverage.sh --dwarf-version 5), and the DW_OP_addr one with gcc.

It skips on 32-bit PIE builds, which reach static globals relative to the GOT base register, and the resolver does not track that.

---
 tools/perf/tests/builtin-test.c            |  1 +
 tools/perf/tests/shell/data_type_global.sh | 73 ++++++++++++++++++++++
 tools/perf/tests/tests.h                   |  1 +
 tools/perf/tests/workloads/Build           |  2 +
 tools/perf/tests/workloads/global_data.c   | 57 +++++++++++++++++
 5 files changed, 134 insertions(+)
 create mode 100755 tools/perf/tests/shell/data_type_global.sh
 create mode 100644 tools/perf/tests/workloads/global_data.c
tools/perf/tests/builtin-test.c +1 -0
index 327483f96401b580..e056a3d3594ff8a2 100644
@@ -213,6 +213,7 @@ static struct test_workload *workloads[] = {
 	&workload__deterministic,
 	&workload__callchain,
 	&workload__false_sharing,
+	&workload__global_data,
 
 #ifdef HAVE_RUST_SUPPORT
 	&workload__code_with_type,
tools/perf/tests/shell/data_type_global.sh new file +73 -0

73 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index af822885890dda73..049a164503166529 100644
@@ -273,6 +273,7 @@ DECLARE_WORKLOAD(context_switch_loop);
 DECLARE_WORKLOAD(deterministic);
 DECLARE_WORKLOAD(callchain);
 DECLARE_WORKLOAD(false_sharing);
+DECLARE_WORKLOAD(global_data);
 
 #ifdef HAVE_RUST_SUPPORT
 DECLARE_WORKLOAD(code_with_type);
tools/perf/tests/workloads/Build +2 -0
index 43cc4da6fb0786de..03017aaaaa0bec32 100644
@@ -17,6 +17,7 @@ perf-test-y += context_switch_loop.o
 perf-test-y += deterministic.o
 perf-test-y += callchain.o
 perf-test-y += false_sharing.o
+perf-test-y += global_data.o
 
 ifeq ($(CONFIG_RUST_SUPPORT),y)
     perf-test-y += code_with_type.o
@@ -35,3 +36,4 @@ CFLAGS_deterministic.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_named_threads.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_callchain.o        = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_false_sharing.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
+CFLAGS_global_data.o      = -g -O0 -fno-inline -U_FORTIFY_SOURCE
tools/perf/tests/workloads/global_data.c new file +57 -0

57 lines not on this page · raw message

Signature · 1 line
2.56.1
#8 lore raw

Re: [PATCH v8 04/13] perf tests: Exercise DW_OP_addrx global variables

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

From: Arnaldo Carvalho de Melo <[email protected]>

clang emits DW_AT_location with DW_OP_addrx for globals in DWARF 5, gcc emits DW_OP_addr. The global_data workload keeps a zero initialized struct in .bss: at run time it sits past the file backed mapping, where the by-name fallback through the thread maps cannot find it, so only the DWARF address lookup resolves it. The test checks that its three member accesses are annotated, so the DW_OP_addrx path is exercised when perf is built with clang and DWARF 5 (e.g. coverage.sh --dwarf-version 5), and the DW_OP_addr one with gcc.

Quoted 4 lines

It skips on 32-bit PIE builds, which reach static globals relative to the GOT base register, and the resolver does not track that.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#9 lore raw

PATCH v8 5/13 perf tests: Exercise the flexible array member path

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

No test covered find_flex_array() and get_flex_array_member(). Add a flex_array workload that keeps a struct with a trailing data[] behind a global pointer, and a test that checks the accesses past the struct size are resolved and named after the flexible array member; find_data_type() folds offsets past the struct modulo the element size back to the member's offset (+0x4 for char data[]). The test skips on 32-bit PIE builds, which reach static globals relative to the GOT base register.

---
 tools/perf/tests/builtin-test.c               |  1 +
 .../perf/tests/shell/data_type_flex_array.sh  | 71 +++++++++++++++++++
 tools/perf/tests/tests.h                      |  1 +
 tools/perf/tests/workloads/Build              |  2 +
 tools/perf/tests/workloads/flex_array.c       | 55 ++++++++++++++
 5 files changed, 130 insertions(+)
 create mode 100755 tools/perf/tests/shell/data_type_flex_array.sh
 create mode 100644 tools/perf/tests/workloads/flex_array.c
tools/perf/tests/builtin-test.c +1 -0
index e056a3d3594ff8a2..8fc425d470c17dbf 100644
@@ -214,6 +214,7 @@ static struct test_workload *workloads[] = {
 	&workload__callchain,
 	&workload__false_sharing,
 	&workload__global_data,
+	&workload__flex_array,
 
 #ifdef HAVE_RUST_SUPPORT
 	&workload__code_with_type,
tools/perf/tests/shell/data_type_flex_array.sh new file +71 -0

71 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index 049a164503166529..0cf33d91804f19c4 100644
@@ -274,6 +274,7 @@ DECLARE_WORKLOAD(deterministic);
 DECLARE_WORKLOAD(callchain);
 DECLARE_WORKLOAD(false_sharing);
 DECLARE_WORKLOAD(global_data);
+DECLARE_WORKLOAD(flex_array);
 
 #ifdef HAVE_RUST_SUPPORT
 DECLARE_WORKLOAD(code_with_type);
tools/perf/tests/workloads/Build +2 -0
index 03017aaaaa0bec32..74a0cbe49dc93533 100644
@@ -18,6 +18,7 @@ perf-test-y += deterministic.o
 perf-test-y += callchain.o
 perf-test-y += false_sharing.o
 perf-test-y += global_data.o
+perf-test-y += flex_array.o
 
 ifeq ($(CONFIG_RUST_SUPPORT),y)
     perf-test-y += code_with_type.o
@@ -37,3 +38,4 @@ CFLAGS_named_threads.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_callchain.o        = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_false_sharing.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_global_data.o      = -g -O0 -fno-inline -U_FORTIFY_SOURCE
+CFLAGS_flex_array.o       = -g -O0 -fno-inline -U_FORTIFY_SOURCE
tools/perf/tests/workloads/flex_array.c new file +55 -0

55 lines not on this page · raw message

Signature · 1 line
2.56.1
#10 lore raw

Re: [PATCH v8 05/13] perf tests: Exercise the flexible array member path

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

From: Arnaldo Carvalho de Melo <[email protected]>

No test covered find_flex_array() and get_flex_array_member(). Add a flex_array workload that keeps a struct with a trailing data[] behind a global pointer, and a test that checks the accesses past the struct size are resolved and named after the flexible array member; find_data_type() folds offsets past the struct modulo the element size back to the member's offset (+0x4 for char data[]). The test skips on 32-bit PIE builds, which reach static globals relative to the GOT base register.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#11 lore raw

PATCH v8 6/13 perf annotate-data: Count flexible array accesses for the whole struct

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

The per-member percentage sums the histogram entries in the member's own [offset, offset + size) range. A flexible array member is resolved past the end of its struct, so the struct row only covered its declared size and showed 0.00% while the member row showed 100.00% and the header said N samples.

Take a member's extent as the end of its furthest child as well, so the struct counts what was resolved past it. Union members all start at offset 0, so a plain union keeps its size; a member that is itself a struct with a flexible array extends the union too. The TUI browser accounts the members the same way, use the extent there as well.

Extend tests/shell/data_type_flex_array.sh to check that the accesses count for the struct in the percent, samples and period columns.

Fixes aaca646915a1bb53 ("perf annotate-data: Adjust type offset for flex-array")
Cc Namhyung Kim <[email protected]>
---
 .../perf/tests/shell/data_type_flex_array.sh  | 42 ++++++++++++++++++-
 tools/perf/ui/browsers/annotate-data.c        |  7 ++--
 tools/perf/util/annotate-data.c               | 25 ++++++++++-
 tools/perf/util/annotate-data.h               |  8 ++++
 4 files changed, 75 insertions(+), 7 deletions(-)
tools/perf/tests/shell/data_type_flex_array.sh +41 -1
index 620c28ec24059661..6adbb556f0e48921 100755
@@ -67,5 +67,45 @@ if ! grep -Fq "# data-type: struct flex +0x4 (data)" "$perfout"; then
 	exit 1
 fi
 
-echo "flexible array member resolved"
+# The accesses to the flexible array are resolved past the end of the
+# struct: they must count for the struct, not only for the member.
+if ! perf annotate --data-type -i "$perfdata" --stdio > "$perfout"; then
+	echo "FAIL: perf annotate --data-type"
+	cleanup
+	exit 1
+fi
+
+if ! awk '
+	$1 + 0 == 100.00 && /struct flex/ { struct_ok = 1 }
+	$1 + 0 > 0 && /char\[\]/ && /data;/ { data_ok = 1 }
+	END { exit !(struct_ok && data_ok) }
+' <(sed -n "/^Annotate type: 'struct flex' in/,/^Annotate type: /p" "$perfout"); then
+	echo "FAIL: --data-type does not count the flexible array accesses"
+	tail -n 30 "$perfout"
+	cleanup
+	exit 1
+fi
+
+# Same with the samples and period columns, the other two display modes.
+for mode in --show-nr-samples --show-total-period; do
+	if ! perf annotate --data-type -i "$perfdata" --stdio "$mode" > "$perfout"; then
+		echo "FAIL: perf annotate --data-type $mode"
+		cleanup
+		exit 1
+	fi
+
+	if ! awk '
+		$1 + 0 > 0 && /struct flex/ { total = $1 + 0 }
+		/int/ && /len;/ { len = $1 + 0 }
+		/char\[\]/ && /data;/ { data = $1 + 0 }
+		END { exit !(total > 0 && data > 0 && total == data + len) }
+	' <(sed -n "/^Annotate type: 'struct flex' in/,/^Annotate type: /p" "$perfout"); then
+		echo "FAIL: --data-type $mode does not count the flexible array accesses"
+		tail -n 30 "$perfout"
+		cleanup
+		exit 1
+	fi
+done
+
+echo "flexible array member resolved and counted"
 cleanup
tools/perf/ui/browsers/annotate-data.c +3 -4
index 0f778788df4a934b..e4047e97e8a943a4 100644
@@ -53,12 +53,11 @@ static int get_member_overhead(struct annotated_data_type *adt,
 			       struct evsel *leader)
 {
 	struct annotated_member *member = entry->data;
-	int i, k;
+	int i, k, end = annotated_member__extent(member);
 
-	for (i = 0; i < member->size; i++) {
+	for (i = member->offset; i < end; i++) {
 		struct type_hist *h;
 		struct evsel *evsel;
-		int offset = member->offset + i;
 
 		k = 0;
 		for_each_group_evsel(evsel, leader) {
@@ -69,7 +68,7 @@ static int get_member_overhead(struct annotated_data_type *adt,
 				continue;
 
 			h = &adt->histograms[evsel->core.idx];
-			if (hashmap__find(&h->samples, offset, &hist))
+			if (hashmap__find(&h->samples, i, &hist))
 				update_hist_entry(&entry->hists[k], hist);
 			k++;
 		}
tools/perf/util/annotate-data.c +23 -2
index 2332d465f9751ef3..19c1de5c29853f69 100644
@@ -2208,6 +2208,26 @@ static void print_annotated_data_value(struct type_hist *h, u64 period, int nr_s
 		color_fprintf(stdout, color, " %7.2f", percent);
 }
 
+/*
+ * A flexible array member is resolved past the end of its parent, so the
+ * parent's samples are not bounded by its size.  A GNU extension non-last
+ * member with a flexible array can overlap the next member and double-count.
+ */
+int annotated_member__extent(struct annotated_member *member)
+{
+	struct annotated_member *child;
+	int end = member->offset + member->size;
+
+	list_for_each_entry(child, &member->children, node) {
+		int child_end = annotated_member__extent(child);
+
+		if (child_end > end)
+			end = child_end;
+	}
+
+	return end;
+}
+
 static void print_annotated_data_type(struct annotated_data_type *mem_type,
 				      struct annotated_member *member,
 				      struct evsel *evsel, int indent)
@@ -2215,6 +2235,7 @@ static void print_annotated_data_type(struct annotated_data_type *mem_type,
 	struct annotated_member *child;
 	struct type_hist *h;
 	int i, nr_events = 0, samples = 0;
+	int end = annotated_member__extent(member);
 	u64 period = 0;
 	int width = symbol_conf.show_total_period ? 11 : 7;
 	struct evsel *pos;
@@ -2228,10 +2249,10 @@ static void print_annotated_data_type(struct annotated_data_type *mem_type,
 
 		samples = 0;
 		period = 0;
-		for (i = 0; i < member->size; i++) {
+		for (i = member->offset; i < end; i++) {
 			struct type_hist_entry *entry;
 
-			if (!hashmap__find(&h->samples, member->offset + i, &entry))
+			if (!hashmap__find(&h->samples, i, &entry))
 				continue;
 
 			samples += entry->nr_samples;
tools/perf/util/annotate-data.h +8 -0
index 184262c7356213fa..6e0d410929651426 100644
@@ -260,6 +260,9 @@ void global_var_type__tree_delete(struct rb_root *root);
 /* Print data type annotation (including members) on stdout */
 int hist_entry__annotate_data_tty(struct hist_entry *he, struct evsel *evsel);
 
+/* End offset of a member, including a flexible array's children */
+int annotated_member__extent(struct annotated_member *member);
+
 /* Get name of member field at the given offset in the data type */
 int annotated_data_type__get_member_name(struct annotated_data_type *adt,
 					 char *buf, size_t sz, int member_offset);
@@ -316,6 +319,11 @@ static inline int hist_entry__annotate_data_tty(struct hist_entry *he __maybe_un
 	return -1;
 }
 
+static inline int annotated_member__extent(struct annotated_member *member)
+{
+	return member->offset + member->size;
+}
+
 static inline int annotated_data_type__get_member_name(struct annotated_data_type *adt __maybe_unused,
 						       char *buf __maybe_unused,
 						       size_t sz __maybe_unused,
Signature · 1 line
2.56.1
#12 lore raw

Re: [PATCH v8 06/13] perf annotate-data: Count flexible array accesses for the whole struct

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

From: Arnaldo Carvalho de Melo <[email protected]>

The per-member percentage sums the histogram entries in the member's own [offset, offset + size) range. A flexible array member is resolved past the end of its struct, so the struct row only covered its declared size and showed 0.00% while the member row showed 100.00% and the header said N samples.

Take a member's extent as the end of its furthest child as well, so the struct counts what was resolved past it. Union members all start at offset 0, so a plain union keeps its size; a member that is itself a struct with a flexible array extends the union too. The TUI browser accounts the members the same way, use the extent there as well.

Quoted 7 lines

Extend tests/shell/data_type_flex_array.sh to check that the accesses count for the struct in the percent, samples and period columns.

Fixes aaca646915a1bb53 ("perf annotate-data: Adjust type offset for flex-array")
Cc Namhyung Kim <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#13 lore raw

PATCH v8 7/13 perf tests: Exercise data type resolution from a register

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

At -O2 a struct pointer lives in a register (with DWARF describing it with a register location on register-argument ABIs), while the unoptimized workloads the data type tests profile keep their variables on the stack.

Add a regptr workload with a noinline function that takes the pointer from a volatile global, so the compiler cannot constant-propagate the object address, and check that its three member accesses are resolved from that register.

---
 tools/perf/tests/builtin-test.c              |  1 +
 tools/perf/tests/shell/data_type_register.sh | 63 ++++++++++++++++++++
 tools/perf/tests/tests.h                     |  1 +
 tools/perf/tests/workloads/Build             |  2 +
 tools/perf/tests/workloads/regptr.c          | 60 +++++++++++++++++++
 5 files changed, 127 insertions(+)
 create mode 100755 tools/perf/tests/shell/data_type_register.sh
 create mode 100644 tools/perf/tests/workloads/regptr.c
tools/perf/tests/builtin-test.c +1 -0
index 8fc425d470c17dbf..fe4d4cd54f85d502 100644
@@ -215,6 +215,7 @@ static struct test_workload *workloads[] = {
 	&workload__false_sharing,
 	&workload__global_data,
 	&workload__flex_array,
+	&workload__regptr,
 
 #ifdef HAVE_RUST_SUPPORT
 	&workload__code_with_type,
tools/perf/tests/shell/data_type_register.sh new file +63 -0

63 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index 0cf33d91804f19c4..b03c56d5e4c98aaf 100644
@@ -275,6 +275,7 @@ DECLARE_WORKLOAD(callchain);
 DECLARE_WORKLOAD(false_sharing);
 DECLARE_WORKLOAD(global_data);
 DECLARE_WORKLOAD(flex_array);
+DECLARE_WORKLOAD(regptr);
 
 #ifdef HAVE_RUST_SUPPORT
 DECLARE_WORKLOAD(code_with_type);
tools/perf/tests/workloads/Build +2 -0
index 74a0cbe49dc93533..17189458032c0a17 100644
@@ -19,6 +19,7 @@ perf-test-y += callchain.o
 perf-test-y += false_sharing.o
 perf-test-y += global_data.o
 perf-test-y += flex_array.o
+perf-test-y += regptr.o
 
 ifeq ($(CONFIG_RUST_SUPPORT),y)
     perf-test-y += code_with_type.o
@@ -39,3 +40,4 @@ CFLAGS_callchain.o        = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_false_sharing.o    = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_global_data.o      = -g -O0 -fno-inline -U_FORTIFY_SOURCE
 CFLAGS_flex_array.o       = -g -O0 -fno-inline -U_FORTIFY_SOURCE
+CFLAGS_regptr.o           = -g -O2
tools/perf/tests/workloads/regptr.c new file +60 -0

60 lines not on this page · raw message

Signature · 1 line
2.56.1
#14 lore raw

Re: [PATCH v8 07/13] perf tests: Exercise data type resolution from a register

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

From: Arnaldo Carvalho de Melo <[email protected]>

At -O2 a struct pointer lives in a register (with DWARF describing it with a register location on register-argument ABIs), while the unoptimized workloads the data type tests profile keep their variables on the stack.

Quoted 6 lines

Add a regptr workload with a noinline function that takes the pointer from a volatile global, so the compiler cannot constant-propagate the object address, and check that its three member accesses are resolved from that register.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author maintainer
#15 lore raw

PATCH v8 8/13 perf annotate: Print the stats after the annotations

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

With --code-with-type the instruction stats are printed from hists__find_annotations() before that event is annotated: the first event reports zeros and later events can report stale counts. The data type total is only counted in --data-type mode, so --type-stat without it is incomplete too.

Print the stats once after all events have been annotated, warning if --type-stat is used without --data-type. Leave the TUI's alternate screen before printing, so the stats remain on the terminal.

Fixes 58824fa0087e1cb7 ("perf annotate: Add --insn-stat option for debugging")
Fixes 61a9741e9f78c64c ("perf annotate: Add --type-stat option for debugging")
Cc Namhyung Kim <[email protected]>
---
 tools/perf/Documentation/perf-annotate.txt |  2 +-
 tools/perf/builtin-annotate.c              | 19 ++++--
 tools/perf/tests/shell/annotate_stats.sh   | 69 ++++++++++++++++++++++
 3 files changed, 84 insertions(+), 6 deletions(-)
 create mode 100755 tools/perf/tests/shell/annotate_stats.sh
tools/perf/Documentation/perf-annotate.txt +1 -1
index 1a90b09a12d5abb1..d27eff28ba4f6af0 100644
@@ -169,7 +169,7 @@ include::itrace.txt[]
 	all data types it finds.
 
 --type-stat::
-	Show stats for the data type annotation.
+	Show stats for the data type annotation (with --data-type).
 
 --skip-empty::
 	Do not display empty (or dummy) events.
tools/perf/builtin-annotate.c +14 -5
index 331adbdbd635917d..8ced8a4aebf07709 100644
@@ -414,11 +414,6 @@ static void hists__find_annotations(struct hists *hists,
 	struct rb_node *nd = rb_first_cached(&hists->entries), *next;
 	int key = K_RIGHT;
 
-	if (ann->type_stat)
-		print_annotate_data_stat(&ann_data_stat);
-	if (ann->insn_stat)
-		print_annotate_item_stat(&ann_insn_stat, "Instruction");
-
 	while (nd) {
 		struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
 		struct annotation *notes;
@@ -660,6 +655,17 @@ static int __cmd_annotate(struct perf_annotate *ann)
 		hists__find_annotations(hists, pos, ann);
 	}
 
+	if (use_browser == 1 && (ann->insn_stat || (ann->data_type && ann->type_stat))) {
+		/* Leave the alternate screen before printing to the terminal. */
+		ui__exit(false);
+		use_browser = 0;
+	}
+
+	if (ann->data_type && ann->type_stat)
+		print_annotate_data_stat(&ann_data_stat);
+	if (ann->insn_stat)
+		print_annotate_item_stat(&ann_insn_stat, "Instruction");
+
 	if (use_browser == 2) {
 		void (*show_annotations)(void);
 
@@ -865,6 +871,9 @@ int cmd_annotate(int argc, const char **argv)
 	if (quiet)
 		perf_quiet_option();
 
+	if (annotate.type_stat && !annotate.data_type)
+		pr_warning("Warning: --type-stat needs --data-type\n");
+
 	data.path = input_name;
 
 	perf_tool__init(&annotate.tool, /*ordered_events=*/true);
tools/perf/tests/shell/annotate_stats.sh new file +69 -0

69 lines not on this page · raw message

Signature · 1 line
2.56.1
#16 lore raw

Re: [PATCH v8 08/13] perf annotate: Print the stats after the annotations

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

From: Arnaldo Carvalho de Melo <[email protected]>

With --code-with-type the instruction stats are printed from hists__find_annotations() before that event is annotated: the first event reports zeros and later events can report stale counts. The data type total is only counted in --data-type mode, so --type-stat without it is incomplete too.

Quoted 8 lines

Print the stats once after all events have been annotated, warning if --type-stat is used without --data-type. Leave the TUI's alternate screen before printing, so the stats remain on the terminal.

Fixes 58824fa0087e1cb7 ("perf annotate: Add --insn-stat option for debugging")
Fixes 61a9741e9f78c64c ("perf annotate: Add --type-stat option for debugging")
Cc Namhyung Kim <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#17 lore raw

PATCH v8 9/13 perf tests: Silence the libbfd probe in build-test

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

build-test evaluates the libbfd probe at parse time and the compiler's stderr isn't captured by $(shell ...), so without binutils-devel it prints "bfd.h: No such file or directory" once per tests/make invocation, five times per run.

Redirect the compiler's stderr; the empty result still skips the nondistro tests as intended.

Fixes 523471c5163659c6 ("perf build: Skip nondistro build test if libbfd is old")
Cc James Clark <[email protected]>
---
 tools/perf/tests/make | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/tests/make +1 -1
index 7524de5228029e7e..e6d7ac49b5b1693d 100644
@@ -128,7 +128,7 @@ make_minimal        += NO_SDT=1 NO_JVMTI=1 NO_LIBZSTD=1
 make_minimal        += NO_CAPSTONE=1
 
 # binutils 2_42 and newer have bfd_thread_init()
-new_libbfd := $(shell echo '#include <bfd.h>' | $(CC) -E -x c - | grep bfd_thread_init)
+new_libbfd := $(shell echo '#include <bfd.h>' | $(CC) -E -x c - 2>/dev/null | grep bfd_thread_init)
 
 # Whether libLLVM can be built, which needs the llvm-devel/llvm-dev headers and
 # libraries of version 13 or newer, not just llvm-config. This mirrors the
Signature · 1 line
2.56.1
#18 lore raw

Re: [PATCH v8 09/13] perf tests: Silence the libbfd probe in build-test

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

From: Arnaldo Carvalho de Melo <[email protected]>

build-test evaluates the libbfd probe at parse time and the compiler's stderr isn't captured by $(shell ...), so without binutils-devel it prints "bfd.h: No such file or directory" once per tests/make invocation, five times per run.

Quoted 7 lines

Redirect the compiler's stderr; the empty result still skips the nondistro tests as intended.

Fixes 523471c5163659c6 ("perf build: Skip nondistro build test if libbfd is old")
Cc James Clark <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author maintainer
#19 lore raw

PATCH v8 10/13 perf build: Record the features checked outside FEATURE_TESTS

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

llvm-perf and rust are in FEATURE_DISPLAY but not in FEATURE_TESTS, and jvmti and jvmti-cmlr are in neither list: they can't be part of the test-all fast path, which sets every FEATURE_TESTS entry to 1 when test-all.c builds. Since FEATURE-DUMP is written from FEATURE_TESTS only, a FEATURES_DUMP= build, as used by build-test, never sees them and silently builds without libLLVM, the rust workloads and the jvmti agent.

Record the display features and the jvmti ones that aren't in FEATURE_TESTS in the dump after the regular feature checks have run.

Fixes 206dcfca1f5cfac3 ("perf build: Autodetect minimum required llvm-dev version")
Fixes 3f5dfa472ea6771c ("tools build: Fix rust feature detection")
Cc James Clark <[email protected]>
---
 tools/perf/Makefile.config | 7 +++++++
 1 file changed, 7 insertions(+)
tools/perf/Makefile.config +7 -0
index 78423b0dcc73ac14..3070947d18772e0e 100644
@@ -1313,3 +1313,10 @@ endif
 # tests.
 $(shell rm -f $(FEATURE_DUMP_FILENAME))
 $(foreach feat,$(FEATURE_TESTS),$(shell echo "$(call feature_assign,$(feat))" >> $(FEATURE_DUMP_FILENAME)))
+# Features checked outside FEATURE_TESTS aren't part of the test-all fast
+# path, so they have to be checked explicitly and recorded here too,
+# otherwise a FEATURES_DUMP= build silently disables them (llvm-perf,
+# rust and the jvmti agent).
+ifeq ($(FEATURES_DUMP),)
+$(foreach feat,$(filter-out $(FEATURE_TESTS),$(FEATURE_DISPLAY) jvmti jvmti-cmlr),$(shell echo "$(call feature_assign,$(feat))" >> $(FEATURE_DUMP_FILENAME)))
+endif
Signature · 1 line
2.56.1
#20 lore raw

Re: [PATCH v8 10/13] perf build: Record the features checked outside FEATURE_TESTS

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

From: Arnaldo Carvalho de Melo <[email protected]>

llvm-perf and rust are in FEATURE_DISPLAY but not in FEATURE_TESTS, and jvmti and jvmti-cmlr are in neither list: they can't be part of the test-all fast path, which sets every FEATURE_TESTS entry to 1 when test-all.c builds. Since FEATURE-DUMP is written from FEATURE_TESTS only, a FEATURES_DUMP= build, as used by build-test, never sees them and silently builds without libLLVM, the rust workloads and the jvmti agent.

Quoted 7 lines

Record the display features and the jvmti ones that aren't in FEATURE_TESTS in the dump after the regular feature checks have run.

Fixes 206dcfca1f5cfac3 ("perf build: Autodetect minimum required llvm-dev version")
Fixes 3f5dfa472ea6771c ("tools build: Fix rust feature detection")
Cc James Clark <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#21 lore raw

PATCH v8 11/13 perf tests: Fix the Intel PT virtual LBR check

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

On an Intel host the virtual LBR check failed with:

Warning: Processed 29 samples and lost 100.00%

The record leaves the buffer sizes to the tool defaults: the data ring follows perf_event_mlock_kb, and the runner's small value left a single page, too small for the AUX samples. Pin 4 data and 64 AUX pages, so the test does not depend on the host sysctl, and give the AUX ring room instead of the single page the tool sizes to the 4 KiB snapshot. Both fit in the default mlock allowance regardless of the CPU count.

Also require the Python perf module to export session: a perf module without it, like the distro's python3-perf, made the check fail instead of skipping.

Fixes 915d6b14dc0c8971 ("perf test: Migrate Intel PT virtual LBR test to Python API")
Cc Adrian Hunter <[email protected]>
Cc Ian Rogers <[email protected]>
---
 tools/perf/tests/shell/test_intel_pt.sh | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
tools/perf/tests/shell/test_intel_pt.sh +6 -4
index c0ecece0a8255124..96f5c132cebf23e6 100755
@@ -384,13 +384,15 @@ test_virtual_lbr()
 	# shellcheck source=lib/setup_python.sh
 	. "${shelldir}"/lib/setup_python.sh
 
-	if ! "$PYTHON" -c 'import perf' > /dev/null 2>&1; then
-		echo "SKIP: Python perf module not found"
+	if ! "$PYTHON" -c 'import perf; perf.session' > /dev/null 2>&1; then
+		echo "SKIP: Python perf module with session support not found"
 		return 2
 	fi
 
-	# Check if virtual lbr is working
-	perf_record_no_bpf -o "${tmpfile}" --aux-sample \
+	# The default data ring follows perf_event_mlock_kb and can be too
+	# small for the AUX samples; pin 4 data and 64 AUX pages, which fit
+	# in the default allowance.
+	perf_record_no_bpf -m 4,64 -o "${tmpfile}" --aux-sample \
 		-e '{intel_pt//,cycles}:u' perf test -w brstack || return 1
 	perf inject --itrace=L -i "${tmpfile}" -o "${perfdatafile}" || return 1
 	output=$("$PYTHON" "${shelldir}/lib/perf_brstack_max.py" -i "${perfdatafile}") || return 1
Signature · 1 line
2.56.1
#22 lore raw

Re: [PATCH v8 11/13] perf tests: Fix the Intel PT virtual LBR check

Sashiko has reviewed this patch and found no issues.
Quoted 13 lines

From: Arnaldo Carvalho de Melo <[email protected]>

On an Intel host the virtual LBR check failed with:

Warning: Processed 29 samples and lost 100.00%

The record leaves the buffer sizes to the tool defaults: the data ring follows perf_event_mlock_kb, and the runner's small value left a single page, too small for the AUX samples. Pin 4 data and 64 AUX pages, so the test does not depend on the host sysctl, and give the AUX ring room instead of the single page the tool sizes to the 4 KiB snapshot. Both fit in the default mlock allowance regardless of the CPU count.

Quoted 8 lines

Also require the Python perf module to export session: a perf module without it, like the distro's python3-perf, made the check fail instead of skipping.

Fixes 915d6b14dc0c8971 ("perf test: Migrate Intel PT virtual LBR test to Python API")
Cc Adrian Hunter <[email protected]>
Cc Ian Rogers <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author maintainer
#23 lore raw

PATCH v8 12/13 perf test: Drop samples without an IP in the dlfilter test

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

Since v7.3 the kernel zeroes PERF_SAMPLE_IP when a user-only event skids into kernel mode, so that kernel register state is not exposed to user
space: commit 166f10836a653dfa ("perf/core: Fix kernel register info leak via hardware skid").

The test records without an event modifier, which is user-only only when perf falls back to cycles:u for an unprivileged user, which is why root runs never saw it. The dlfilter keeps those ip 0 samples, and the check that nothing but test_loop survives then trips on their lines: the comm column reads "perf". Drop them, as everything except test_loop must be filtered out.

Fixes 199d5e872a9ce737 ("perf tests script dlfilter: Add a dlfilter test")
---
 tools/perf/tests/shell/script_dlfilter.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/tests/shell/script_dlfilter.sh +1 -1
index 88222280f6094fd0..797cd9ae84141f64 100755
@@ -46,7 +46,7 @@ int filter_event(void *data, const struct perf_dlfilter_sample *sample, void *ct
 	const struct perf_dlfilter_al *al;
 
 	if (!sample->ip)
-		return 0;
+		return 1;
 
 	al = perf_dlfilter_fns.resolve_ip(ctx);
 	if (!al || !al->sym || strcmp(al->sym, "test_loop"))
Signature · 1 line
2.56.1
#24 lore raw

Re: [PATCH v8 12/13] perf test: Drop samples without an IP in the dlfilter test

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

From: Arnaldo Carvalho de Melo <[email protected]>

Since v7.3 the kernel zeroes PERF_SAMPLE_IP when a user-only event skids into kernel mode, so that kernel register state is not exposed to user
space: commit 166f10836a653dfa ("perf/core: Fix kernel register info leak via hardware skid").

The test records without an event modifier, which is user-only only when perf falls back to cycles:u for an unprivileged user, which is why root runs never saw it. The dlfilter keeps those ip 0 samples, and the check that nothing but test_loop survives then trips on their lines: the comm column reads "perf". Drop them, as everything except test_loop must be filtered out.

Quoted 3 lines
Fixes 199d5e872a9ce737 ("perf tests script dlfilter: Add a dlfilter test")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
author maintainer
#25 lore raw

PATCH v8 13/13 perf test: Skip the LBR inline unwinding check when unsupported

In reply to Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <[email protected]>

The LBR check takes caps/branches as sufficient to record cycles with --call-graph lbr, but the file only says the PMU has an LBR: AMD LBRv2 rejects the call stack mode with EOPNOTSUPP and AMD BRS, which samples only its own retired branches event, rejects cycles with EINVAL, so the test fails on AMD instead of skipping.

Skip when the same event records without the branch stack, so a PMU without the LBR call stack skips while a perf record that fails for another reason still shows its error and fails the test.

Fixes 446c595dc0dd1759 ("perf test addr2line_inlines: Ensure inline information shows on LBR leaves")
Cc Ian Rogers <[email protected]>
---
 tools/perf/tests/shell/addr2line_inlines.sh | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
tools/perf/tests/shell/addr2line_inlines.sh +19 -1
index e8754ef2d7f21ac2..050e95c0fea12aae 100755
@@ -8,6 +8,7 @@ err=0
 test_dir=$(mktemp -d /tmp/perf-test-inline-addr2line.XXXXXXXXXX)
 perf_data="${test_dir}/perf.data"
 perf_script_txt="${test_dir}/perf_script.txt"
+perf_record_err="${test_dir}/perf_record.err"
 
 cleanup() {
     rm -rf "${test_dir}"
@@ -71,7 +72,24 @@ test_lbr() {
     fi
 
     # Record data. Currently only dwarf callchains support inlined functions.
-    perf record --call-graph lbr -e cycles:u -o "${perf_data}" -- perf test -w inlineloop 1
+    # caps/branches does not mean the LBR call stack is supported: AMD LBRv2
+    # rejects it with EOPNOTSUPP and AMD BRS, which samples only its own
+    # retired branches event, rejects cycles with EINVAL. Skip when the same
+    # event records without the branch stack.
+    if ! perf record --call-graph lbr -e cycles:u -o "${perf_data}" -- \
+            perf test -w inlineloop 1 2> "${perf_record_err}"
+    then
+        if perf record -e cycles:u -o "${perf_data}" -- true 2> /dev/null
+        then
+            echo "Skip: LBR call stack not supported by the PMU"
+        else
+            cat "${perf_record_err}"
+            echo "Inline unwinding lbr verification test [Failed to record]"
+            err=1
+        fi
+        return
+    fi
+    cat "${perf_record_err}"
 
     # Check output with inline (default) and srcline
     perf script -i "${perf_data}" --fields +srcline > "${perf_script_txt}"
Signature · 1 line
2.56.1
#26 lore raw

Re: [PATCH v8 13/13] perf test: Skip the LBR inline unwinding check when unsupported

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

From: Arnaldo Carvalho de Melo <[email protected]>

The LBR check takes caps/branches as sufficient to record cycles with --call-graph lbr, but the file only says the PMU has an LBR: AMD LBRv2 rejects the call stack mode with EOPNOTSUPP and AMD BRS, which samples only its own retired branches event, rejects cycles with EINVAL, so the test fails on AMD instead of skipping.

Quoted 7 lines

Skip when the same event records without the branch stack, so a PMU without the LBR call stack skips while a perf record that fails for another reason still shows its error and fails the test.

Fixes 446c595dc0dd1759 ("perf test addr2line_inlines: Ensure inline information shows on LBR leaves")
Cc Ian Rogers <[email protected]>

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13