Skip to contentSkip to conversation

perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

PATCH Superseded Ian Rogers 6 participants 190 messages Apr 24 – Jun 15 perf events Page 1 of 4

lore
Share & tools
lore

Ian Rogers

author reviewer
#0 lore raw

PATCH 1/2 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

If perf.data files are taken from one machine to another they make leak virtual addresses and so weaken ASLR on the machine they are coming from. Add a '--aslr' option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

---
 tools/perf/builtin-inject.c |  11 +-
 tools/perf/util/Build       |   1 +
 tools/perf/util/aslr.c      | 752 ++++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |  10 +
 4 files changed, 773 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +10 -1
index f174bc69cec4..fa3a71e23f1b 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -2564,6 +2566,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2575,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,7 +2689,9 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr)
+		tool = aslr_tool__new(&inject.tool);
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
@@ -2789,6 +2796,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +752 -0

752 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#1 lore raw

PATCH 2/2 perf test: Add inject ASLR test

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

Assisted-by Gemini:gemini-3.1-pro-preview
---
 tools/perf/tests/shell/inject_aslr.sh | 381 ++++++++++++++++++++++++++
 1 file changed, 381 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +381 -0
new file mode 100755
index 000000000000..17544fe9ef6c
@@ -0,0 +1,381 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+# Set path to built perf
+PERF="/tmp/perf3/perf"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="${PERF} test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+set -e
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+  trap - EXIT TERM INT
+}
+
+trap_cleanup() {
+  echo "Unexpected signal in ${FUNCNAME[1]}"
+  cleanup
+  exit 1
+}
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  ${PERF} script -i "$file" | awk '{for(i=1;i<=NF;i++) if($i ~ /noploop\+/) {print $(i-1); exit}}'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.basic.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.basic.XXXXXX)
+
+  ${PERF} record -e task-clock:u -o "${data}" ${prog}
+  ${PERF} inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.pipe.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.pipe.XXXXXX)
+
+  # Use tee to save the original pipe data for comparison
+  ${PERF} record -e task-clock:u -o - ${prog} | tee "${data}" | ${PERF} inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.callchain.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.callchain.XXXXXX)
+
+  ${PERF} record -g -e task-clock:u -o "${data}" ${prog}
+  ${PERF} inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Also check that the full script output differs (to cover callchains)
+    orig_script=$(${PERF} script -i "${data}" | grep -A 5 noploop | head -n 20)
+    new_script=$(${PERF} script -i "${data2}" | grep -A 5 noploop | head -n 20)
+
+    if [ "$orig_script" = "$new_script" ]; then
+      echo "Callchain ASLR test [Failed - callchain output is identical]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+      rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp /tmp/perf.data.report.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+
+  ${PERF} record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  ${PERF} inject -b -i "${data}" -o "${data_clean}"
+  ${PERF} inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  ${PERF} report -i "${data_clean}" --stdio > "${report1}"
+  ${PERF} report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}"
+
+  diff -u "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+  rm -f "${data}" "${data2}" "${data_clean}" "${data}.old" "${data2}.old" "${data_clean}.old"
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp /tmp/perf.data.pipe_report.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.pipe_report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  ${PERF} record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    ${PERF} inject -b --aslr -o "${data2}"
+  ${PERF} inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  ${PERF} report -i "${data_clean}" --stdio > "${report1}"
+  ${PERF} report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}"
+
+  diff -u "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+  rm -f "${data}" "${data2}" "${data_clean}" "${data}.old" "${data2}.old" "${data_clean}.old"
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp /tmp/perf.data.dropped.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.dropped.XXXXXX)
+
+  # Check if --phys-data is supported by recording a short run
+  if ! ${PERF} record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  ${PERF} record -e task-clock:u --phys-data -o "${data}" ${prog}
+  ${PERF} inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that samples are dropped.
+  samples_count=$(${PERF} script -i "${data2}" | wc -l)
+
+  if [ "$samples_count" -gt 0 ]; then
+    echo "Dropped samples test [Failed - samples were not dropped]"
+    err=1
+  else
+    echo "Dropped samples test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp /tmp/perf.data.kernel.XXXXXX)
+  local kdata2
+  kdata2=$(mktemp /tmp/perf.data2.kernel.XXXXXX)
+  local log_file
+  log_file=$(mktemp /tmp/kernel_record.log.XXXXXX)
+
+  # Try to record kernel samples
+  if ! ${PERF} record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  ${PERF} inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  orig_addr=$(${PERF} script -i "${kdata}" | awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')
+  new_addr=$(${PERF} script -i "${kdata2}" | awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+    rm -f "${kdata}" "${kdata2}" "${log_file}" "${kdata}.old" "${kdata2}.old"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp /tmp/perf.data.kernel_report.XXXXXX)
+  local kdata2
+  kdata2=$(mktemp /tmp/perf.data2.kernel_report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+  local log_file
+  log_file=$(mktemp /tmp/kernel_report_record.log.XXXXXX)
+
+  # Try to record kernel samples
+  if ! ${PERF} record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  ${PERF} inject -b -i "${kdata}" -o "${data_clean}"
+  ${PERF} inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  ${PERF} report -i "${data_clean}" --stdio > "${report1}"
+  ${PERF} report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}"
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  awk '{$3 = ($3 ~ /^\[.*\]$/ ? "[kernel]" : $3); \
+        for(i=1;i<=NF;i++) \
+          if($i ~ /^ffff/ || $i ~ /^0x/ || $i == "0000000000000000") \
+            $i = "[addr]"; \
+        print}' "${report1_clean}" | sort > "${report1_norm}"
+  awk '{$3 = ($3 ~ /^\[.*\]$/ ? "[kernel]" : $3); \
+        for(i=1;i<=NF;i++) \
+          if($i ~ /^ffff/ || $i ~ /^0x/ || $i == "0000000000000000") \
+            $i = "[addr]"; \
+        print}' "${report2_clean}" | sort > "${report2_norm}"
+
+  diff -u "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+  rm -f "${kdata}" "${kdata2}" "${data_clean}" "${log_file}" "${kdata}.old" "${kdata2}.old" "${data_clean}.old"
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#2 lore raw

Re: [PATCH v1 2/2] perf test: Add inject ASLR test

Sashiko AI review found 4 potential issue(s): - [High] Hardcoded and insecure PERF binary path - [Medium] Unhandled grep pipeline aborts script via set -e - [Medium] Architecture assumption in…

Sashiko AI review found 4 potential issue(s):
- [High] Hardcoded and insecure PERF binary path
- [Medium] Unhandled grep pipeline aborts script via set -e
- [Medium] Architecture assumption in kernel address parsing breaks 32-bit systems
- [Medium] Improper cleanup of temporary files and directories
--

commit 55c497e7d1e9a304b5ad52e13004ec9955f6ffcb
Author: Ian Rogers <[email protected]>

perf test: Add inject ASLR test

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature.

Quoted 8 lines
tools/perf/tests/shell/inject_aslr.sh new file +2 -0
new file mode 100755
index 00000000000000..17544fe9ef6c02
@@ -0,0 +1,381 @@
+#!/bin/bash
+# perf inject --aslr test

tools/perf/tests/shell/inject_aslr.sh line 12

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+# SPDX-License-Identifier: GPL-2.0
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+# Set path to built perf
+PERF="/tmp/perf3/perf"

Is this hardcoded path safe and portable? If the test is run as root, could a local user place a malicious executable at /tmp/perf3/perf and escalate privileges?

Also, won't this break the test in standard CI environments?

[ ... ]

Quoted 4 lines
tools/perf/tests/shell/inject_aslr.sh new file +4 -0
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"

tools/perf/tests/shell/inject_aslr.sh line 40

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+  fi
+  trap - EXIT TERM INT
+}
+
+trap_cleanup() {
+  echo "Unexpected signal in ${FUNCNAME[1]}"
+  cleanup
+  exit 1
+}
+trap trap_cleanup TERM INT

Because the script uses set -e, should this also trap EXIT? Without an EXIT trap, if a command fails and triggers an exit, temp_dir might be leaked.

[ ... ]

tools/perf/tests/shell/inject_aslr.sh line 50

Quoted 4 lines
tools/perf/tests/shell/inject_aslr.sh new file +4 -0
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.basic.XXXXXX)

Should these temporary files be created inside temp_dir instead of directly in /tmp?

[ ... ]

Quoted 4 lines
tools/perf/tests/shell/inject_aslr.sh new file +4 -0
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then

tools/perf/tests/shell/inject_aslr.sh line 75

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}

If the test fails and err=1 is set, won't these temporary files be permanently leaked?

This pattern appears in multiple test functions. Also, in test_dropped_samples, if the test returns early due to unsupported --phys-data, these files are also leaked.

[ ... ]

Quoted 18 lines
tools/perf/tests/shell/inject_aslr.sh new file +18 -0
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp /tmp/perf.data.kernel.XXXXXX)
+  local kdata2
+  kdata2=$(mktemp /tmp/perf.data2.kernel.XXXXXX)
+  local log_file
+  log_file=$(mktemp /tmp/kernel_record.log.XXXXXX)
+
+  # Try to record kernel samples
+  if ! ${PERF} record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then

tools/perf/tests/shell/inject_aslr.sh line 282

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  ${PERF} inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  orig_addr=$(${PERF} script -i "${kdata}" | awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')
+  new_addr=$(${PERF} script -i "${kdata2}" | awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')

Will this parsing work on 32-bit architectures? Kernel space typically resides at different offsets (such as 0xc0000000 or 0x80000000) on 32-bit platforms, so hardcoding ^ffff might cause the test to spuriously fail there.

[ ... ]

Quoted 1 line
tools/perf/tests/shell/inject_aslr.sh new file +1 -0
+test_kernel_report_aslr() {

[ ... ]

tools/perf/tests/shell/inject_aslr.sh line 341

Quoted 6 lines
tools/perf/tests/shell/inject_aslr.sh new file +6 -0
+  ${PERF} report -i "${data_clean}" --stdio > "${report1}"
+  ${PERF} report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}"

What happens if report1 contains no matching lines?

The second grep -v would receive empty input and exit with a status code of 1. Since the script uses set -e and doesn't have || true on this pipeline, won't this cause the script to abort immediately and silently?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#3 lore raw
In reply to Ian Rogers
Sashiko AI review found 8 potential issue(s): - [High] Missing `thread__put()` causes severe memory leak of thread objects per event. - [High] Incorrect bitmask check for branch stack flags causes…

Sashiko AI review found 8 potential issue(s):
- [High] Missing thread__put() causes severe memory leak of thread objects per event.
- [High] Incorrect bitmask check for branch stack flags causes catastrophic sample parsing failure.
- [High] Incorrect size calculation for PERF_SAMPLE_RAW causes parsing desynchronization and uninitialized memory leak.
- [High] Off-by-one error in copy_u64() bounds checking allows out-of-bounds memory reads.
- [High] Unconditional zeroing of union fields in perf_event_attr corrupts PMU configurations.
- [High] hashmap usage causes 32-bit compilation failures and silent 64-bit address truncation.
- [Medium] Unhandled guest callchain contexts cause valid samples to be discarded.
- [Medium] Missing integer overflow checks on branch_stack->nr allow bounds-check bypass.
--

commit cb2629f8e0c5449ea2cd944df7889ca64868a5eb
Author: Ian Rogers <[email protected]>
Subject: perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

This commit introduces an ASLR tool to perf inject. It allows remapping virtual memory addresses to prevent leaking ASLR information when sharing perf.data files. Unhandled events are dropped to remain conservative.

tools/perf/util/aslr.c new file +0 -0

[ ... ]

Quoted 5 lines
(quoted diff) +5 -0
+static u64 aslr_tool__remap_address(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u8 cpumode,
+				    u64 addr)
+{

[ ... ]

Review

Quoted 1 line
(quoted diff) +1 -0
+	if (!hashmap__find(&aslr->remap_addresses, &key, &remap_addr)) {

Will storing and retrieving 64-bit addresses in this hashmap cause truncation or build failures on 32-bit architectures?

The underlying hashmap API stores long values. On 32-bit systems, long is 32 bits wide, which might truncate the upper 32 bits of the remapped address during hashmap__add.

Additionally, passing a u64 pointer to hashmap__find triggers hashmap_cast_ptr(), which contains a static assertion that the value size equals sizeof(long). Might this result in a build failure when compiling on 32-bit platforms?

[ ... ]

Quoted 5 lines
(quoted diff) +5 -0
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{

[ ... ]

Quoted 5 lines
(quoted diff) +5 -0
+	thread = machine__findnew_thread(&aslr->machine, event->mmap.pid, event->mmap.tid);
+	memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap.start, event->mmap.len);

[ ... ]

Review

Quoted 2 lines
(quoted diff) +2 -0
+	return delegate->mmap(delegate, new_event, sample, machine);
+}

Since machine__findnew_thread() increments the reference count of the returned thread, could returning from this function without calling thread__put() leak the thread reference for every processed event?

This pattern appears to be repeated in aslr_tool__process_mmap2, aslr_tool__process_ksymbol, aslr_tool__process_text_poke, and aslr_tool__process_sample.

[ ... ]

Review

Quoted 8 lines
(quoted diff) +8 -0
+static inline int copy_u64(__u64 *in_array, __u64 *out_array,
+			   size_t *i, size_t *j, const __u64 max_i)
+{
+	if (*i > max_i)
+		return -EFAULT;
+	out_array[(*j)++] = in_array[(*i)++];
+	return 0;
+}

Does this bounds check allow reading past the end of the input event buffer?

The max_i value is calculated as event->header.size / sizeof(__u64). Since in_array points to event->sample.array[0], which starts after the 8-byte perf_event_header, the array contains max_i - 1 elements.

Should the check be if (*i >= max_i - 1) instead?

[ ... ]

Quoted 4 lines
(quoted diff) +4 -0
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{

[ ... ]

Quoted 20 lines
(quoted diff) +20 -0
+	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
+		if (copy_u64(in_array, out_array, &i, &j, max_i))
+			return -EFAULT; // nr
+
+		for (u64 cntr = 0; cntr < sample->callchain->nr; cntr++) {
+			if (i > max_i)
+				return -EFAULT;
+			i++;
+			addr = sample->callchain->ips[cntr];
+			if (addr >= PERF_CONTEXT_MAX) {
+				// Copy context values as is.
+				out_array[j++] = addr;
+				switch (addr) {
+				case PERF_CONTEXT_HV:
+					cpumode = PERF_RECORD_MISC_HYPERVISOR;
+					break;
+				case PERF_CONTEXT_KERNEL:
+					cpumode = PERF_RECORD_MISC_KERNEL;
+					break;
+				case PERF_CONTEXT_USER:

Review

Quoted 10 lines
(quoted diff) +10 -0
+					cpumode = PERF_RECORD_MISC_USER;
+					break;
+				default:
+					pr_debug("invalid callchain context: %"PRIx64"\n", addr);
+					/*
+					 * It seems the callchain is corrupted.
+					 * Discard sample.
+					 */
+					return 0;
+				}

Should the switch statement handle other valid context markers like PERF_CONTEXT_GUEST, PERF_CONTEXT_GUEST_KERNEL, PERF_CONTEXT_GUEST_USER, and PERF_CONTEXT_USER_DEFERRED?

Falling into the default block here abruptly discards the sample, which might break profiling workflows involving KVM guests.

[ ... ]

Review

Quoted 8 lines
(quoted diff) +8 -0
+	if (sample_type & PERF_SAMPLE_RAW) {
+		size_t bytes = sizeof(u32) + sample->raw_size;
+
+		if ((i + (bytes / sizeof(u64))) > max_i)
+			return -EFAULT;
+		memcpy(&out_array[j], &in_array[i], bytes);
+		i += bytes / sizeof(u64);
+		j += bytes / sizeof(u64);

Will the integer division truncate the padding bytes if the raw sample size is not perfectly aligned to an 8-byte boundary?

Because the kernel pads raw sample payloads to an 8-byte boundary, truncation might cause i and j to fail to advance past the padding.

Could this lead to the tool misinterpreting the padding bytes as the next fields in the sample, and also leave uninitialized heap memory from aslr->event_copy in the output?

[ ... ]

Review

Quoted 6 lines
(quoted diff) +6 -0
+	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
+		if (copy_u64(in_array, out_array, &i, &j, max_i))
+			return -EFAULT; // nr
+		if (sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)
+			if (copy_u64(in_array, out_array, &i, &j, max_i))
+				return -EFAULT; // hw_idx

Is this checking the correct bitmask?

The PERF_SAMPLE_BRANCH_HW_INDEX and PERF_SAMPLE_BRANCH_COUNTERS flags belong to the branch_sample_type bitmask, not the sample_type bitmask.

Because the sample_type enum uses those bit values for PERF_SAMPLE_TRANSACTION and PERF_SAMPLE_PHYS_ADDR, could a sample with a transaction or physical address field cause the parser to incorrectly assume the presence of branch hardware indices or counters?

Review

Quoted 2 lines
(quoted diff) +2 -0
+		if (i + (sample->branch_stack->nr * 3) > max_i)
+			return -EFAULT;

Is it possible for sample->branch_stack->nr * 3 to wrap around and bypass this bounds check?

If a crafted perf.data file contains an exceptionally large nr value, the multiplication might overflow and result in a small number. Could this allow the subsequent loop to perform out-of-bounds reads from in_array?

[ ... ]

Quoted 4 lines
(quoted diff) +4 -0
+static int aslr_tool__process_attr(const struct perf_tool *tool,
+				   union perf_event *event,
+				   struct evlist **pevlist)
+{

[ ... ]

Review

Quoted 6 lines
(quoted diff) +6 -0
+	memcpy(&new_event->attr, &event->attr, event->attr.header.size);
+	new_event->attr.attr.bp_addr = 0;  // Conservatively remove addresses.
+	new_event->attr.attr.kprobe_addr = 0;  // Conservatively remove addresses.
+
+	return delegate->attr(delegate, new_event, pevlist);
+}

Could clearing bp_addr and kprobe_addr unintentionally corrupt PMU configurations?

In struct perf_event_attr, bp_addr is an alias for the config1 union field, and kprobe_addr is an alias for config2.

Since many hardware PMU drivers rely on config1 and config2 to store critical event configuration data, could clearing these fields break configurations for non-probe hardware events?

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

PATCH v2 1/2 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

In reply to Ian Rogers

If perf.data files are taken from one machine to another they make leak virtual addresses and so weaken ASLR on the machine they are coming from. Add a '--aslr' option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

Assisted-by Gemini:gemini-3.1-pro-preview
---
 tools/perf/builtin-inject.c |  11 +-
 tools/perf/util/Build       |   1 +
 tools/perf/util/aslr.c      | 816 ++++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |  10 +
 4 files changed, 837 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +10 -1
index f174bc69cec4..fa3a71e23f1b 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -2564,6 +2566,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2575,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,7 +2689,9 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr)
+		tool = aslr_tool__new(&inject.tool);
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
@@ -2789,6 +2796,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +816 -0

816 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#5 lore raw

PATCH v2 2/2 perf test: Add inject ASLR test

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

Assisted-by Gemini:gemini-3.1-pro-preview
---
 tools/perf/tests/shell/inject_aslr.sh | 386 ++++++++++++++++++++++++++
 1 file changed, 386 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +386 -0
new file mode 100755
index 000000000000..951809eecfd4
@@ -0,0 +1,386 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+set -e
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+  trap - EXIT TERM INT
+}
+
+trap_cleanup() {
+  echo "Unexpected signal in ${FUNCNAME[1]}"
+  cleanup
+  exit 1
+}
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '{for(i=1;i<=NF;i++) if($i ~ /noploop\+/) {print $(i-1); exit}}'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.basic.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.basic.XXXXXX)
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.pipe.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.pipe.XXXXXX)
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp /tmp/perf.data.callchain.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.callchain.XXXXXX)
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Also check that the full script output differs (to cover callchains)
+    orig_script=$(perf script -i "${data}" | grep -A 5 noploop | head -n 20)
+    new_script=$(perf script -i "${data2}" | grep -A 5 noploop | head -n 20)
+
+    if [ "$orig_script" = "$new_script" ]; then
+      echo "Callchain ASLR test [Failed - callchain output is identical]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+      rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp /tmp/perf.data.report.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}"
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+  rm -f "${data}" "${data2}" "${data_clean}" "${data}.old" "${data2}.old" "${data_clean}.old"
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp /tmp/perf.data.pipe_report.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.pipe_report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}"
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+  rm -f "${data}" "${data2}" "${data_clean}" "${data}.old" "${data2}.old" "${data_clean}.old"
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp /tmp/perf.data.dropped.XXXXXX)
+  local data2
+  data2=$(mktemp /tmp/perf.data2.dropped.XXXXXX)
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that samples are dropped.
+  samples_count=$(perf script -i "${data2}" | wc -l)
+
+  if [ "$samples_count" -gt 0 ]; then
+    echo "Dropped samples test [Failed - samples were not dropped]"
+    err=1
+  else
+    echo "Dropped samples test [Success]"
+    rm -f "${data}" "${data2}" "${data}.old" "${data2}.old"
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp /tmp/perf.data.kernel.XXXXXX)
+  local kdata2
+  kdata2=$(mktemp /tmp/perf.data2.kernel.XXXXXX)
+  local log_file
+  log_file=$(mktemp /tmp/kernel_record.log.XXXXXX)
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  orig_addr=$(perf script -i "${kdata}" | \
+    awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')
+  new_addr=$(perf script -i "${kdata2}" | \
+    awk '{for(i=1;i<=NF;i++) if($i ~ /^ffff/) {print $i; exit}}')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+    rm -f "${kdata}" "${kdata2}" "${log_file}" "${kdata}.old" "${kdata2}.old"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp /tmp/perf.data.kernel_report.XXXXXX)
+  local kdata2
+  kdata2=$(mktemp /tmp/perf.data2.kernel_report.XXXXXX)
+  local data_clean
+  data_clean=$(mktemp /tmp/perf.data.clean.XXXXXX)
+  local log_file
+  log_file=$(mktemp /tmp/kernel_report_record.log.XXXXXX)
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    rm -f "${kdata}" "${log_file}"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}"
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}"
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        gsub(/0x[0-9a-f]+/, "[addr]", $0); \
+        gsub(/ffff[0-9a-f]+/, "[addr]", $0); \
+        gsub(/0000000000000000/, "[addr]", $0); \
+        print}' "${report1_clean}" > "${report1_norm}"
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        gsub(/0x[0-9a-f]+/, "[addr]", $0); \
+        gsub(/ffff[0-9a-f]+/, "[addr]", $0); \
+        gsub(/0000000000000000/, "[addr]", $0); \
+        print}' "${report2_clean}" > "${report2_norm}"
+
+  # Calculate sum of percentages for [kernel] samples
+  sum1=$(awk '/\[kernel\]/ {sum += $1} END {print sum}' "${report1_norm}")
+  sum2=$(awk '/\[kernel\]/ {sum += $1} END {print sum}' "${report2_norm}")
+
+  echo "Kernel report sums: sum1=$sum1, sum2=$sum2"
+
+  # Compare sums with tolerance
+  if awk -v s1="$sum1" -v s2="$sum2" \
+    'BEGIN {diff = s1 - s2; if (diff < 0) diff = -diff; if (diff < 0.05) exit 0; else exit 1}'; then
+    echo "Kernel Report ASLR test [Success]"
+  else
+    echo "Kernel Report ASLR test [Failed - sums differ too much]"
+    err=1
+  fi
+
+  rm -f "${kdata}" "${kdata2}" "${data_clean}" "${log_file}" \
+        "${kdata}.old" "${kdata2}.old" "${data_clean}.old"
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#6 lore raw

v3 cover perf tools: Add inject --aslr feature and prerequisite robustness fixes

In reply to Ian Rogers

This patch series introduces the new 'perf inject --aslr' feature to remap virtual memory addresses or drop physical memory event leaks when profile record data is shared between machines. Bundled with this feature are two independent, critical bug fixes inside core event dispatching tools that harden perf session analysis against dynamic crashes and callchain mapping failures.

--- Core Feature: 'perf inject --aslr' (Patches 3 and 4)

Transferring perf.data files across environments introduces a potential leak of virtual address footprints, weakening Address Space Layout Randomization (ASLR) on the originating machine. To mitigate this, we introduce the --aslr flag into perf inject. Unknown or unhandled events are dropped conservatively, while handled samples and branch loops undergo systematic virtual memory offset obfuscation.

To ensure comprehensive memory and error-path safety, the ASLR tool implements:
- Machine namespaces ('struct machines') to safely interleave host mappings and unprivileged guest (KVM) memory regions without boundary leakages.
- Multi-map anchor key matching ( anchored by DSO, invariant offsets, and PID) resolving overlapping split-map lookups.
- Subtraction-based bounds check equations to mathematically secure branch stack loops against integer overflows.
- Secure u64 dynamic buffer calculations on userspace stack and hardware tracing payloads to prevent wrap-around heap overflows.
- Clean, error-checked skip advancement loops (skipn) past dynamic AUX streams in piped records to maintain stream reader sync.
- Robust OOM fallback rollbacks of transient dictionary keys to guarantee dictionary hashmap integrity on failures.

Verification is reinforced in Patch 4 with a new comprehensive POSIX shell suite ('inject_aslr.sh'), hardened against SIGPIPE signal exits with stream consuming awk loops and robust 'set -o pipefail' assertions.

--- Prerequisite Bug Fixes (Patches 1 and 2)

During development, two core event delegation issues were identified and resolved to prevent crashes and data-loss during analysis:

1. perf sched: 'timehist' registers standard MMAP, COMM, EXIT, and FORK stubs, but completely omitted registering MMAP2 callbacks. Because modern environments output maps primarily via MMAP2 frames, this caused timehist sessions to silently drop shared library mappings, causing dynamic callchain symbol resolutions to fail. Patch 1 corrects this by properly registering perf_event__process_mmap2.

2. perf tool: Patch 2 fixes missing copies of schedstat callbacks inside delegated wrapper tools (which caused segfaults on NULL stubs) and properly initializes/copies the 'dont_split_sample_group' grouping parameters to prevent stack garbage from triggering silent non-leader events drops during split deliver streams.

Ian Rogers (4):
perf sched: Add missing mmap2 handler in timehist
perf tool: Fix missing schedstat delegates and dont_split_sample_group
in delegate_tool
perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses perf test: Add inject ASLR test

 tools/perf/builtin-inject.c           |   18 +-
 tools/perf/builtin-sched.c            |    1 +
 tools/perf/tests/shell/inject_aslr.sh |  423 +++++++++
 tools/perf/util/Build                 |    1 +
 tools/perf/util/aslr.c                | 1157 +++++++++++++++++++++++++
 tools/perf/util/aslr.h                |   10 +
 tools/perf/util/tool.c                |    6 +
 7 files changed, 1615 insertions(+), 1 deletion(-)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#7 lore raw

PATCH v3 1/4 perf sched: Add missing mmap2 handler in timehist

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 5bbfec0ad93c ("perf sched: Implement timehist option")
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -0
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
 	 */
 	sched->tool.sample	 = perf_timehist__process_sample;
 	sched->tool.mmap	 = perf_event__process_mmap;
+	sched->tool.mmap2	 = perf_event__process_mmap2;
 	sched->tool.comm	 = perf_event__process_comm;
 	sched->tool.exit	 = perf_event__process_exit;
 	sched->tool.fork	 = perf_event__process_fork;
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#8 lore raw

PATCH v3 2/4 perf tool: Fix missing schedstat delegates and dont_split_sample_group in delegate_tool

In reply to Ian Rogers

delegate_tool was missing the delegate overrides for schedstat_cpu and schedstat_domain. As a result, when allocated with zalloc, these callbacks defaulted to NULL, causing a segmentation fault crash if any schedstat events were delivered during event processing. Fix this by adding delegate_schedstat_cpu and delegate_schedstat_domain via the CREATE_DELEGATE_OP2 macro, and ensuring delegate_tool__init correctly registers them.

Additionally, delegate_tool__init completely omitted copying the dont_split_sample_group property from the delegate. This would cause wrapper tools to default the flag to false, which corrupts piped event processing (e.g., in perf inject) by triggering duplicate event deliveries on split sample values in deliver_sample_group().

Similarly, perf_tool__init() omitted the initialization of this boolean field. On stack-allocated tools that rely on this initializer (like intel-tpebs or __cmd_evlist), this could result in uninitialized stack garbage evaluating to true—silently dropping non-leader event members in deliver_sample_group().

Fix both issues by properly copying the field in delegate_tool__init and initializing it to false in perf_tool__init.

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 6331b2669359 ("perf tool: Add a delegate_tool that just delegates actions to another tool")
Fixes 79bcd34e0f3d ("perf inject: Fix leader sampling inserting additional samples")
---
 tools/perf/util/tool.c | 6 ++++++
 1 file changed, 6 insertions(+)
tools/perf/util/tool.c +6 -0
index 013c7839e2cf..ff2150517b75 100644
@@ -285,6 +285,7 @@ void perf_tool__init(struct perf_tool *tool, bool ordered_events)
 	tool->no_warn = false;
 	tool->show_feat_hdr = SHOW_FEAT_NO_HEADER;
 	tool->merge_deferred_callchains = true;
+	tool->dont_split_sample_group = false;
 
 	tool->sample = process_event_sample_stub;
 	tool->mmap = process_event_stub;
@@ -433,6 +434,8 @@ CREATE_DELEGATE_OP2(stat_config);
 CREATE_DELEGATE_OP2(stat_round);
 CREATE_DELEGATE_OP2(thread_map);
 CREATE_DELEGATE_OP2(time_conv);
+CREATE_DELEGATE_OP2(schedstat_cpu);
+CREATE_DELEGATE_OP2(schedstat_domain);
 CREATE_DELEGATE_OP2(tracing_data);
 
 #define CREATE_DELEGATE_OP3(name)					\
@@ -470,6 +473,7 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.no_warn = delegate->no_warn;
 	tool->tool.show_feat_hdr = delegate->show_feat_hdr;
 	tool->tool.merge_deferred_callchains = delegate->merge_deferred_callchains;
+	tool->tool.dont_split_sample_group = delegate->dont_split_sample_group;
 
 	tool->tool.sample = delegate_sample;
 	tool->tool.read = delegate_read;
@@ -516,4 +520,6 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.bpf_metadata = delegate_bpf_metadata;
 	tool->tool.compressed = delegate_compressed;
 	tool->tool.auxtrace = delegate_auxtrace;
+	tool->tool.schedstat_cpu = delegate_schedstat_cpu;
+	tool->tool.schedstat_domain = delegate_schedstat_domain;
 }
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#9 lore raw

PATCH v3 3/4 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

In reply to Ian Rogers

If perf.data files are taken from one machine to another they make leak virtual addresses and so weaken ASLR on the machine they are coming from. Add a '--aslr' option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

To ensure comprehensive robustness and security, this tool:
- Employs guest namespace isolation by utilizing 'struct machines' to safely interleave host and unprivileged KVM guest virtual address mappings.
- Resolves VMA split map failures (caused by maps__fixup_overlap_and_insert) consistently by anchoring mappings on DSO and memory invariants.
- Guards against integer overflows in branch stack loops via subtraction-based bounds arithmetic.
- Prevents heap buffer overflows by computing safe word limits on userspace stacks and dynamic hardware tracing (AUX) sizes.
- Prevents key collisions/ABA lookups by correctly managing DSO reference counts (dso__get/put).
- Cleans up error paths to avoid inconsistent hashmap mappings on OOM failures.
- Optimizes performance by removing redundant hot-path memory allocations.
- Cleanly advances session readers past dropped auxtrace streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v3: Combine split-map fixes, guest namespaces, bounds checks, OOM rollbacks,
hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.
v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   18 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1157 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1185 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +17 -1
index f174bc69cec4..6e6bf6b67956 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -2564,6 +2566,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2575,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,12 +2689,21 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
@@ -2789,6 +2803,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +1157 -0

1,157 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#10 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Breakpoint addresses (bp_addr) are not scrubbed when processing regular perf.data files or…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Breakpoint addresses (bp_addr) are not scrubbed when processing regular perf.data files or synthesizing for a pipe, defeating the ASLR protection.
- [High] The --aslr option defeats kernel ASLR obfuscation by deterministically encoding the original kernel start address into the emitted mmap.pgoff field.
- [Medium] The skipn function does not handle EINTR when reading from a pipe, which can cause spurious tool aborts.
--

commit e61cd92f35f2e374d97add5939b1983c327eae98
Author: Ian Rogers <[email protected]>

perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

This commit adds an --aslr option to perf inject to remap virtual addresses in perf.data files. This prevents virtual addresses from leaking when transferring perf data between machines, thus weakening ASLR. Unhandled events are dropped to conservatively avoid leaking ASLR information.

Quoted 4 lines
tools/perf/builtin-inject.c +0 -0
index f174bc69cec4..6e6bf6b67956 100644

[ ... ]

tools/perf/builtin-inject.c int cmd_inject(int argc, const char **argv) · line 2786

Quoted 11 lines
tools/perf/builtin-inject.c +0 -0
@@ -2763,12 +2777,12 @@ int cmd_inject(int argc, const char **argv)
 		/*
 		 * If the input is already a pipe then the features and
 		 * attributes don't need synthesizing, they will be present in
 		 * the input.
 		 */
 		if (!data.is_pipe) {
 			ret = perf_event__synthesize_for_pipe(&inject.tool,
 							      inject.session,
 							      &inject.output,
 							      perf_event__repipe);

Does this bypass the ASLR tool wrapper for ATTR events and leave breakpoint addresses unscrubbed?

The aslr_tool__process_attr() function zeros out bp_addr, but this callback only intercepts ATTR events in the main event stream. If the output is a pipe, perf_event__synthesize_for_pipe() uses perf_event__repipe directly, bypassing the scrubbing and exposing the original bp_addr in the output stream.

When processing regular input files, ATTR configurations are parsed from the file header and stored in session->evlist. Does perf_session__inject_header() write this un-scrubbed evlist directly into the output file's header, also leaking the original bp_addr?

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +0 -0
new file mode 100644
index 000000000000..32548352e1e5

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+static int skipn(int fd, u64 n)
+{
+	char buf[4096];
+	ssize_t ret;

tools/perf/util/aslr.c line 36

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+
+	while (n > 0) {
+		ret = read(fd, buf, (n < (u64)sizeof(buf) ? n : (u64)sizeof(buf)));
+		if (ret <= 0)
+			return ret;
+		n -= ret;
+	}
+
+	return 0;
+}

Can this cause spurious tool aborts if read() is interrupted by a signal (like SIGWINCH)?

This function explicitly checks if ret <= 0 and returns it without checking for EINTR, which allows the error to propagate back to the event processing loop and prematurely abort the perf inject session.

Should this utilize readn() or preadn() from the perf library which correctly handle EINTR?

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{

[ ... ]

tools/perf/util/aslr.c line 448

Quoted 12 lines
tools/perf/util/aslr.c new file +12 -0
+	/* Remaps the mmap.start. */
+	new_event->mmap.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap.start,
+							   event->mmap.len,
+							   event->mmap.pgoff);
+	if (aslr->first_kernel_mapping && cpumode == PERF_RECORD_MISC_KERNEL) {
+		/*
+		 * If this is the first kernel image, we need to adjust the pgoff by a
+		 * similar delta.
+		 */
+		new_event->mmap.pgoff = event->mmap.pgoff - event->mmap.start +
+					new_event->mmap.start;

Does this adjustment of pgoff allow recovering the original kernel ASLR base?

Since event->mmap.pgoff is typically a known public constant for the first kernel image mapping (e.g., 0 or a fixed ELF offset), and the output trace exposes both new_event->mmap.start and new_event->mmap.pgoff, could an attacker trivially reverse the equation:

old_start = new_start - new_pgoff + old_pgoff

Does this mathematical leak nullify the ASLR obfuscation intended for the kernel image?

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

PATCH v3 4/4 perf test: Add inject ASLR test

In reply to Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with:
- Global 'set -o pipefail' pipeline checks to catch failures in perf script.
- Safe awk processing loop closures that consume whole streams to avoid SIGPIPE signal aborts.
- False success assertions to verify callchain data isn't dynamically dropped.
- Graceful error paths on empty sample records.
- Multi-arch support (32-bit and 64-bit address normalizations).

Assisted-by Gemini-CLI:Google Gemini 3

---
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Ensure grep report filters have || true suffixes. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
 tools/perf/tests/shell/inject_aslr.sh | 423 ++++++++++++++++++++++++++
 1 file changed, 423 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +423 -0
new file mode 100755
index 000000000000..fa7dd3b4c411
@@ -0,0 +1,423 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report1_clean}" > "${report1_norm}"
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report2_clean}" > "${report2_norm}"
+
+  # Calculate sum of percentages for [kernel] samples
+  sum1=$(awk '/\[kernel\]/ {sum += $1} END {print sum}' "${report1_norm}")
+  sum2=$(awk '/\[kernel\]/ {sum += $1} END {print sum}' "${report2_norm}")
+
+  echo "Kernel report sums: sum1=$sum1, sum2=$sum2"
+
+  # Compare sums with tolerance
+  if [ -z "$sum1" ] || [ -z "$sum2" ]; then
+    echo "Kernel Report ASLR test [Failed - no kernel data]"
+    err=1
+  elif awk -v s1="$sum1" -v s2="$sum2" \
+    'BEGIN {diff = s1 - s2; if (diff < 0) diff = -diff; if (diff < 0.05) exit 0; else exit 1}'; then
+    echo "Kernel Report ASLR test [Success]"
+  else
+    echo "Kernel Report ASLR test [Failed - sums differ too much]"
+    err=1
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#12 lore raw

Re: [PATCH v3 4/4] perf test: Add inject ASLR test

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The claimed multi-arch address normalization feature is not implemented. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The claimed multi-arch address normalization feature is not implemented. --

commit 7330768f7ec5b4d1676ce71056c223b55aff876e
Author: Ian Rogers <[email protected]>

perf test: Add inject ASLR test

This commit adds a new shell test inject_aslr.sh to verify the perf inject --aslr feature. It covers various remapping scenarios, pipe modes, callchains, and report consistency checks.

Quoted 7 lines

The test suite is hardened with:
- Global 'set -o pipefail' pipeline checks to catch failures in perf script.
- Safe awk processing loop closures that consume whole streams to avoid SIGPIPE signal aborts.
- False success assertions to verify callchain data isn't dynamically dropped.
- Graceful error paths on empty sample records.
- Multi-arch support (32-bit and 64-bit address normalizations).

The commit message mentions multi-arch support and 32-bit and 64-bit address normalizations, but it appears the script only normalizes the DSO names.

[ ... ]

Quoted 5 lines
tools/perf/tests/shell/inject_aslr.sh new file +0 -0
new file mode 100755
index 000000000000..fa7dd3b4c411

[ ... ]

Quoted 1 line

+test_kernel_report_aslr() {

[ ... ]

tools/perf/tests/shell/inject_aslr.sh line 392

Quoted 13 lines
tools/perf/tests/shell/inject_aslr.sh new file +13 -0
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report1_clean}" > "${report1_norm}"
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report2_clean}" > "${report2_norm}"

Does this awk script normalize memory addresses, or does it only normalize the DSO names?

The code seems to avoid address-related diff failures by summing the percentage column later, rather than normalizing the addresses themselves.

Could the commit message and the inline comment be updated to accurately describe what the script actually normalizes?

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

v4 cover perf tools: Add inject --aslr feature and prerequisite robustness fixes

In reply to Ian Rogers

This patch series introduces the new 'perf inject --aslr' feature to remap virtual memory addresses or drop physical memory event leaks when profile record data is shared between machines. Bundled with this feature are two independent, critical bug fixes inside core event dispatching tools that harden perf session analysis against dynamic crashes and callchain mapping failures.

Core Feature: 'perf inject --aslr' (Patches 3 and 4)

Transferring perf.data files across environments introduces a potential leak of virtual address footprints, weakening Address Space Layout Randomization (ASLR) on the originating machine. To mitigate this, we introduce the --aslr flag into perf inject. Unknown or unhandled events are dropped conservatively, while handled samples and branch loops undergo systematic virtual memory offset obfuscation.

To ensure comprehensive memory and error-path safety, the ASLR tool implements:
- Machine namespaces ('struct machines') to safely interleave host mappings and unprivileged KVM guest virtual address mappings.
- Resolves VMA split map failures (caused by overlap fixups during map insertions) consistently by anchoring mappings on DSO and memory invariants.
- Guards against integer overflows in branch stack loops via subtraction-based bounds arithmetic.
- Prevents heap buffer overflows by computing safe word limits on userspace stacks and dynamic hardware tracing (AUX) sizes.
- Prevents key collisions/ABA lookups by correctly managing DSO reference counts (dso__get/put).
- Cleans up error paths to avoid inconsistent hashmap mappings on OOM failures.
- Optimizes performance by removing redundant hot-path memory allocations.
- Cleanly advances session readers past dropped auxtrace streams using pipe-stream I/O skip helpers.
- Scrubs breakpoint addresses (bp_addr) from output event headers and dynamically synthesized events for pipes via a custom pipe repipe wrapper to prevent unscrubbed address leakage.
- Remaps kernel memory maps linearly to maintain secure base obfuscation bounds.
- Hardens guest cpumode lookups against corrupting host/guest user and kernel mapping boundaries during sample fallback searches.
- Synchronizes ksymbol map tracking invariants using precise VMA offset math rather than raw addresses to prevent unique base leaks on every function symbol.
- Blocks trailing heap padding byte data leakage vectors in userspace stacks and AUX tracking frames via targeted tail-word clearing.

Verification is reinforced in Patch 4 with a new comprehensive POSIX shell suite ('inject_aslr.sh'), hardened against SIGPIPE signal exits with stream consuming awk loops and robust 'set -o pipefail' assertions. The suite includes a new dedicated scenario validating pipe stdout injection attribute stability.

Prerequisite Bug Fixes (Patches 1 and 2)

During development, two core event delegation issues were identified and resolved to prevent crashes and data-loss during analysis:

1. perf sched: 'timehist' registers standard MMAP, COMM, EXIT, and FORK stubs, but completely omitted registering MMAP2 callbacks. Because modern environments output maps primarily via MMAP2 frames, this caused timehist sessions to silently drop shared library mappings, causing dynamic callchain symbol resolutions to fail. Patch 1 corrects this by properly registering perf_event__process_mmap2.

2. perf tool: Patch 2 fixes missing copies of schedstat callbacks inside delegated wrapper tools (which caused segfaults on NULL stubs) and properly initializes/copies the 'dont_split_sample_group' grouping parameters to prevent stack garbage from triggering silent non-leader events drops during split deliver streams.

Changes since v3:
- Feature integration: Pass a dedicated 'perf_event__aslr_repipe' callback to perf_event__synthesize_for_pipe() to scrub synthesized breakpoint attributes.
- Feature core: Loop through and scrub event evlist breakpoint attributes right before writing file headers in __cmd_inject().
- Feature core: Linearize kernel map base obfuscation and remove redundant pgoff delta adjustments that leaked kernel layout calculations.
- Feature core: Fix host/guest cpumode mappings in sample fallback lookups.
- Feature core: Sync ksymbol tracking keys onto VMA offset invariants.
- Feature core: Zero out trailing padding word bytes in user stacks and AUX blocks.
- Validation suite: Add 'test_pipe_out_report_aslr' validation case.
- Validation suite: Upgrade kernel report checks to strict sorted line-by-line diffs.
- Style: Wrap all commit description lines to under 75 columns and fix code formatting.

Ian Rogers (4):
perf sched: Add missing mmap2 handler in timehist
perf tool: Fix missing schedstat delegates and dont_split_sample_group
in delegate_tool
perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses perf test: Add inject ASLR test

 tools/perf/builtin-inject.c           |   52 +-
 tools/perf/builtin-sched.c            |    1 +
 tools/perf/tests/shell/inject_aslr.sh |  459 ++++++++++
 tools/perf/util/Build                 |    1 +
 tools/perf/util/aslr.c                | 1161 +++++++++++++++++++++++++
 tools/perf/util/aslr.h                |   10 +
 tools/perf/util/tool.c                |    6 +
 7 files changed, 1689 insertions(+), 1 deletion(-)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#14 lore raw

PATCH v4 1/4 perf sched: Add missing mmap2 handler in timehist

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 5bbfec0ad93c ("perf sched: Implement timehist option")
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -0
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
 	 */
 	sched->tool.sample	 = perf_timehist__process_sample;
 	sched->tool.mmap	 = perf_event__process_mmap;
+	sched->tool.mmap2	 = perf_event__process_mmap2;
 	sched->tool.comm	 = perf_event__process_comm;
 	sched->tool.exit	 = perf_event__process_exit;
 	sched->tool.fork	 = perf_event__process_fork;
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#15 lore raw

PATCH v4 2/4 perf tool: Fix missing schedstat delegates and dont_split_sample_group in delegate_tool

In reply to Ian Rogers

delegate_tool was missing the delegate overrides for schedstat_cpu and schedstat_domain. As a result, when allocated with zalloc, these callbacks defaulted to NULL, causing a segmentation fault crash if any schedstat events were delivered during event processing. Fix this by adding delegate_schedstat_cpu and delegate_schedstat_domain via the CREATE_DELEGATE_OP2 macro, and ensuring delegate_tool__init correctly registers them.

Additionally, delegate_tool__init completely omitted copying the dont_split_sample_group property from the delegate. This would cause wrapper tools to default the flag to false, which corrupts piped event processing (e.g., in perf inject) by triggering duplicate event deliveries on split sample values in deliver_sample_group().

Similarly, perf_tool__init() omitted the initialization of this boolean field. On stack-allocated tools that rely on this initializer (like intel-tpebs or __cmd_evlist), this could result in uninitialized stack garbage evaluating to true—silently dropping non-leader event members in deliver_sample_group().

Fix both issues by properly copying the field in delegate_tool__init and initializing it to false in perf_tool__init.

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 6331b2669359 ("perf tool: Add a delegate_tool that just delegates actions to another tool")
Fixes 79bcd34e0f3d ("perf inject: Fix leader sampling inserting additional samples")
---
 tools/perf/util/tool.c | 6 ++++++
 1 file changed, 6 insertions(+)
tools/perf/util/tool.c +6 -0
index 013c7839e2cf..ff2150517b75 100644
@@ -285,6 +285,7 @@ void perf_tool__init(struct perf_tool *tool, bool ordered_events)
 	tool->no_warn = false;
 	tool->show_feat_hdr = SHOW_FEAT_NO_HEADER;
 	tool->merge_deferred_callchains = true;
+	tool->dont_split_sample_group = false;
 
 	tool->sample = process_event_sample_stub;
 	tool->mmap = process_event_stub;
@@ -433,6 +434,8 @@ CREATE_DELEGATE_OP2(stat_config);
 CREATE_DELEGATE_OP2(stat_round);
 CREATE_DELEGATE_OP2(thread_map);
 CREATE_DELEGATE_OP2(time_conv);
+CREATE_DELEGATE_OP2(schedstat_cpu);
+CREATE_DELEGATE_OP2(schedstat_domain);
 CREATE_DELEGATE_OP2(tracing_data);
 
 #define CREATE_DELEGATE_OP3(name)					\
@@ -470,6 +473,7 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.no_warn = delegate->no_warn;
 	tool->tool.show_feat_hdr = delegate->show_feat_hdr;
 	tool->tool.merge_deferred_callchains = delegate->merge_deferred_callchains;
+	tool->tool.dont_split_sample_group = delegate->dont_split_sample_group;
 
 	tool->tool.sample = delegate_sample;
 	tool->tool.read = delegate_read;
@@ -516,4 +520,6 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.bpf_metadata = delegate_bpf_metadata;
 	tool->tool.compressed = delegate_compressed;
 	tool->tool.auxtrace = delegate_auxtrace;
+	tool->tool.schedstat_cpu = delegate_schedstat_cpu;
+	tool->tool.schedstat_domain = delegate_schedstat_domain;
 }
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#16 lore raw

PATCH v4 3/4 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

In reply to Ian Rogers

If perf.data files are taken from one machine to another they make leak virtual addresses and so weaken ASLR on the machine they are coming from. Add a '--aslr' option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

To ensure comprehensive robustness and security, this tool:
- Employs guest namespace isolation by utilizing 'struct machines' to safely interleave host and unprivileged KVM guest virtual address mappings.
- Resolves VMA split map failures (caused by overlap fixups during map insertions) consistently by anchoring mappings on DSO and memory invariants.
- Guards against integer overflows in branch stack loops via subtraction-based bounds arithmetic.
- Prevents heap buffer overflows by computing safe word limits on userspace stacks and dynamic hardware tracing (AUX) sizes.
- Prevents key collisions/ABA lookups by correctly managing DSO reference counts (dso__get/put).
- Cleans up error paths to avoid inconsistent hashmap mappings on OOM failures.
- Optimizes performance by removing redundant hot-path memory allocations.
- Cleanly advances session readers past dropped auxtrace streams using pipe-stream I/O skip helpers.
- Scrubs breakpoint addresses (bp_addr) from output event headers and dynamically synthesized events for pipes via a custom pipe repipe wrapper to prevent unscrubbed address leakage.
- Remaps kernel memory maps linearly to maintain secure base obfuscation bounds.
- Hardens guest cpumode lookups against corrupting host/guest user and kernel mapping boundaries during sample fallback searches.
- Synchronizes ksymbol map tracking invariants using precise VMA offset math rather than raw addresses to prevent unique base leaks on every function symbol.
- Blocks trailing heap padding byte data leakage vectors in userspace stacks and AUX tracking frames via targeted tail-word clearing.

Assisted-by Gemini-CLI:Google Gemini 3

---
v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove kernel
mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.
v3: Combine split-map fixes, guest namespaces, bounds checks, OOM rollbacks,
hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.
v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   52 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1161 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1223 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +51 -1
index f174bc69cec4..d2167a94d4be 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -304,6 +306,29 @@ static int perf_event__repipe(const struct perf_tool *tool,
 	return perf_event__repipe_synth(tool, event);
 }
 
+/**
+ * perf_event__aslr_repipe - Wrapper to scrub synthesized pipe attributes.
+ * @tool: The original &inject.tool pointer.
+ * @event: The synthesized perf_event record.
+ *
+ * Synthesized attributes for pipes bypass the main event stream tool hooks.
+ * This wrapper intercepts them during pipe header generation to clear unprivileged
+ * breakpoint addresses (bp_addr). It forwards execution using the original tool
+ * context pointer to ensure container_of(&inject.tool) evaluation inside the
+ * downstream repipe stubs remains valid and does not cause structure corruptions.
+ */
+static int perf_event__aslr_repipe(const struct perf_tool *tool,
+				   union perf_event *event,
+				   struct perf_sample *sample,
+				   struct machine *machine)
+{
+	if (event->header.type == PERF_RECORD_HEADER_ATTR &&
+	    event->attr.attr.type == PERF_TYPE_BREAKPOINT) {
+		event->attr.attr.bp_addr = 0;
+	}
+	return perf_event__repipe(tool, event, sample, machine);
+}
+
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
 			    union perf_event *event __maybe_unused,
 			    struct perf_sample *sample __maybe_unused,
@@ -2458,6 +2483,15 @@ static int __cmd_inject(struct perf_inject *inject)
 			}
 		}
 
+		if (inject->aslr) {
+			struct evsel *evsel;
+
+			evlist__for_each_entry(session->evlist, evsel) {
+				if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+					evsel->core.attr.bp_addr = 0;
+			}
+		}
+
 		session->header.data_offset = output_data_offset;
 		session->header.data_size = inject->bytes_written;
 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2564,6 +2598,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2607,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,12 +2721,21 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
@@ -2717,6 +2763,8 @@ int cmd_inject(int argc, const char **argv)
 			ret = perf_event__synthesize_for_pipe(&inject.tool,
 							      inject.session,
 							      &inject.output,
+							      inject.aslr ?
+							      perf_event__aslr_repipe :
 							      perf_event__repipe);
 			if (ret < 0)
 				goto out_delete;
@@ -2789,6 +2837,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +1161 -0

1,161 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#17 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Kernel ASLR base is leaked through unmodified mmap `pgoff` fields. - [Medium] The 'targeted…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Kernel ASLR base is leaked through unmodified mmap pgoff fields.
- [Medium] The 'targeted tail-word clearing' logic for STACK_USER and AUX frames is dead code because the entire sample is unconditionally dropped immediately after.
- [Medium] The skipn() pipe helper lacks retry logic for -EINTR, risking spurious aborts.
--

commit 0794ff7942de3e0dd56f299d7bfb0e61ba3fc97a
Author: Ian Rogers <[email protected]>

perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

This commit introduces an '--aslr' option for perf inject to remap virtual addresses in perf.data files. This prevents leaking virtual addresses and weakening ASLR on the source machine. Events with unknown or unhandled addresses are dropped to remain conservative.

Quoted 6 lines
tools/perf/util/aslr.c new file +0 -0
new file mode 100644
index 000000000000..27b642c91eb9
@@ -0,0 +1,1161 @@

[ ... ]

tools/perf/util/aslr.c line 31

Quoted 9 lines
tools/perf/util/aslr.c new file +9 -0
+static int skipn(int fd, u64 n)
+{
+	char buf[4096];
+	ssize_t ret;
+
+	while (n > 0) {
+		ret = read(fd, buf, (n < (u64)sizeof(buf) ? n : (u64)sizeof(buf)));
+		if (ret <= 0)
+			return ret;

Will this cause spurious aborts if read() is interrupted by a signal?

Since this is reading from a pipe, if read() returns -1 with errno == EINTR, skipn() will return the error immediately rather than retrying.

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+		n -= ret;
+	}
+
+	return 0;
+}

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{

[ ... ]

tools/perf/util/aslr.c line 454

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+	memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap.start,
+							   event->mmap.len,
+							   event->mmap.pgoff);

Does this leak the kernel ASLR base?

For the main kernel mapping, the perf tool synthesizes mmap events where the mmap.pgoff field is set to the original kernel start address. Since pgoff is left unmodified here, the unobfuscated kernel base address will be copied directly into the output stream.

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	err = delegate->mmap(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+static int aslr_tool__process_mmap2(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{

[ ... ]

tools/perf/util/aslr.c line 497

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+	memcpy(&new_event->mmap2, &event->mmap2, event->mmap2.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap2.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap2.start,
+							   event->mmap2.len,
+							   event->mmap2.pgoff);

Similarly, does this leave the unobfuscated kernel base address in pgoff for mmap2 events?

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	err = delegate->mmap2(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{

[ ... ]

Quoted 8 lines
tools/perf/util/aslr.c new file +8 -0
+	if (sample_type & PERF_SAMPLE_STACK_USER) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+

tools/perf/util/aslr.c line 927

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}

Is this tail-word clearing dead code?

tools/perf/util/aslr.c line 936

Quoted 9 lines
tools/perf/util/aslr.c new file +9 -0
+			i += u64_words;
+			j += u64_words;
+
+			COPY_U64(); /* dyn_size */
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping stack user sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;

Immediately after clearing the trailing heap padding in the output array, the code unconditionally jumps to out_put with ret = 0, skipping the sample delegate call. This drops the entire sample from the output stream.

Quoted 1 line
tools/perf/util/aslr.c new file +1 -0
+	}

[ ... ]

Quoted 16 lines
tools/perf/util/aslr.c new file +16 -0
+	if (sample_type & PERF_SAMPLE_AUX) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+

tools/perf/util/aslr.c line 1004

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping aux sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}

Does this code also unnecessarily calculate and clear the tail padding for AUX frames, given that the sample is unconditionally dropped?

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

PATCH v4 4/4 perf test: Add inject ASLR test

In reply to Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with:
- Global 'set -o pipefail' pipeline checks to catch failures in perf script.
- Safe awk processing loop closures that consume whole streams to avoid SIGPIPE signal aborts.
- False success assertions to verify callchain data isn't dynamically dropped.
- Graceful error paths on empty sample records.
- Multi-arch support (32-bit and 64-bit address normalizations).
- Adds a new 'test_pipe_out_report_aslr' pipeline validation scenario testing raw 'perf inject --aslr -o -' pipe stdout generation to verify attribute repipe wrapper stability.

Assisted-by Gemini-CLI:Google Gemini 3

---
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on
unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
 tools/perf/tests/shell/inject_aslr.sh | 459 ++++++++++++++++++++++++++
 1 file changed, 459 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +459 -0
new file mode 100755
index 000000000000..80ec9bf3daf8
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report1_clean}" | sort > "${report1_norm}"
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report2_clean}" | sort > "${report2_norm}"
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#19 lore raw

Re: [PATCH v4 4/4] perf test: Add inject ASLR test

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The test script claims to perform address normalization for kernel reports but fails to…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The test script claims to perform address normalization for kernel reports but fails to implement it in the awk substitution. --

commit 35a72f67733a9ae0ed75cf3ba7c2a7ec0e4419cd
Author: Ian Rogers <[email protected]>

perf test: Add inject ASLR test

This commit adds a new shell test, inject_aslr.sh, to verify the perf inject --aslr feature. It covers various scenarios including basic address remapping, pipe modes, callchains, and kernel address remapping consistency.

Quoted 5 lines
tools/perf/tests/shell/inject_aslr.sh new file +0 -0
new file mode 100755
index 000000000000..80ec9bf3daf8

[ ... ]

Quoted 1 line

+test_kernel_report_aslr() {

[ ... ]

tools/perf/tests/shell/inject_aslr.sh line 431

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report1_clean}" | sort > "${report1_norm}"
+  awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); \
+        print}' "${report2_clean}" | sort > "${report2_norm}"

The commit message mentions "32-bit and 64-bit address normalizations", and the inline comment here specifically states it will normalize addresses.

However, the awk substitution appears to only match and replace the DSO module names.

If unresolved kernel symbols are present in the trace, perf report will output their absolute hexadecimal addresses. Since --aslr shifts these addresses, wouldn't the unnormalized hex strings differ between the original and injected reports?

Could this cause the diff check to fail on environments lacking full kernel symbol resolution, leading to flaky test failures?

Quoted 2 lines
tools/perf/tests/shell/inject_aslr.sh new file +2 -0
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author reviewer
#20 lore raw

Re: [PATCH v4 0/4] perf tools: Add inject --aslr feature and prerequisite robustness fixes

In reply to Ian Rogers

I found a regression when testing as root, so please ignore.

Thanks,
Ian

Quoted 105 lines · Ian Rogers

This patch series introduces the new 'perf inject --aslr' feature to remap virtual memory addresses or drop physical memory event leaks when profile record data is shared between machines. Bundled with this feature are two independent, critical bug fixes inside core event dispatching tools that harden perf session analysis against dynamic crashes and callchain mapping failures.

Core Feature: 'perf inject --aslr' (Patches 3 and 4)

Transferring perf.data files across environments introduces a potential leak of virtual address footprints, weakening Address Space Layout Randomization (ASLR) on the originating machine. To mitigate this, we introduce the --aslr flag into perf inject. Unknown or unhandled events are dropped conservatively, while handled samples and branch loops undergo systematic virtual memory offset obfuscation.

To ensure comprehensive memory and error-path safety, the ASLR tool implements:
- Machine namespaces ('struct machines') to safely interleave host mappings and unprivileged KVM guest virtual address mappings.
- Resolves VMA split map failures (caused by overlap fixups during map insertions) consistently by anchoring mappings on DSO and memory invariants.
- Guards against integer overflows in branch stack loops via subtraction-based bounds arithmetic.
- Prevents heap buffer overflows by computing safe word limits on userspace stacks and dynamic hardware tracing (AUX) sizes.
- Prevents key collisions/ABA lookups by correctly managing DSO reference counts (dso__get/put).
- Cleans up error paths to avoid inconsistent hashmap mappings on OOM failures.
- Optimizes performance by removing redundant hot-path memory allocations.
- Cleanly advances session readers past dropped auxtrace streams using pipe-stream I/O skip helpers.
- Scrubs breakpoint addresses (bp_addr) from output event headers and dynamically synthesized events for pipes via a custom pipe repipe wrapper to prevent unscrubbed address leakage.
- Remaps kernel memory maps linearly to maintain secure base obfuscation bounds.
- Hardens guest cpumode lookups against corrupting host/guest user and kernel mapping boundaries during sample fallback searches.
- Synchronizes ksymbol map tracking invariants using precise VMA offset math rather than raw addresses to prevent unique base leaks on every function symbol.
- Blocks trailing heap padding byte data leakage vectors in userspace stacks and AUX tracking frames via targeted tail-word clearing.

Verification is reinforced in Patch 4 with a new comprehensive POSIX shell suite ('inject_aslr.sh'), hardened against SIGPIPE signal exits with stream consuming awk loops and robust 'set -o pipefail' assertions. The suite includes a new dedicated scenario validating pipe stdout injection attribute stability.

Prerequisite Bug Fixes (Patches 1 and 2)

During development, two core event delegation issues were identified and resolved to prevent crashes and data-loss during analysis:

1. perf sched: 'timehist' registers standard MMAP, COMM, EXIT, and FORK stubs, but completely omitted registering MMAP2 callbacks. Because modern environments output maps primarily via MMAP2 frames, this caused timehist sessions to silently drop shared library mappings, causing dynamic callchain symbol resolutions to fail. Patch 1 corrects this by properly registering perf_event__process_mmap2.

2. perf tool: Patch 2 fixes missing copies of schedstat callbacks inside delegated wrapper tools (which caused segfaults on NULL stubs) and properly initializes/copies the 'dont_split_sample_group' grouping parameters to prevent stack garbage from triggering silent non-leader events drops during split deliver streams.

Changes since v3:
- Feature integration: Pass a dedicated 'perf_event__aslr_repipe' callback to perf_event__synthesize_for_pipe() to scrub synthesized breakpoint attributes.
- Feature core: Loop through and scrub event evlist breakpoint attributes right before writing file headers in __cmd_inject().
- Feature core: Linearize kernel map base obfuscation and remove redundant pgoff delta adjustments that leaked kernel layout calculations.
- Feature core: Fix host/guest cpumode mappings in sample fallback lookups.
- Feature core: Sync ksymbol tracking keys onto VMA offset invariants.
- Feature core: Zero out trailing padding word bytes in user stacks and AUX blocks.
- Validation suite: Add 'test_pipe_out_report_aslr' validation case.
- Validation suite: Upgrade kernel report checks to strict sorted line-by-line diffs.
- Style: Wrap all commit description lines to under 75 columns and fix code formatting.

Ian Rogers (4):
perf sched: Add missing mmap2 handler in timehist
perf tool: Fix missing schedstat delegates and dont_split_sample_group
in delegate_tool
perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses perf test: Add inject ASLR test

 tools/perf/builtin-inject.c           |   52 +-
 tools/perf/builtin-sched.c            |    1 +
 tools/perf/tests/shell/inject_aslr.sh |  459 ++++++++++
 tools/perf/util/Build                 |    1 +
 tools/perf/util/aslr.c                | 1161 +++++++++++++++++++++++++
 tools/perf/util/aslr.h                |   10 +
 tools/perf/util/tool.c                |    6 +
 7 files changed, 1689 insertions(+), 1 deletion(-)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h

--
2.54.0.545.g6539524ca2-goog

author reviewer
#21 lore raw

v5 cover perf tools: Add inject --aslr feature and prerequisite robustness fixes

In reply to Ian Rogers

This patch series introduces the new 'perf inject --aslr' feature to remap virtual memory addresses or drop physical memory event leaks when profile record data is shared between machines. Bundled with this feature are three independent, critical bug fixes inside core event dispatching and map tracking tools that harden perf session analysis against dynamic crashes and callchain mapping failures.

Core Feature: 'perf inject --aslr' (Patches 4 and 5)

Transferring perf.data files across environments introduces a potential leak of virtual address footprints, weakening Address Space Layout Randomization (ASLR) on the originating machine. To mitigate this, we introduce the --aslr flag into perf inject. Unknown or unhandled events are dropped conservatively, while handled samples and branch loops undergo systematic virtual memory offset obfuscation.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory space layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames) to completely eliminate accidental address leakage vectors.

Verification is reinforced in Patch 5 with a comprehensive POSIX shell suite ('inject_aslr.sh'), hardened against SIGPIPE signal exits with stream consuming awk loops and robust 'set -o pipefail' assertions. The suite includes a dedicated scenario validating raw 'perf inject -o -' pipe stdout generation attribute stability.

Prerequisite Bug Fixes (Patches 1, 2, and 3)

During development, three core event delegation and map indexing issues were identified and resolved to prevent crashes and data-loss during analysis:

1. perf sched: 'timehist' registers standard MMAP, COMM, EXIT, and FORK stubs, but completely omitted registering MMAP2 callbacks. Because modern environments output maps primarily via MMAP2 frames, this caused timehist sessions to silently drop shared library mappings, causing dynamic callchain symbol resolutions to fail. Patch 1 corrects this by properly registering perf_event__process_mmap2.

2. perf tool: Patch 2 fixes missing copies of schedstat callbacks inside delegated wrapper tools (which caused segfaults on NULL stubs) and properly initializes/copies the 'dont_split_sample_group' grouping parameters to prevent stack garbage from triggering silent non-leader events drops during split deliver streams.

3. perf symbols: Patch 3 resolves a deep structural map tracking desynchronization bug inside symbol-elf.c by re-engineering the map removal sequence order to run strictly BEFORE in-place virtual address mutations, preventing absolute binary searches (bsearch) from failing on misaligned cache array slots.

Changes since v4:
- Core Bug Fix: Introduce a new prerequisite standalone fix patch (Patch 3) that re-engineers map tracking removal sequence order inside symbol-elf.c to prevent corrupting binary search index arrays during in-place address mutations.
- Feature Core: Refactor aslr_tool__delete to cleanly clear host/guest maps and structures via machines__destroy_kernel_maps() to cure all destructor leaks.
- Feature Core: Integrate the 'first_kernel_mapping' state guard to protect kernel module file offsets (pgoff) from corruption, preventing dynamic symbolization resolutions dropouts.
- Feature Integration: Move breakpoint address (bp_addr) cleaning to the core session memory initialization startup level, natively securing both files and pipes while completely stripping away redundant runtime wrapper layers.
- Validation Suite: Harden grep-v filters with || true operators to protect pipelines from crashing under set -o pipefail on empty inputs.
- Style: Prune out and streamline commit log text clutter into concise high-level architectural summary overviews.

Ian Rogers (5):
perf sched: Add missing mmap2 handler in timehist
perf tool: Fix missing schedstat delegates and dont_split_sample_group
in delegate_tool
perf symbols: Fix map removal sequence inside
dso__process_kernel_symbol()
perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses perf test: Add inject ASLR test

 tools/perf/builtin-inject.c           |   31 +-
 tools/perf/builtin-sched.c            |    1 +
 tools/perf/tests/shell/inject_aslr.sh |  459 ++++++++++
 tools/perf/util/Build                 |    1 +
 tools/perf/util/aslr.c                | 1220 +++++++++++++++++++++++++
 tools/perf/util/aslr.h                |   10 +
 tools/perf/util/symbol-elf.c          |   21 +-
 tools/perf/util/tool.c                |    6 +
 8 files changed, 1743 insertions(+), 6 deletions(-)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#22 lore raw

PATCH v5 1/5 perf sched: Add missing mmap2 handler in timehist

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 5bbfec0ad93c ("perf sched: Implement timehist option")
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -0
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
 	 */
 	sched->tool.sample	 = perf_timehist__process_sample;
 	sched->tool.mmap	 = perf_event__process_mmap;
+	sched->tool.mmap2	 = perf_event__process_mmap2;
 	sched->tool.comm	 = perf_event__process_comm;
 	sched->tool.exit	 = perf_event__process_exit;
 	sched->tool.fork	 = perf_event__process_fork;
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#23 lore raw

Re: [PATCH v5 1/5] perf sched: Add missing mmap2 handler in timehist

Quoted 10 lines · Ian Rogers

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Quoted 5 lines

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 5bbfec0ad93c ("perf sched: Implement timehist option")

I'm picking patches 1 and 2 as they're simple and passed sashiko review, but:

⬢ [acme@toolbx perf-tools-next2]$ git show 5bbfec0ad93c
fatal: ambiguous argument '5bbfec0ad93c': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
⬢ [acme@toolbx perf-tools-next2]$

The right one is:

Fixes 49394a2a24c78ce0 ("perf sched timehist: Introduce timehist command")

I checked and at the time, mmap2 was already present and it missed adding this handler.

I fixed it, in case I'm missing something, lemme know,

- Arnaldo

Quoted 19 lines
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -0
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
 	 */
 	sched->tool.sample	 = perf_timehist__process_sample;
 	sched->tool.mmap	 = perf_event__process_mmap;
+	sched->tool.mmap2	 = perf_event__process_mmap2;
 	sched->tool.comm	 = perf_event__process_comm;
 	sched->tool.exit	 = perf_event__process_exit;
 	sched->tool.fork	 = perf_event__process_fork;
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#24 lore raw

Re: [PATCH v5 1/5] perf sched: Add missing mmap2 handler in timehist

Quoted 27 lines · Arnaldo Carvalho de Melo
Quoted 10 lines · Ian Rogers

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Quoted 5 lines

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 5bbfec0ad93c ("perf sched: Implement timehist option")

I'm picking patches 1 and 2 as they're simple and passed sashiko review, but:

⬢ [acme@toolbx perf-tools-next2]$ git show 5bbfec0ad93c
fatal: ambiguous argument '5bbfec0ad93c': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
⬢ [acme@toolbx perf-tools-next2]$

Quoted 8 lines

The right one is:

Fixes 49394a2a24c78ce0 ("perf sched timehist: Introduce timehist command")

I checked and at the time, mmap2 was already present and it missed adding this handler.

I fixed it, in case I'm missing something, lemme know,

Sounds good. I reworked patch3 because the remove/insert pattern was potentially racy. Now, with the write lock held it mutates the map entry in place and then marks the backing maps as being unsorted. Sashiko reviews made me aware of about four instances of this potential bug. I've also tweaked the ASLR code to make it more robust against colliding host/guest VM PIDs. I'm running sashiko locally and will post the next version when satisfied. For some reason the external Sashiko seems to be catching different issues :-/

Thanks,
Ian

Quoted 21 lines

- Arnaldo

Quoted 19 lines
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -1
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
       */
      sched->tool.sample       = perf_timehist__process_sample;
      sched->tool.mmap         = perf_event__process_mmap;
+     sched->tool.mmap2        = perf_event__process_mmap2;
      sched->tool.comm         = perf_event__process_comm;
      sched->tool.exit         = perf_event__process_exit;
      sched->tool.fork         = perf_event__process_fork;
--

2.54.0.545.g6539524ca2-goog

author reviewer
#25 lore raw

PATCH v5 2/5 perf tool: Fix missing schedstat delegates and dont_split_sample_group in delegate_tool

In reply to Ian Rogers

delegate_tool was missing the delegate overrides for schedstat_cpu and schedstat_domain. As a result, when allocated with zalloc, these callbacks defaulted to NULL, causing a segmentation fault crash if any schedstat events were delivered during event processing. Fix this by adding delegate_schedstat_cpu and delegate_schedstat_domain via the CREATE_DELEGATE_OP2 macro, and ensuring delegate_tool__init correctly registers them.

Additionally, delegate_tool__init completely omitted copying the dont_split_sample_group property from the delegate. This would cause wrapper tools to default the flag to false, which corrupts piped event processing (e.g., in perf inject) by triggering duplicate event deliveries on split sample values in deliver_sample_group().

Similarly, perf_tool__init() omitted the initialization of this boolean field. On stack-allocated tools that rely on this initializer (like intel-tpebs or __cmd_evlist), this could result in uninitialized stack garbage evaluating to true—silently dropping non-leader event members in deliver_sample_group().

Fix both issues by properly copying the field in delegate_tool__init and initializing it to false in perf_tool__init.

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 6331b2669359 ("perf tool: Add a delegate_tool that just delegates actions to another tool")
Fixes 79bcd34e0f3d ("perf inject: Fix leader sampling inserting additional samples")
---
 tools/perf/util/tool.c | 6 ++++++
 1 file changed, 6 insertions(+)
tools/perf/util/tool.c +6 -0
index 013c7839e2cf..ff2150517b75 100644
@@ -285,6 +285,7 @@ void perf_tool__init(struct perf_tool *tool, bool ordered_events)
 	tool->no_warn = false;
 	tool->show_feat_hdr = SHOW_FEAT_NO_HEADER;
 	tool->merge_deferred_callchains = true;
+	tool->dont_split_sample_group = false;
 
 	tool->sample = process_event_sample_stub;
 	tool->mmap = process_event_stub;
@@ -433,6 +434,8 @@ CREATE_DELEGATE_OP2(stat_config);
 CREATE_DELEGATE_OP2(stat_round);
 CREATE_DELEGATE_OP2(thread_map);
 CREATE_DELEGATE_OP2(time_conv);
+CREATE_DELEGATE_OP2(schedstat_cpu);
+CREATE_DELEGATE_OP2(schedstat_domain);
 CREATE_DELEGATE_OP2(tracing_data);
 
 #define CREATE_DELEGATE_OP3(name)					\
@@ -470,6 +473,7 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.no_warn = delegate->no_warn;
 	tool->tool.show_feat_hdr = delegate->show_feat_hdr;
 	tool->tool.merge_deferred_callchains = delegate->merge_deferred_callchains;
+	tool->tool.dont_split_sample_group = delegate->dont_split_sample_group;
 
 	tool->tool.sample = delegate_sample;
 	tool->tool.read = delegate_read;
@@ -516,4 +520,6 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.bpf_metadata = delegate_bpf_metadata;
 	tool->tool.compressed = delegate_compressed;
 	tool->tool.auxtrace = delegate_auxtrace;
+	tool->tool.schedstat_cpu = delegate_schedstat_cpu;
+	tool->tool.schedstat_domain = delegate_schedstat_domain;
 }
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#26 lore raw

PATCH v5 3/5 perf symbols: Fix map removal sequence inside dso__process_kernel_symbol()

In reply to Ian Rogers

When parsing vmlinux ELF binary symbols, dso__process_kernel_symbol() mutates the map's start address key fields in place before executing maps__remove(). This forces maps__by_address_index() to look up the new mutated address range via strict binary search inside an array interval that was ordered using the old unmutated boundaries, leading to a bsearch() mismatch failure and leaking maps index errors.

Fix this natively by executing maps__remove() before mutating the map fields in place, ensuring binary search maps queries always locate and extract target elements flawlessly.

Fixes 39b12f781271 ("perf tools: Make it possible to read object code from vmlinux")
---
 tools/perf/util/symbol-elf.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
tools/perf/util/symbol-elf.c +16 -5
index 7afa8a117139..f31d481a8627 100644
@@ -1372,20 +1372,31 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
 		 */
 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
 			*remap_kernel = false;
-			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
-			map__set_end(map, map__start(map) + shdr->sh_size);
-			map__set_pgoff(map, shdr->sh_offset);
-			map__set_mapping_type(map, MAPPING_TYPE__DSO);
-			/* Ensure maps are correctly ordered */
+			/*
+			 * If the map is tracking inside the kmaps cache list array, we
+			 * MUST remove it before mutating its virtual address key fields
+			 * in place. Otherwise, downstream binary search lookups (bsearch)
+			 * will search for mutated keys inside an array sorted under old
+			 * invariants, causing indexing desynchronization faults.
+			 */
 			if (kmaps) {
 				int err;
 				struct map *tmp = map__get(map);
 
 				maps__remove(kmaps, map);
+				map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
+				map__set_end(map, map__start(map) + shdr->sh_size);
+				map__set_pgoff(map, shdr->sh_offset);
+				map__set_mapping_type(map, MAPPING_TYPE__DSO);
 				err = maps__insert(kmaps, map);
 				map__put(tmp);
 				if (err)
 					return err;
+			} else {
+				map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
+				map__set_end(map, map__start(map) + shdr->sh_size);
+				map__set_pgoff(map, shdr->sh_offset);
+				map__set_mapping_type(map, MAPPING_TYPE__DSO);
 			}
 		}
 
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#27 lore raw

Re: [PATCH v5 3/5] perf symbols: Fix map removal sequence inside dso__process_kernel_symbol()

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Medium] Incomplete implementation missing identical map mutation anti-patterns in the kallsyms loading…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Medium] Incomplete implementation missing identical map mutation anti-patterns in the kallsyms loading path.
- [Medium] Out-of-bounds array access and crash on session teardown if maps__insert() fails.
- [Medium] Lockless window exposes missing kernel map to concurrent worker threads, causing dropped samples. --

commit bf2ae4502d20517901689001acc83f0ec6ca94db
Author: Ian Rogers <[email protected]>

perf symbols: Fix map removal sequence inside dso__process_kernel_symbol()

This commit addresses a binary search indexing issue by ensuring a map is removed from its cache list before mutating its address key fields. After the in-place mutations are complete, the map is re-inserted to preserve the sorting invariants of the underlying array.

Quoted 15 lines
tools/perf/util/symbol-elf.c +2 -5
index 7afa8a1171396..f31d481a8627a 100644
@@ -1372,20 +1372,31 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
 		 */
 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
 			*remap_kernel = false;
-			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
-			map__set_end(map, map__start(map) + shdr->sh_size);
-			map__set_pgoff(map, shdr->sh_offset);
-			map__set_mapping_type(map, MAPPING_TYPE__DSO);
-			/* Ensure maps are correctly ordered */
+			/*
+			 * If the map is tracking inside the kmaps cache list array, we

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1386

Quoted 10 lines
tools/perf/util/symbol-elf.c +5 -0
+			 * MUST remove it before mutating its virtual address key fields
+			 * in place. Otherwise, downstream binary search lookups (bsearch)
+			 * will search for mutated keys inside an array sorted under old
+			 * invariants, causing indexing desynchronization faults.
+			 */
 			if (kmaps) {
 				int err;
 				struct map *tmp = map__get(map);
 
 				maps__remove(kmaps, map);

Does this introduce a window where the kernel map is missing from kmaps?

maps__remove() and maps__insert() each independently acquire and release the kmaps write lock. During the gap between these operations, the kernel map is missing from the collection.

For KVM guests, kernel symbols are loaded lazily when the first guest sample is received. If concurrent perf top worker threads process samples during this window, will their maps__find() queries fail and cause samples to be dropped or misattributed as unknown?

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1391

Quoted 5 lines
tools/perf/util/symbol-elf.c +4 -0
+				map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
+				map__set_end(map, map__start(map) + shdr->sh_size);
+				map__set_pgoff(map, shdr->sh_offset);
+				map__set_mapping_type(map, MAPPING_TYPE__DSO);
 				err = maps__insert(kmaps, map);

If maps__insert() fails here (for example, due to an ENOMEM when reallocating the array), is the kernel map left permanently detached from kmaps?

If it remains detached but is still referenced by machine->vmlinux_map, what happens during session teardown? It looks like machine__destroy_kernel_maps() unconditionally calls maps__remove().

Inside __maps__remove(), if maps__by_address_index() fails to find the map and returns -1 (UINT_MAX), it seems the code will use this index to call map__put(maps_by_address[UINT_MAX]) and perform a memmove(). Could this trigger an out-of-bounds memory access and crash?

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1401

Quoted 10 lines
tools/perf/util/symbol-elf.c +5 -0
 				map__put(tmp);
 				if (err)
 					return err;
+			} else {
+				map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
+				map__set_end(map, map__start(map) + shdr->sh_size);
+				map__set_pgoff(map, shdr->sh_offset);
+				map__set_mapping_type(map, MAPPING_TYPE__DSO);
 			}
 		}

Also, this commit fixes the in-place map boundary mutations for ELF symbols, but does it miss similar patterns in the kallsyms loading path?

In dso__load_kernel_sym() and dso__load_guest_kernel_sym(), it appears map__fixup_start(map) directly mutates map->start in place after the map is already inserted into the kmaps array. Will this lockless mutation break the sorting invariants of the maps_by_address array in the same way, causing bsearch lookups to fail?

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

PATCH v5 4/5 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

In reply to Ian Rogers

If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames) to completely eliminate accidental address leakage vectors.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Fix memory leaks inside aslr_tool__delete destructor by calling standard
machines__destroy_kernel_maps() to cleanly free host/guest maps and guest machine structures. Introduce the precise 'first_kernel_mapping' tracking guard inside aslr.c to rewrite the core kernel pgoff virtual address while safely protecting module file offsets from corruption. Harden skipn() pipe I/O stream reader loops against EINTR interruption errors. Clean up breakpoint address (bp_addr) memory scrubbing by executing the scrubbing loop directly at core session initialization startup level, natively securing both file headers and streaming pipe channels while removing redundant runtime tool wrapper interception hooks layers.
v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove kernel
mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.
v3: Combine split-map fixes, guest namespaces, bounds checks, OOM rollbacks,
hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.
v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   31 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1220 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1261 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +30 -1
index f174bc69cec4..8fe479cb4152 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -304,6 +306,8 @@ static int perf_event__repipe(const struct perf_tool *tool,
 	return perf_event__repipe_synth(tool, event);
 }
 
+
+
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
 			    union perf_event *event __maybe_unused,
 			    struct perf_sample *sample __maybe_unused,
@@ -2458,6 +2462,8 @@ static int __cmd_inject(struct perf_inject *inject)
 			}
 		}
 
+
+
 		session->header.data_offset = output_data_offset;
 		session->header.data_size = inject->bytes_written;
 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2564,6 +2570,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2579,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,18 +2693,36 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
 	if (zstd_init(&(inject.session->zstd_data), 0) < 0)
 		pr_warning("Decompression initialization failed.\n");
 
+	if (inject.aslr) {
+		struct evsel *evsel;
+
+		evlist__for_each_entry(inject.session->evlist, evsel) {
+			if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+				evsel->core.attr.bp_addr = 0;
+		}
+	}
+
 	/* Save original section info before feature bits change */
 	ret = save_section_info(&inject);
 	if (ret)
@@ -2789,6 +2816,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +1220 -0

1,220 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
#29 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Cross-VM Isolation Failure in ASLR Remapping - [Medium] Callchain Parsing Omission for…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Cross-VM Isolation Failure in ASLR Remapping
- [Medium] Callchain Parsing Omission for PERF_CONTEXT_USER_DEFERRED
- [Low] Fragile Alignment of event_copy Buffer
--

commit 1b2fdd3058f351673614b5537a0bdcbb471a964a
Author: Ian Rogers <[email protected]>

perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

This patch adds an aslr option for perf inject that remaps all virtual addresses to prevent leaking host ASLR information. It uses a struct machines instance to isolate host mappings from KVM guest address spaces.

Quoted 5 lines
tools/perf/util/aslr.c new file +0 -0
new file mode 100644
index 0000000000000..effdcbec0db0d

[ ... ]

tools/perf/util/aslr.c line 57

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+struct remap_addresses_key {
+	struct dso *dso;
+	u64 invariant;
+	pid_t pid;
+};

Is there a missing machine identifier in this struct? If host processes and guest processes share the same PID and map anonymous memory at the same offset, it appears their keys will collide, causing the guest to reuse the host's remapped address.

[ ... ]

tools/perf/util/aslr.c line 72

Quoted 7 lines
tools/perf/util/aslr.c new file +7 -0
+struct aslr_tool {
+	/** @tool: The tool implemented here and a pointer to a delegate to process the data. */
+	struct delegate_tool tool;
+	/** @machines: The machines with the input, not remapped, virtual address layout. */
+	struct machines machines;
+	/** @event_copy: Buffer used to create an event to pass to the delegate. */
+	char event_copy[PERF_SAMPLE_MAX_SIZE];

This isn't a bug, but since event_copy is declared as a char array, it only guarantees a 1-byte alignment. While it currently happens to be 8-byte aligned because it follows struct machines, could future additions to struct aslr_tool break this alignment and cause crashes on strict-alignment architectures when it is cast to union perf_event *?

tools/perf/util/aslr.c line 76

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	/** @remap_addresses: mapping from remap_addresses_key to remapped address. */
+	struct hashmap remap_addresses;
+	/** @top_addresses: mapping from process to max remapped address. */
+	struct hashmap top_addresses;

Since top_addresses tracks allocations by pid alone, will host and guest processes with the same PID share the same allocation pool and intertwine their memory layouts?

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+static u64 aslr_tool__remap_ksymbol(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u64 addr, u32 len)
+{

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+		k = (struct remap_addresses_key *)cur->pkey;
+		if (k->pid == kernel_pid && k->invariant == key.invariant) {
+			v = (u64 *)cur->pvalue;

tools/perf/util/aslr.c line 386

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+
+			if (al.map)
+				remap_addr = *v + map__pgoff(al.map) +
+					     (addr - map__start(al.map));
+			else
+				remap_addr = *v;
+			addr_location__exit(&al);
+			return remap_addr;
+		}
+	}

Because both host and guest use kernel_pid (-1), will this loop match the first entry regardless of dso identity and cause guest kernel symbols to collide with host kernel symbols, leaking host kernel layouts to the guest?

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{

[ ... ]

tools/perf/util/aslr.c line 876

Quoted 12 lines
tools/perf/util/aslr.c new file +12 -0
+				case PERF_CONTEXT_GUEST_USER:
+					cpumode = PERF_RECORD_MISC_GUEST_USER;
+					break;
+				case PERF_CONTEXT_USER_DEFERRED:
+					/*
+					 * Immediately followed by a 64-bit
+					 * stitching cookie. Skip/Copy it!
+					 */
+					CHECK_BOUNDS(1, 1);
+					out_array[j++] = in_array[i++];
+					cntr++;
+					break;

Should this case also update cpumode to PERF_RECORD_MISC_USER?

Without it, subsequent user-space addresses will be processed using the preceding CPU mode (usually kernel). If a user address overlaps with a valid kernel map, it looks like it could be erroneously remapped as a kernel address.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer
#30 lore raw
In reply to Ian Rogers
Quoted 88 lines · Ian Rogers

If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames) to completely eliminate accidental address leakage vectors.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Fix memory leaks inside aslr_tool__delete destructor by calling standard
machines__destroy_kernel_maps() to cleanly free host/guest maps and guest machine structures. Introduce the precise 'first_kernel_mapping' tracking guard inside aslr.c to rewrite the core kernel pgoff virtual address while safely protecting module file offsets from corruption. Harden skipn() pipe I/O stream reader loops against EINTR interruption errors. Clean up breakpoint address (bp_addr) memory scrubbing by executing the scrubbing loop directly at core session initialization startup level, natively securing both file headers and streaming pipe channels while removing redundant runtime tool wrapper interception hooks layers.
v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove kernel
mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.
v3: Combine split-map fixes, guest namespaces, bounds checks, OOM rollbacks,
hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.
v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   31 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1220 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1261 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +4 -0
index f174bc69cec4..8fe479cb4152 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -304,6 +306,8 @@ static int perf_event__repipe(const struct perf_tool *tool,
 	return perf_event__repipe_synth(tool, event);
 }
 
+
+
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
 			    union perf_event *event __maybe_unused,
 			    struct perf_sample *sample __maybe_unused,

tools/perf/builtin-inject.c static int __cmd_inject(struct perf_inject *inject) · line 2466

Quoted 5 lines
tools/perf/builtin-inject.c +2 -0
@@ -2458,6 +2462,8 @@ static int __cmd_inject(struct perf_inject *inject)
 			}
 		}
 
+
+

Unnessary whitespace changes here and the above.

Quoted 125 lines
tools/perf/builtin-inject.c +24 -1
 		session->header.data_offset = output_data_offset;
 		session->header.data_size = inject->bytes_written;
 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2564,6 +2570,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2571,6 +2579,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,18 +2693,36 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
 	if (zstd_init(&(inject.session->zstd_data), 0) < 0)
 		pr_warning("Decompression initialization failed.\n");
 
+	if (inject.aslr) {
+		struct evsel *evsel;
+
+		evlist__for_each_entry(inject.session->evlist, evsel) {
+			if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+				evsel->core.attr.bp_addr = 0;
+		}
+	}
+
 	/* Save original section info before feature bits change */
 	ret = save_section_info(&inject);
 	if (ret)
@@ -2789,6 +2816,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +40 -0
new file mode 100644
index 000000000000..effdcbec0db0
@@ -0,0 +1,1220 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "aslr.h"
+
+#include "addr_location.h"
+#include "debug.h"
+#include "event.h"
+#include "evsel.h"
+#include "machine.h"
+#include "map.h"
+#include "thread.h"
+#include "tool.h"
+#include "session.h"
+#include "data.h"
+#include "dso.h"
+
+#include <internal/lib.h>  /* page_size */
+#include <linux/compiler.h>
+#include <linux/zalloc.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <unistd.h>
+
+static int skipn(int fd, u64 n)
+{
+	char buf[4096];
+	ssize_t ret;
+
+	while (n > 0) {
+		ret = read(fd, buf, (n < (u64)sizeof(buf) ? n : (u64)sizeof(buf)));
+		if (ret < 0) {
+			if (errno == EINTR)
+				continue;
+			return ret;
+		}
+		if (ret == 0)
+			return 0;
+		n -= ret;
+	}
+
+	return 0;

tools/perf/util/aslr.c line 50

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+}
+
+/**
+ * struct remap_addresses_key - Key for mapping original addresses to remapped ones.
+ * @dso: Pointer to the DSO (Dynamic Shared Object) associated with the mapping.
+ * @invariant: Unique offset invariant within the VMA (Virtual Memory Area).
+ *             Calculated as `start - pgoff`. This value remains constant when
+ *             perf's internal `maps__fixup_overlap_and_insert` splits a map into
+ *             fragmented VMA pieces due to overlapping events, allowing us to
+ *             resolve split maps consistently back to the original VMA.

I'm curious if it's guaranteed to be unique within a process.

Quoted 195 lines
tools/perf/util/aslr.c new file +195 -0
+ * @pid: Process ID associated with the mapping.
+ */
+struct remap_addresses_key {
+	struct dso *dso;
+	u64 invariant;
+	pid_t pid;
+};
+
+struct aslr_mapping {
+	struct list_head node;
+	u64 orig_start;
+	u64 len;
+	u64 remap_start;
+};
+
+struct aslr_tool {
+	/** @tool: The tool implemented here and a pointer to a delegate to process the data. */
+	struct delegate_tool tool;
+	/** @machines: The machines with the input, not remapped, virtual address layout. */
+	struct machines machines;
+	/** @event_copy: Buffer used to create an event to pass to the delegate. */
+	char event_copy[PERF_SAMPLE_MAX_SIZE];
+	/** @remap_addresses: mapping from remap_addresses_key to remapped address. */
+	struct hashmap remap_addresses;
+	/** @top_addresses: mapping from process to max remapped address. */
+	struct hashmap top_addresses;
+	/** @first_kernel_mapping: flag indicating if we are still to process any kernel mapping. */
+	bool first_kernel_mapping;
+};
+
+static const pid_t kernel_pid = -1;
+
+/* Start remapping user processes from a small non-zero offset. */
+static const u64 user_space_start = 0x200000;
+static const u64 kernel_space_start = 0xffff800010000000;
+
+static size_t remap_addresses__hash(long _key, void *ctx __maybe_unused)
+{
+	struct remap_addresses_key *key = (struct remap_addresses_key *)_key;
+
+	return (size_t)key->dso ^ key->invariant ^ key->pid;
+}
+
+static bool remap_addresses__equal(long _key1, long _key2, void *ctx __maybe_unused)
+{
+	struct remap_addresses_key *key1 = (struct remap_addresses_key *)_key1;
+	struct remap_addresses_key *key2 = (struct remap_addresses_key *)_key2;
+
+	return RC_CHK_EQUAL(key1->dso, key2->dso) &&
+	       key1->invariant == key2->invariant &&
+	       key1->pid == key2->pid;
+}
+
+static size_t top_addresses__hash(long key, void *ctx __maybe_unused)
+{
+	return key;
+}
+
+static bool top_addresses__equal(long key1, long key2, void *ctx __maybe_unused)
+{
+	return key1 == key2;
+}
+
+static u64 round_up_to_page_size(u64 addr)
+{
+	return (addr + page_size - 1) & ~((u64)page_size - 1);
+}
+
+static u64 aslr_tool__remap_address(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u8 cpumode,
+				    u64 addr)
+{
+	struct addr_location al;
+	struct remap_addresses_key key;
+	u64 *remapped_invariant_ptr = NULL;
+	u64 remap_addr = 0;
+	u8 effective_cpumode = cpumode;
+
+	if (!aslr_thread)
+		return 0; /* No thread. */
+
+	addr_location__init(&al);
+	if (!thread__find_map(aslr_thread, cpumode, addr, &al)) {
+		/*
+		 * If lookup fails with specified cpumode, try fallback to the other space
+		 * to be robust against bad cpumode in samples.
+		 */
+		if (cpumode == PERF_RECORD_MISC_KERNEL)
+			effective_cpumode = PERF_RECORD_MISC_USER;
+		else if (cpumode == PERF_RECORD_MISC_USER)
+			effective_cpumode = PERF_RECORD_MISC_KERNEL;
+		else if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL)
+			effective_cpumode = PERF_RECORD_MISC_GUEST_USER;
+		else if (cpumode == PERF_RECORD_MISC_GUEST_USER)
+			effective_cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+
+		if (!thread__find_map(aslr_thread, effective_cpumode, addr, &al)) {
+			addr_location__exit(&al);
+			return 0; /* No mmap. */
+		}
+	}
+
+	key.dso = map__dso(al.map);
+	key.invariant = map__start(al.map) - map__pgoff(al.map);
+	key.pid = effective_cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;
+
+	if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+		remap_addr = *remapped_invariant_ptr + map__pgoff(al.map) +
+			     (addr - map__start(al.map));
+	} else {
+		if (effective_cpumode == PERF_RECORD_MISC_KERNEL) {
+			struct hashmap_entry *cur;
+			size_t bkt;
+
+			hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+				struct remap_addresses_key *k;
+				u64 *v;
+
+				k = (struct remap_addresses_key *)cur->pkey;
+				if (k->pid == kernel_pid &&
+				    k->invariant == key.invariant) {
+					v = (u64 *)cur->pvalue;
+					remap_addr = *v + map__pgoff(al.map) +
+						     (addr - map__start(al.map));
+					break;
+				}
+			}
+		}
+		if (remap_addr == 0) {
+			pr_debug("Cannot find a remapped entry for address %lx in mapping %lx(%lx) for pid=%d\n",
+				 addr, map__start(al.map), map__size(al.map), key.pid);
+		}
+	}
+
+	addr_location__exit(&al);
+	return remap_addr;
+}
+
+static u64 aslr_tool__remap_mapping(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u8 cpumode,
+				    u64 start, u64 len, u64 pgoff)
+{
+	struct addr_location al;
+	struct addr_location prev_al;
+	struct remap_addresses_key key;
+	struct remap_addresses_key *new_key = NULL;
+	struct remap_addresses_key *old_key = NULL;
+	u64 remap_addr = 0;
+	u64 *remapped_invariant_ptr = NULL;
+	u64 *max_addr_ptr = NULL;
+	u64 *new_val = NULL;
+	u64 *new_max = NULL;
+	u64 *old_val = NULL;
+	u64 *old_val_remap = NULL;
+	bool is_contiguous = false;
+	bool first_mapping = false;
+	bool key_found = false;
+	int err;
+
+	if (!aslr_thread)
+		return 0; /* No thread. */
+
+	addr_location__init(&al);
+	if (thread__find_map(aslr_thread, cpumode, start, &al)) {
+		key.dso = map__dso(al.map);
+		key.invariant = map__start(al.map) - map__pgoff(al.map);
+	} else {
+		key.dso = NULL;
+		key.invariant = start - pgoff;
+	}
+	key.pid = cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;
+
+	if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+		remap_addr = *remapped_invariant_ptr + (al.map ? map__pgoff(al.map) : pgoff);
+		key_found = true;
+	} else {
+		addr_location__init(&prev_al);
+		if (thread__find_map(aslr_thread, cpumode, start - 1, &prev_al)) {
+			if (map__start(prev_al.map) + map__size(prev_al.map) == start) {
+				is_contiguous = true;
+			} else {
+				pr_debug("Previous mmap [%lx, %lx] overlaps current map [%lx, %lx]\n",
+					 map__start(prev_al.map),
+					 map__start(prev_al.map) + map__size(prev_al.map),
+					 start, start+len);
+			}
+		}
+		addr_location__exit(&prev_al);
+
+		if (!hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+			first_mapping = true;
+			remap_addr = (cpumode == PERF_RECORD_MISC_KERNEL ?
+				      kernel_space_start : user_space_start);

tools/perf/util/aslr.c line 255

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+		} else {
+			remap_addr = *max_addr_ptr;
+		}
+
+		remap_addr = round_up_to_page_size(remap_addr);
+		if (!is_contiguous && !first_mapping)
+			remap_addr += page_size;
+
+		new_key = malloc(sizeof(*new_key));
+		new_val = malloc(sizeof(u64));

I think the value of hashmap can be passed as value if it's u64.. well on 64-bit systems.

Quoted 65 lines
tools/perf/util/aslr.c new file +65 -0
+
+		if (!new_key || !new_val) {
+			free(new_key);
+			free(new_val);
+			addr_location__exit(&al);
+			return 0;
+		}
+		*new_key = key;
+		new_key->dso = dso__get(key.dso);
+		*new_val = remap_addr - (al.map ? map__pgoff(al.map) : pgoff);
+
+		if (hashmap__add(&aslr->remap_addresses, new_key, new_val) != 0) {
+			dso__put(new_key->dso);
+			free(new_key);
+			free(new_val);
+			addr_location__exit(&al);
+			return 0;
+		}
+	}
+
+	/* Update top_addresses */
+	new_max = malloc(sizeof(u64));
+	old_val = NULL;
+
+	if (!new_max) {
+		old_key = NULL;
+		old_val_remap = NULL;
+
+		if (!key_found) {
+			hashmap__delete(&aslr->remap_addresses, &key,
+					&old_key, &old_val_remap);
+			if (old_key)
+				dso__put(old_key->dso);
+			free(old_key);
+			free(old_val_remap);
+		}
+		addr_location__exit(&al);
+		return 0;
+	}
+	*new_max = remap_addr + len;
+
+	if (hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+		if (*max_addr_ptr > *new_max)
+			*new_max = *max_addr_ptr;
+	}
+
+	err = hashmap__insert(&aslr->top_addresses, key.pid, new_max,
+				  (first_mapping && !key_found) ?
+					HASHMAP_ADD : HASHMAP_UPDATE,
+				  NULL, &old_val);
+	if (err) {
+		old_key = NULL;
+		old_val_remap = NULL;
+
+		free(new_max);
+		if (!key_found) {
+			hashmap__delete(&aslr->remap_addresses, &key,
+					&old_key, &old_val_remap);
+			if (old_key)
+				dso__put(old_key->dso);
+			free(old_key);
+			free(old_val_remap);
+		}
+		addr_location__exit(&al);
+		return 0;

tools/perf/util/aslr.c line 330

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	}
+	free(old_val);
+
+	addr_location__exit(&al);
+	return remap_addr;
+}
+
+static u64 aslr_tool__remap_ksymbol(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u64 addr, u32 len)

Any chance you can share the code with the above function?

Quoted 424 lines
tools/perf/util/aslr.c new file +424 -0
+{
+	struct addr_location al;
+	struct remap_addresses_key key;
+	struct hashmap_entry *cur;
+	struct remap_addresses_key *new_key = NULL;
+	struct remap_addresses_key *old_key = NULL;
+	struct remap_addresses_key *k;
+	size_t bkt;
+	u64 remap_addr = 0;
+	u64 *remapped_invariant_ptr = NULL;
+	u64 *max_addr_ptr = NULL;
+	u64 *new_val = NULL;
+	u64 *new_max = NULL;
+	u64 *old_val = NULL;
+	u64 *old_val_remap = NULL;
+	u64 *v;
+	bool first_mapping = false;
+	int err;
+
+	if (!aslr_thread)
+		return 0; /* No thread. */
+
+	addr_location__init(&al);
+	if (thread__find_map(aslr_thread, PERF_RECORD_MISC_KERNEL, addr, &al)) {
+		key.dso = map__dso(al.map);
+		key.invariant = map__start(al.map) - map__pgoff(al.map);
+	} else {
+		key.dso = NULL;
+		key.invariant = addr; /* pgoff is 0 for ksymbols */
+	}
+	key.pid = aslr_thread->pid_;
+
+	if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+		if (al.map)
+			remap_addr = *remapped_invariant_ptr + map__pgoff(al.map) +
+				     (addr - map__start(al.map));
+		else
+			remap_addr = *remapped_invariant_ptr;
+		addr_location__exit(&al);
+		return remap_addr;
+	}
+
+	hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+		k = (struct remap_addresses_key *)cur->pkey;
+		if (k->pid == kernel_pid && k->invariant == key.invariant) {
+			v = (u64 *)cur->pvalue;
+
+			if (al.map)
+				remap_addr = *v + map__pgoff(al.map) +
+					     (addr - map__start(al.map));
+			else
+				remap_addr = *v;
+			addr_location__exit(&al);
+			return remap_addr;
+		}
+	}
+
+	if (!hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+		first_mapping = true;
+		remap_addr = kernel_space_start;
+	} else {
+		remap_addr = *max_addr_ptr;
+	}
+
+	remap_addr = round_up_to_page_size(remap_addr) + page_size;
+
+	new_key = malloc(sizeof(*new_key));
+	new_val = malloc(sizeof(u64));
+
+	if (!new_key || !new_val) {
+		free(new_key);
+		free(new_val);
+		addr_location__exit(&al);
+		return 0;
+	}
+	*new_key = key;
+	new_key->dso = dso__get(key.dso);
+	if (al.map)
+		*new_val = remap_addr - (addr - map__start(al.map)) - map__pgoff(al.map);
+	else
+		*new_val = remap_addr;
+
+	if (hashmap__add(&aslr->remap_addresses, new_key, new_val) < 0) {
+		dso__put(new_key->dso);
+		free(new_key);
+		free(new_val);
+		addr_location__exit(&al);
+		return 0;
+	}
+
+	new_max = malloc(sizeof(u64));
+	old_val = NULL;
+
+	if (!new_max) {
+		old_key = NULL;
+		old_val_remap = NULL;
+
+		hashmap__delete(&aslr->remap_addresses, &key, &old_key, &old_val_remap);
+		if (old_key)
+			dso__put(old_key->dso);
+		free(old_key);
+		free(old_val_remap);
+		addr_location__exit(&al);
+		return 0;
+	}
+	*new_max = remap_addr + len;
+
+	if (hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+		if (*max_addr_ptr > *new_max)
+			*new_max = *max_addr_ptr;
+	}
+
+	err = hashmap__insert(&aslr->top_addresses, key.pid, new_max,
+				  first_mapping ?
+					HASHMAP_ADD : HASHMAP_UPDATE,
+				  NULL, &old_val);
+	if (err) {
+		old_key = NULL;
+		old_val_remap = NULL;
+
+		free(new_max);
+		hashmap__delete(&aslr->remap_addresses, &key, &old_key, &old_val_remap);
+		if (old_key)
+			dso__put(old_key->dso);
+		free(old_key);
+		free(old_val_remap);
+		addr_location__exit(&al);
+		return 0;
+	}
+	free(old_val);
+
+	addr_location__exit(&al);
+	return remap_addr;
+}
+
+
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	u8 cpumode;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_mmap(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, event->mmap.pid, event->mmap.tid);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap.start,
+							   event->mmap.len,
+							   event->mmap.pgoff);
+	if (aslr->first_kernel_mapping && cpumode == PERF_RECORD_MISC_KERNEL) {
+		new_event->mmap.pgoff = new_event->mmap.start;
+		aslr->first_kernel_mapping = false;
+	}
+	err = delegate->mmap(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_mmap2(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	u8 cpumode;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_mmap2(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, event->mmap2.pid, event->mmap2.tid);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->mmap2, &event->mmap2, event->mmap2.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap2.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+							   event->mmap2.start,
+							   event->mmap2.len,
+							   event->mmap2.pgoff);
+	if (aslr->first_kernel_mapping && cpumode == PERF_RECORD_MISC_KERNEL) {
+		new_event->mmap2.pgoff = new_event->mmap2.start;
+		aslr->first_kernel_mapping = false;
+	}
+	err = delegate->mmap2(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_comm(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_comm(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->comm(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_fork(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_fork(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->fork(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_exit(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_exit(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->exit(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_text_poke(const struct perf_tool *tool,
+					union perf_event *event,
+					struct perf_sample *sample,
+					struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	u8 cpumode;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	thread = machine__findnew_thread(aslr_machine, sample->pid, sample->tid);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->text_poke, &event->text_poke, event->text_poke.header.size);
+	new_event->text_poke.addr = aslr_tool__remap_address(aslr, thread, cpumode,
+							     event->text_poke.addr);
+
+	err = delegate->text_poke(delegate, new_event, sample, machine);
+
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_ksymbol(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	err = perf_event__process_ksymbol(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, kernel_pid, 0);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->ksymbol, &event->ksymbol, event->ksymbol.header.size);
+	/* Remaps the ksymbol.start */
+	new_event->ksymbol.addr = aslr_tool__remap_ksymbol(aslr, thread,
+							   event->ksymbol.addr, event->ksymbol.len);
+
+	err = delegate->ksymbol(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	int ret;
+	u64 sample_type;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	__u64 max_i;
+	__u64 max_j;
+	union perf_event *new_event;
+	struct perf_sample new_sample;
+	__u64 *in_array, *out_array;
+	u8 cpumode;
+	u64 addr;
+	size_t i;
+	size_t j;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	ret = -EFAULT;
+	sample_type = evsel->core.attr.sample_type;
+	max_i = (event->header.size - sizeof(struct perf_event_header)) / sizeof(__u64);
+	max_j = (PERF_SAMPLE_MAX_SIZE - sizeof(struct perf_event_header)) / sizeof(__u64);
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = sample->cpumode;
+	i = 0;
+	j = 0;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+

tools/perf/util/aslr.c line 764

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	thread = machine__findnew_thread(aslr_machine, sample->pid, sample->tid);
+
+	if (!thread)
+		return -ENOMEM;
+
+	if (max_i > PERF_SAMPLE_MAX_SIZE / sizeof(u64))
+		goto out_put;
+
+
+

Excessive blank lines.

Quoted 191 lines
tools/perf/util/aslr.c new file +191 -0
+	new_event->sample.header = event->sample.header;
+
+	in_array = &event->sample.array[0];
+	out_array = &new_event->sample.array[0];
+
+#define CHECK_BOUNDS(required_i, required_j) \
+	do { \
+		if (i + (required_i) > max_i || j + (required_j) > max_j) { \
+			ret = -EFAULT; \
+			goto out_put; \
+		} \
+	} while (0)
+
+#define COPY_U64() \
+	do { \
+		CHECK_BOUNDS(1, 1); \
+		out_array[j++] = in_array[i++]; \
+	} while (0)
+
+#define REMAP_U64(addr_field) \
+	do { \
+		CHECK_BOUNDS(1, 1); \
+		out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr_field); \
+		i++; \
+	} while (0)
+
+	if (sample_type & PERF_SAMPLE_IDENTIFIER)
+		COPY_U64(); /* id */
+	if (sample_type & PERF_SAMPLE_IP)
+		REMAP_U64(sample->ip);
+	if (sample_type & PERF_SAMPLE_TID)
+		COPY_U64(); /* pid, tid */
+	if (sample_type & PERF_SAMPLE_TIME)
+		COPY_U64(); /* time */
+	if (sample_type & PERF_SAMPLE_ADDR)
+		REMAP_U64(sample->addr);
+	if (sample_type & PERF_SAMPLE_ID)
+		COPY_U64(); /* id */
+	if (sample_type & PERF_SAMPLE_STREAM_ID)
+		COPY_U64(); /* stream_id */
+	if (sample_type & PERF_SAMPLE_CPU)
+		COPY_U64(); /* cpu, res */
+	if (sample_type & PERF_SAMPLE_PERIOD)
+		COPY_U64(); /* period */
+	if (sample_type & PERF_SAMPLE_READ) {
+		if ((evsel->core.attr.read_format & PERF_FORMAT_GROUP) == 0) {
+			COPY_U64(); /* value */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+				COPY_U64(); /* time_enabled */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+				COPY_U64(); /* time_running */
+			if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+				COPY_U64(); /* id */
+			if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+				COPY_U64(); /* lost */
+		} else {
+			u64 nr;
+
+			CHECK_BOUNDS(1, 1);
+			nr = out_array[j++] = in_array[i++];
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+				COPY_U64(); /* time_enabled */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+				COPY_U64(); /* time_running */
+			for (u64 cntr = 0; cntr < nr; cntr++) {
+				COPY_U64(); /* value */
+				if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+					COPY_U64(); /* id */
+				if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+					COPY_U64(); /* lost */
+			}
+		}
+	}
+	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
+		u64 nr;
+
+		CHECK_BOUNDS(1, 1);
+		nr = out_array[j++] = in_array[i++];
+
+		for (u64 cntr = 0; cntr < nr; cntr++) {
+			CHECK_BOUNDS(1, 1);
+			addr = in_array[i++];
+			if (addr >= PERF_CONTEXT_MAX) {
+				out_array[j++] = addr;
+				switch (addr) {
+				case PERF_CONTEXT_HV:
+					cpumode = PERF_RECORD_MISC_HYPERVISOR;
+					break;
+				case PERF_CONTEXT_KERNEL:
+					cpumode = PERF_RECORD_MISC_KERNEL;
+					break;
+				case PERF_CONTEXT_USER:
+					cpumode = PERF_RECORD_MISC_USER;
+					break;
+				case PERF_CONTEXT_GUEST:
+					cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+					break;
+				case PERF_CONTEXT_GUEST_KERNEL:
+					cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+					break;
+				case PERF_CONTEXT_GUEST_USER:
+					cpumode = PERF_RECORD_MISC_GUEST_USER;
+					break;
+				case PERF_CONTEXT_USER_DEFERRED:
+					/*
+					 * Immediately followed by a 64-bit
+					 * stitching cookie. Skip/Copy it!
+					 */
+					CHECK_BOUNDS(1, 1);
+					out_array[j++] = in_array[i++];
+					cntr++;
+					break;
+				default:
+					pr_debug("invalid callchain context: %"PRIx64"\n", addr);
+					ret = 0;
+					goto out_put;
+				}
+				continue;
+			}
+			out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr);
+		}
+	}
+	if (sample_type & PERF_SAMPLE_RAW) {
+		size_t bytes = sizeof(u32) + sample->raw_size;
+		size_t u64_words = (bytes + 7) / 8;
+
+		if (i + u64_words > max_i || j + u64_words > max_j) {
+			ret = -EFAULT;
+			goto out_put;
+		}
+		memcpy(&out_array[j], &in_array[i], bytes);
+		i += u64_words;
+		j += u64_words;
+		/*
+		 * TODO: certain raw samples can be remapped, such as
+		 * tracepoints by examining their fields.
+		 */
+		pr_debug("Dropping raw samples as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
+		u64 nr;
+
+		CHECK_BOUNDS(1, 1);
+		nr = out_array[j++] = in_array[i++];
+
+		if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)
+			COPY_U64(); /* hw_idx */
+
+		if (nr > (ULLONG_MAX / 3)) {
+			ret = -EFAULT;
+			goto out_put;
+		}
+		if (nr * 3 > max_i - i || nr * 3 > max_j - j) {
+			ret = -EFAULT;
+			goto out_put;
+		}
+		for (u64 cntr = 0; cntr < nr; cntr++) {
+			out_array[j++] = aslr_tool__remap_address(aslr, thread,
+								  sample->cpumode,
+								  in_array[i++]); /* from */
+			out_array[j++] = aslr_tool__remap_address(aslr, thread,
+								  sample->cpumode,
+								  in_array[i++]); /* to */
+			out_array[j++] = in_array[i++]; /* flags */
+		}
+		if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) {
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+			/* TODO: confirm branch counters don't leak ASLR information. */
+			pr_debug("Dropping sample branch counters as possible ASLR leak\n");
+			ret = 0;
+			goto out_put;
+		}
+	}
+	if (sample_type & PERF_SAMPLE_REGS_USER) {
+		u64 abi;
+
+		COPY_U64(); /* abi */
+		abi = out_array[j-1];
+		if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+			u64 nr = hweight64(evsel->core.attr.sample_regs_user);
+
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;

tools/perf/util/aslr.c line 965

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping regs user sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;

Is this mean you drop samples if it contains registers?

Quoted 86 lines
tools/perf/util/aslr.c new file +86 -0
+	}
+	if (sample_type & PERF_SAMPLE_STACK_USER) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+
+			COPY_U64(); /* dyn_size */
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping stack user sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
+		COPY_U64(); /* perf_sample_weight */
+	if (sample_type & PERF_SAMPLE_DATA_SRC)
+		COPY_U64(); /* data_src */
+	if (sample_type & PERF_SAMPLE_TRANSACTION)
+		COPY_U64(); /* transaction */
+	if (sample_type & PERF_SAMPLE_REGS_INTR) {
+		u64 abi;
+
+		COPY_U64(); /* abi */
+		abi = out_array[j-1];
+		if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+			u64 nr = hweight64(evsel->core.attr.sample_regs_intr);
+
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping interrupt register sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_PHYS_ADDR) {
+		COPY_U64(); /* phys_addr */
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping physical address sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_CGROUP)
+		COPY_U64(); /* cgroup */
+	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
+		COPY_U64(); /* data_page_size */
+	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
+		COPY_U64(); /* code_page_size */
+
+	if (sample_type & PERF_SAMPLE_AUX) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+

tools/perf/util/aslr.c line 1061

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping aux sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}

Can you use perf_event__synthesize_sample()?

tools/perf/util/aslr.c line 1065

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+
+	if (evsel__is_offcpu_event(evsel)) {
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping off-CPU sample as possible ASLR leak\n");

Why not remap the address?

Thanks,
Namhyung

Quoted 174 lines
tools/perf/util/aslr.c new file +155 -0
+		ret = 0;
+		goto out_put;
+	}
+
+	new_event->sample.header.size = sizeof(struct perf_event_header) + j * sizeof(u64);
+
+	perf_sample__init(&new_sample, /*all=*/ true);
+	ret = evsel__parse_sample(evsel, new_event, &new_sample);
+	if (ret) {
+		perf_sample__exit(&new_sample);
+		goto out_put;
+	}
+
+	ret = delegate->sample(delegate, new_event, &new_sample, evsel, machine);
+	perf_sample__exit(&new_sample);
+
+out_put:
+	thread__put(thread);
+	return ret;
+}
+
+#undef CHECK_BOUNDS
+#undef COPY_U64
+#undef REMAP_U64
+
+
+static int aslr_tool__process_attr(const struct perf_tool *tool,
+				   union perf_event *event,
+				   struct evlist **pevlist)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+
+	memcpy(&new_event->attr, &event->attr, event->attr.header.size);
+	if (new_event->attr.attr.type == PERF_TYPE_BREAKPOINT)
+		new_event->attr.attr.bp_addr = 0;  /* Conservatively remove addresses. */
+
+	return delegate->attr(delegate, new_event, pevlist);
+}
+
+static s64 aslr_tool__process_auxtrace(const struct perf_tool *tool __maybe_unused,
+				       struct perf_session *session,
+				       union perf_event *event)
+{
+	if (perf_data__is_pipe(session->data)) {
+		int err = skipn(perf_data__fd(session->data), event->auxtrace.size);
+
+		if (err < 0)
+			return err;
+	}
+	return event->auxtrace.size;
+}
+
+static int aslr_tool__process_auxtrace_info(const struct perf_tool *tool __maybe_unused,
+					    struct perf_session *session __maybe_unused,
+					    union perf_event *event __maybe_unused)
+{
+	return 0;
+}
+
+static int aslr_tool__process_auxtrace_error(const struct perf_tool *tool __maybe_unused,
+					     struct perf_session *session __maybe_unused,
+					     union perf_event *event __maybe_unused)
+{
+	return 0;
+}
+
+static void aslr_tool__init(struct aslr_tool *aslr, struct perf_tool *delegate)
+{
+	delegate_tool__init(&aslr->tool, delegate);
+	aslr->tool.tool.ordered_events = true;
+
+	machines__init(&aslr->machines);
+
+	hashmap__init(&aslr->remap_addresses,
+		      remap_addresses__hash, remap_addresses__equal,
+		      /*ctx=*/NULL);
+	hashmap__init(&aslr->top_addresses,
+		      top_addresses__hash, top_addresses__equal,
+		      /*ctx=*/NULL);
+	aslr->first_kernel_mapping = true;
+
+	aslr->tool.tool.sample	= aslr_tool__process_sample;
+	/* read - reads a counter, okay to delegate. */
+	aslr->tool.tool.mmap	= aslr_tool__process_mmap;
+	aslr->tool.tool.mmap2	= aslr_tool__process_mmap2;
+	aslr->tool.tool.comm	= aslr_tool__process_comm;
+	aslr->tool.tool.fork	= aslr_tool__process_fork;
+	aslr->tool.tool.exit	= aslr_tool__process_exit;
+	/* namesspaces, cgroup, lost, lost_sample, aux, */
+	/* itrace_start, aux_output_hw_id, context_switch, throttle, unthrottle */
+	/* - no virtual addresses. */
+	aslr->tool.tool.ksymbol	= aslr_tool__process_ksymbol;
+	/* bpf - no virtual address. */
+	aslr->tool.tool.text_poke = aslr_tool__process_text_poke;
+	aslr->tool.tool.attr = aslr_tool__process_attr;
+	/* event_update, tracing_data, finished_round, build_id, id_index, */
+	/* event_update, tracing_data, finished_round, build_id, id_index, */
+	/* auxtrace_info, auxtrace_error, time_conv, thread_map, cpu_map, */
+	/* stat_config, stat, feature, finished_init, bpf_metadata, compressed, */
+	/* auxtrace - no virtual addresses. */
+	aslr->tool.tool.auxtrace = aslr_tool__process_auxtrace;
+	aslr->tool.tool.auxtrace_info = aslr_tool__process_auxtrace_info;
+	aslr->tool.tool.auxtrace_error = aslr_tool__process_auxtrace_error;
+}
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate)
+{
+	struct aslr_tool *aslr = zalloc(sizeof(*aslr));
+
+	if (!aslr)
+		return NULL;
+
+	aslr_tool__init(aslr, delegate);
+	return &aslr->tool.tool;
+}
+
+void aslr_tool__delete(struct perf_tool *tool)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct hashmap_entry *cur;
+	size_t bkt;
+
+	if (!tool)
+		return;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+
+	hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+		struct remap_addresses_key *key = (struct remap_addresses_key *)cur->pkey;
+
+		if (key)
+			dso__put(key->dso);
+		zfree(&cur->pkey);
+		zfree(&cur->pvalue);
+	}
+	hashmap__for_each_entry(&aslr->top_addresses, cur, bkt) {
+		zfree(&cur->pvalue);
+	}
+
+	hashmap__clear(&aslr->remap_addresses);
+	hashmap__clear(&aslr->top_addresses);
+	machines__destroy_kernel_maps(&aslr->machines);
+	machines__exit(&aslr->machines);
+	free(aslr);
+}
tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author reviewer
#31 lore raw
Quoted 93 lines · Namhyung Kim
Quoted 91 lines · Ian Rogers

If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

When events are not known/handled by the tool they are dropped. This makes the tool conservative and it should never leak ASLR information, but it means virtual address remapping is needed for cases like auxtrace.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames) to completely eliminate accidental address leakage vectors.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Fix memory leaks inside aslr_tool__delete destructor by calling standard
machines__destroy_kernel_maps() to cleanly free host/guest maps and guest machine structures. Introduce the precise 'first_kernel_mapping' tracking guard inside aslr.c to rewrite the core kernel pgoff virtual address while safely protecting module file offsets from corruption. Harden skipn() pipe I/O stream reader loops against EINTR interruption errors. Clean up breakpoint address (bp_addr) memory scrubbing by executing the scrubbing loop directly at core session initialization startup level, natively securing both file headers and streaming pipe channels while removing redundant runtime tool wrapper interception hooks layers.
v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove kernel
mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.
v3: Combine split-map fixes, guest namespaces, bounds checks, OOM rollbacks,
hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.
v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   31 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1220 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1261 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +4 -0
index f174bc69cec4..8fe479cb4152 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
      bool                    in_place_update_dry_run;
      bool                    copy_kcore_dir;
      bool                    convert_callchain;
+     bool                    aslr;
      const char              *input_name;
      struct perf_data        output;
      u64                     bytes_written;
@@ -304,6 +306,8 @@ static int perf_event__repipe(const struct perf_tool *tool,
      return perf_event__repipe_synth(tool, event);
 }
 
+
+
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
                          union perf_event *event __maybe_unused,
                          struct perf_sample *sample __maybe_unused,
@@ -2458,6 +2462,8 @@ static int __cmd_inject(struct perf_inject *inject)
                      }
              }
 
Quoted 4 lines

tools/perf/builtin-inject.c static int __cmd_inject(struct perf_inject *inject) · line 2466

Quoted 2 lines
tools/perf/builtin-inject.c +2 -0
+
+

Unnessary whitespace changes here and the above.

Ack.

Quoted 129 lines
Quoted 129 lines
tools/perf/builtin-inject.c +24 -1
              session->header.data_offset = output_data_offset;
              session->header.data_size = inject->bytes_written;
              perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2564,6 +2570,8 @@ int cmd_inject(int argc, const char **argv)
                         " instance has a subdir"),
              OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
                          "Generate callchains using DWARF and drop register/stack data"),
+             OPT_BOOLEAN(0, "aslr", &inject.aslr,
+                         "Remap virtual memory addresses similar to ASLR"),
              OPT_END()
      };
      const char * const inject_usage[] = {
@@ -2571,6 +2579,7 @@ int cmd_inject(int argc, const char **argv)
              NULL
      };
      bool ordered_events;
+     struct perf_tool *tool = &inject.tool;
 
      if (!inject.itrace_synth_opts.set) {
              /* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2684,18 +2693,36 @@ int cmd_inject(int argc, const char **argv)
      inject.tool.schedstat_domain    = perf_event__repipe_op2_synth;
      inject.tool.dont_split_sample_group = true;
      inject.tool.merge_deferred_callchains = false;
-     inject.session = __perf_session__new(&data, &inject.tool,
+     if (inject.aslr) {
+             tool = aslr_tool__new(&inject.tool);
+             if (!tool) {
+                     ret = -ENOMEM;
+                     goto out_close_output;
+             }
+     }
+     inject.session = __perf_session__new(&data, tool,
                                           /*trace_event_repipe=*/inject.output.is_pipe,
                                           /*host_env=*/NULL);
 
      if (IS_ERR(inject.session)) {
              ret = PTR_ERR(inject.session);
+             if (inject.aslr)
+                     aslr_tool__delete(tool);
              goto out_close_output;
      }
 
      if (zstd_init(&(inject.session->zstd_data), 0) < 0)
              pr_warning("Decompression initialization failed.\n");
 
+     if (inject.aslr) {
+             struct evsel *evsel;
+
+             evlist__for_each_entry(inject.session->evlist, evsel) {
+                     if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+                             evsel->core.attr.bp_addr = 0;
+             }
+     }
+
      /* Save original section info before feature bits change */
      ret = save_section_info(&inject);
      if (ret)
@@ -2789,6 +2816,8 @@ int cmd_inject(int argc, const char **argv)
      strlist__delete(inject.known_build_ids);
      zstd_fini(&(inject.session->zstd_data));
      perf_session__delete(inject.session);
+     if (inject.aslr)
+             aslr_tool__delete(tool);
 out_close_output:
      if (!inject.in_place_update)
              perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +44 -0
new file mode 100644
index 000000000000..effdcbec0db0
@@ -0,0 +1,1220 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "aslr.h"
+
+#include "addr_location.h"
+#include "debug.h"
+#include "event.h"
+#include "evsel.h"
+#include "machine.h"
+#include "map.h"
+#include "thread.h"
+#include "tool.h"
+#include "session.h"
+#include "data.h"
+#include "dso.h"
+
+#include <internal/lib.h>  /* page_size */
+#include <linux/compiler.h>
+#include <linux/zalloc.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <unistd.h>
+
+static int skipn(int fd, u64 n)
+{
+     char buf[4096];
+     ssize_t ret;
+
+     while (n > 0) {
+             ret = read(fd, buf, (n < (u64)sizeof(buf) ? n : (u64)sizeof(buf)));
+             if (ret < 0) {
+                     if (errno == EINTR)
+                             continue;
+                     return ret;
+             }
+             if (ret == 0)
+                     return 0;
+             n -= ret;
+     }
+
+     return 0;
+}
+
+/**
+ * struct remap_addresses_key - Key for mapping original addresses to remapped ones.
Quoted 8 lines

tools/perf/util/aslr.c line 50

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+ * @dso: Pointer to the DSO (Dynamic Shared Object) associated with the mapping.
+ * @invariant: Unique offset invariant within the VMA (Virtual Memory Area).
+ *             Calculated as `start - pgoff`. This value remains constant when
+ *             perf's internal `maps__fixup_overlap_and_insert` splits a map into
+ *             fragmented VMA pieces due to overlapping events, allowing us to
+ *             resolve split maps consistently back to the original VMA.

I'm curious if it's guaranteed to be unique within a process.

You could have two DSOs at different addresses, and when the `address
- pgoff` is computed, they might yield the same invariant value. However, in that case the DSOs differ, so the keys don't match. If it were the same DSO, either the address or the pgoff would differ making it impossible to have the same invariant value.

Quoted 201 lines
Quoted 201 lines
tools/perf/util/aslr.c new file +200 -0
+ * @pid: Process ID associated with the mapping.
+ */
+struct remap_addresses_key {
+     struct dso *dso;
+     u64 invariant;
+     pid_t pid;
+};
+
+struct aslr_mapping {
+     struct list_head node;
+     u64 orig_start;
+     u64 len;
+     u64 remap_start;
+};
+
+struct aslr_tool {
+     /** @tool: The tool implemented here and a pointer to a delegate to process the data. */
+     struct delegate_tool tool;
+     /** @machines: The machines with the input, not remapped, virtual address layout. */
+     struct machines machines;
+     /** @event_copy: Buffer used to create an event to pass to the delegate. */
+     char event_copy[PERF_SAMPLE_MAX_SIZE];
+     /** @remap_addresses: mapping from remap_addresses_key to remapped address. */
+     struct hashmap remap_addresses;
+     /** @top_addresses: mapping from process to max remapped address. */
+     struct hashmap top_addresses;
+     /** @first_kernel_mapping: flag indicating if we are still to process any kernel mapping. */
+     bool first_kernel_mapping;
+};
+
+static const pid_t kernel_pid = -1;
+
+/* Start remapping user processes from a small non-zero offset. */
+static const u64 user_space_start = 0x200000;
+static const u64 kernel_space_start = 0xffff800010000000;
+
+static size_t remap_addresses__hash(long _key, void *ctx __maybe_unused)
+{
+     struct remap_addresses_key *key = (struct remap_addresses_key *)_key;
+
+     return (size_t)key->dso ^ key->invariant ^ key->pid;
+}
+
+static bool remap_addresses__equal(long _key1, long _key2, void *ctx __maybe_unused)
+{
+     struct remap_addresses_key *key1 = (struct remap_addresses_key *)_key1;
+     struct remap_addresses_key *key2 = (struct remap_addresses_key *)_key2;
+
+     return RC_CHK_EQUAL(key1->dso, key2->dso) &&
+            key1->invariant == key2->invariant &&
+            key1->pid == key2->pid;
+}
+
+static size_t top_addresses__hash(long key, void *ctx __maybe_unused)
+{
+     return key;
+}
+
+static bool top_addresses__equal(long key1, long key2, void *ctx __maybe_unused)
+{
+     return key1 == key2;
+}
+
+static u64 round_up_to_page_size(u64 addr)
+{
+     return (addr + page_size - 1) & ~((u64)page_size - 1);
+}
+
+static u64 aslr_tool__remap_address(struct aslr_tool *aslr,
+                                 struct thread *aslr_thread,
+                                 u8 cpumode,
+                                 u64 addr)
+{
+     struct addr_location al;
+     struct remap_addresses_key key;
+     u64 *remapped_invariant_ptr = NULL;
+     u64 remap_addr = 0;
+     u8 effective_cpumode = cpumode;
+
+     if (!aslr_thread)
+             return 0; /* No thread. */
+
+     addr_location__init(&al);
+     if (!thread__find_map(aslr_thread, cpumode, addr, &al)) {
+             /*
+              * If lookup fails with specified cpumode, try fallback to the other space
+              * to be robust against bad cpumode in samples.
+              */
+             if (cpumode == PERF_RECORD_MISC_KERNEL)
+                     effective_cpumode = PERF_RECORD_MISC_USER;
+             else if (cpumode == PERF_RECORD_MISC_USER)
+                     effective_cpumode = PERF_RECORD_MISC_KERNEL;
+             else if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL)
+                     effective_cpumode = PERF_RECORD_MISC_GUEST_USER;
+             else if (cpumode == PERF_RECORD_MISC_GUEST_USER)
+                     effective_cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+
+             if (!thread__find_map(aslr_thread, effective_cpumode, addr, &al)) {
+                     addr_location__exit(&al);
+                     return 0; /* No mmap. */
+             }
+     }
+
+     key.dso = map__dso(al.map);
+     key.invariant = map__start(al.map) - map__pgoff(al.map);
+     key.pid = effective_cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;
+
+     if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+             remap_addr = *remapped_invariant_ptr + map__pgoff(al.map) +
+                          (addr - map__start(al.map));
+     } else {
+             if (effective_cpumode == PERF_RECORD_MISC_KERNEL) {
+                     struct hashmap_entry *cur;
+                     size_t bkt;
+
+                     hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+                             struct remap_addresses_key *k;
+                             u64 *v;
+
+                             k = (struct remap_addresses_key *)cur->pkey;
+                             if (k->pid == kernel_pid &&
+                                 k->invariant == key.invariant) {
+                                     v = (u64 *)cur->pvalue;
+                                     remap_addr = *v + map__pgoff(al.map) +
+                                                  (addr - map__start(al.map));
+                                     break;
+                             }
+                     }
+             }
+             if (remap_addr == 0) {
+                     pr_debug("Cannot find a remapped entry for address %lx in mapping %lx(%lx) for pid=%d\n",
+                              addr, map__start(al.map), map__size(al.map), key.pid);
+             }
+     }
+
+     addr_location__exit(&al);
+     return remap_addr;
+}
+
+static u64 aslr_tool__remap_mapping(struct aslr_tool *aslr,
+                                 struct thread *aslr_thread,
+                                 u8 cpumode,
+                                 u64 start, u64 len, u64 pgoff)
+{
+     struct addr_location al;
+     struct addr_location prev_al;
+     struct remap_addresses_key key;
+     struct remap_addresses_key *new_key = NULL;
+     struct remap_addresses_key *old_key = NULL;
+     u64 remap_addr = 0;
+     u64 *remapped_invariant_ptr = NULL;
+     u64 *max_addr_ptr = NULL;
+     u64 *new_val = NULL;
+     u64 *new_max = NULL;
+     u64 *old_val = NULL;
+     u64 *old_val_remap = NULL;
+     bool is_contiguous = false;
+     bool first_mapping = false;
+     bool key_found = false;
+     int err;
+
+     if (!aslr_thread)
+             return 0; /* No thread. */
+
+     addr_location__init(&al);
+     if (thread__find_map(aslr_thread, cpumode, start, &al)) {
+             key.dso = map__dso(al.map);
+             key.invariant = map__start(al.map) - map__pgoff(al.map);
+     } else {
+             key.dso = NULL;
+             key.invariant = start - pgoff;
+     }
+     key.pid = cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;
+
+     if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+             remap_addr = *remapped_invariant_ptr + (al.map ? map__pgoff(al.map) : pgoff);
+             key_found = true;
+     } else {
+             addr_location__init(&prev_al);
+             if (thread__find_map(aslr_thread, cpumode, start - 1, &prev_al)) {
+                     if (map__start(prev_al.map) + map__size(prev_al.map) == start) {
+                             is_contiguous = true;
+                     } else {
+                             pr_debug("Previous mmap [%lx, %lx] overlaps current map [%lx, %lx]\n",
+                                      map__start(prev_al.map),
+                                      map__start(prev_al.map) + map__size(prev_al.map),
+                                      start, start+len);
+                     }
+             }
+             addr_location__exit(&prev_al);
+
+             if (!hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+                     first_mapping = true;
+                     remap_addr = (cpumode == PERF_RECORD_MISC_KERNEL ?
+                                   kernel_space_start : user_space_start);
+             } else {
+                     remap_addr = *max_addr_ptr;
+             }
+
+             remap_addr = round_up_to_page_size(remap_addr);
Quoted 8 lines

tools/perf/util/aslr.c line 255

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+             if (!is_contiguous && !first_mapping)
+                     remap_addr += page_size;
+
+             new_key = malloc(sizeof(*new_key));
+             new_val = malloc(sizeof(u64));

I think the value of hashmap can be passed as value if it's u64.. well on 64-bit systems.

Yeah, sashiko was complaining about 32-bit builds. I think we should diverge our hashmap implementation as using long for the key rather than s64 just causes this kind of silliness for us. I think we can also add generic support avoid errptrs, etc. I don't have hope of BPF people being sensible as in this series:
https://lore.kernel.org/linux-perf-users/[email protected]/

Quoted 70 lines
Quoted 70 lines
tools/perf/util/aslr.c new file +69 -0
+
+             if (!new_key || !new_val) {
+                     free(new_key);
+                     free(new_val);
+                     addr_location__exit(&al);
+                     return 0;
+             }
+             *new_key = key;
+             new_key->dso = dso__get(key.dso);
+             *new_val = remap_addr - (al.map ? map__pgoff(al.map) : pgoff);
+
+             if (hashmap__add(&aslr->remap_addresses, new_key, new_val) != 0) {
+                     dso__put(new_key->dso);
+                     free(new_key);
+                     free(new_val);
+                     addr_location__exit(&al);
+                     return 0;
+             }
+     }
+
+     /* Update top_addresses */
+     new_max = malloc(sizeof(u64));
+     old_val = NULL;
+
+     if (!new_max) {
+             old_key = NULL;
+             old_val_remap = NULL;
+
+             if (!key_found) {
+                     hashmap__delete(&aslr->remap_addresses, &key,
+                                     &old_key, &old_val_remap);
+                     if (old_key)
+                             dso__put(old_key->dso);
+                     free(old_key);
+                     free(old_val_remap);
+             }
+             addr_location__exit(&al);
+             return 0;
+     }
+     *new_max = remap_addr + len;
+
+     if (hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+             if (*max_addr_ptr > *new_max)
+                     *new_max = *max_addr_ptr;
+     }
+
+     err = hashmap__insert(&aslr->top_addresses, key.pid, new_max,
+                               (first_mapping && !key_found) ?
+                                     HASHMAP_ADD : HASHMAP_UPDATE,
+                               NULL, &old_val);
+     if (err) {
+             old_key = NULL;
+             old_val_remap = NULL;
+
+             free(new_max);
+             if (!key_found) {
+                     hashmap__delete(&aslr->remap_addresses, &key,
+                                     &old_key, &old_val_remap);
+                     if (old_key)
+                             dso__put(old_key->dso);
+                     free(old_key);
+                     free(old_val_remap);
+             }
+             addr_location__exit(&al);
+             return 0;
+     }
+     free(old_val);
+
+     addr_location__exit(&al);
Quoted 8 lines

tools/perf/util/aslr.c line 330

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+     return remap_addr;
+}
+
+static u64 aslr_tool__remap_ksymbol(struct aslr_tool *aslr,
+                                 struct thread *aslr_thread,
+                                 u64 addr, u32 len)

Any chance you can share the code with the above function?

I'll check.

Quoted 428 lines
Quoted 428 lines
tools/perf/util/aslr.c new file +428 -0
+{
+     struct addr_location al;
+     struct remap_addresses_key key;
+     struct hashmap_entry *cur;
+     struct remap_addresses_key *new_key = NULL;
+     struct remap_addresses_key *old_key = NULL;
+     struct remap_addresses_key *k;
+     size_t bkt;
+     u64 remap_addr = 0;
+     u64 *remapped_invariant_ptr = NULL;
+     u64 *max_addr_ptr = NULL;
+     u64 *new_val = NULL;
+     u64 *new_max = NULL;
+     u64 *old_val = NULL;
+     u64 *old_val_remap = NULL;
+     u64 *v;
+     bool first_mapping = false;
+     int err;
+
+     if (!aslr_thread)
+             return 0; /* No thread. */
+
+     addr_location__init(&al);
+     if (thread__find_map(aslr_thread, PERF_RECORD_MISC_KERNEL, addr, &al)) {
+             key.dso = map__dso(al.map);
+             key.invariant = map__start(al.map) - map__pgoff(al.map);
+     } else {
+             key.dso = NULL;
+             key.invariant = addr; /* pgoff is 0 for ksymbols */
+     }
+     key.pid = aslr_thread->pid_;
+
+     if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+             if (al.map)
+                     remap_addr = *remapped_invariant_ptr + map__pgoff(al.map) +
+                                  (addr - map__start(al.map));
+             else
+                     remap_addr = *remapped_invariant_ptr;
+             addr_location__exit(&al);
+             return remap_addr;
+     }
+
+     hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+             k = (struct remap_addresses_key *)cur->pkey;
+             if (k->pid == kernel_pid && k->invariant == key.invariant) {
+                     v = (u64 *)cur->pvalue;
+
+                     if (al.map)
+                             remap_addr = *v + map__pgoff(al.map) +
+                                          (addr - map__start(al.map));
+                     else
+                             remap_addr = *v;
+                     addr_location__exit(&al);
+                     return remap_addr;
+             }
+     }
+
+     if (!hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+             first_mapping = true;
+             remap_addr = kernel_space_start;
+     } else {
+             remap_addr = *max_addr_ptr;
+     }
+
+     remap_addr = round_up_to_page_size(remap_addr) + page_size;
+
+     new_key = malloc(sizeof(*new_key));
+     new_val = malloc(sizeof(u64));
+
+     if (!new_key || !new_val) {
+             free(new_key);
+             free(new_val);
+             addr_location__exit(&al);
+             return 0;
+     }
+     *new_key = key;
+     new_key->dso = dso__get(key.dso);
+     if (al.map)
+             *new_val = remap_addr - (addr - map__start(al.map)) - map__pgoff(al.map);
+     else
+             *new_val = remap_addr;
+
+     if (hashmap__add(&aslr->remap_addresses, new_key, new_val) < 0) {
+             dso__put(new_key->dso);
+             free(new_key);
+             free(new_val);
+             addr_location__exit(&al);
+             return 0;
+     }
+
+     new_max = malloc(sizeof(u64));
+     old_val = NULL;
+
+     if (!new_max) {
+             old_key = NULL;
+             old_val_remap = NULL;
+
+             hashmap__delete(&aslr->remap_addresses, &key, &old_key, &old_val_remap);
+             if (old_key)
+                     dso__put(old_key->dso);
+             free(old_key);
+             free(old_val_remap);
+             addr_location__exit(&al);
+             return 0;
+     }
+     *new_max = remap_addr + len;
+
+     if (hashmap__find(&aslr->top_addresses, key.pid, &max_addr_ptr)) {
+             if (*max_addr_ptr > *new_max)
+                     *new_max = *max_addr_ptr;
+     }
+
+     err = hashmap__insert(&aslr->top_addresses, key.pid, new_max,
+                               first_mapping ?
+                                     HASHMAP_ADD : HASHMAP_UPDATE,
+                               NULL, &old_val);
+     if (err) {
+             old_key = NULL;
+             old_val_remap = NULL;
+
+             free(new_max);
+             hashmap__delete(&aslr->remap_addresses, &key, &old_key, &old_val_remap);
+             if (old_key)
+                     dso__put(old_key->dso);
+             free(old_key);
+             free(old_val_remap);
+             addr_location__exit(&al);
+             return 0;
+     }
+     free(old_val);
+
+     addr_location__exit(&al);
+     return remap_addr;
+}
+
+
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     union perf_event *new_event;
+     u8 cpumode;
+     struct thread *thread;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     new_event = (union perf_event *)aslr->event_copy;
+     cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     /* Create the thread, map, etc. in the ASLR before virtual address space. */
+     err = perf_event__process_mmap(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     thread = machine__findnew_thread(aslr_machine, event->mmap.pid, event->mmap.tid);
+     if (!thread)
+             return -ENOMEM;
+     memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size);
+     /* Remaps the mmap.start. */
+     new_event->mmap.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+                                                        event->mmap.start,
+                                                        event->mmap.len,
+                                                        event->mmap.pgoff);
+     if (aslr->first_kernel_mapping && cpumode == PERF_RECORD_MISC_KERNEL) {
+             new_event->mmap.pgoff = new_event->mmap.start;
+             aslr->first_kernel_mapping = false;
+     }
+     err = delegate->mmap(delegate, new_event, sample, machine);
+     thread__put(thread);
+     return err;
+}
+
+static int aslr_tool__process_mmap2(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     union perf_event *new_event;
+     u8 cpumode;
+     struct thread *thread;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     new_event = (union perf_event *)aslr->event_copy;
+     cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     /* Create the thread, map, etc. in the ASLR before virtual address space. */
+     err = perf_event__process_mmap2(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     thread = machine__findnew_thread(aslr_machine, event->mmap2.pid, event->mmap2.tid);
+     if (!thread)
+             return -ENOMEM;
+     memcpy(&new_event->mmap2, &event->mmap2, event->mmap2.header.size);
+     /* Remaps the mmap.start. */
+     new_event->mmap2.start = aslr_tool__remap_mapping(aslr, thread, cpumode,
+                                                        event->mmap2.start,
+                                                        event->mmap2.len,
+                                                        event->mmap2.pgoff);
+     if (aslr->first_kernel_mapping && cpumode == PERF_RECORD_MISC_KERNEL) {
+             new_event->mmap2.pgoff = new_event->mmap2.start;
+             aslr->first_kernel_mapping = false;
+     }
+     err = delegate->mmap2(delegate, new_event, sample, machine);
+     thread__put(thread);
+     return err;
+}
+
+static int aslr_tool__process_comm(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     /* Create the thread, map, etc. in the ASLR before virtual address space. */
+     err = perf_event__process_comm(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     return delegate->comm(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_fork(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     /* Create the thread, map, etc. in the ASLR before virtual address space. */
+     err = perf_event__process_fork(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     return delegate->fork(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_exit(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     /* Create the thread, map, etc. in the ASLR before virtual address space. */
+     err = perf_event__process_exit(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     return delegate->exit(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_text_poke(const struct perf_tool *tool,
+                                     union perf_event *event,
+                                     struct perf_sample *sample,
+                                     struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     union perf_event *new_event;
+     u8 cpumode;
+     struct thread *thread;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     new_event = (union perf_event *)aslr->event_copy;
+     cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     thread = machine__findnew_thread(aslr_machine, sample->pid, sample->tid);
+     if (!thread)
+             return -ENOMEM;
+     memcpy(&new_event->text_poke, &event->text_poke, event->text_poke.header.size);
+     new_event->text_poke.addr = aslr_tool__remap_address(aslr, thread, cpumode,
+                                                          event->text_poke.addr);
+
+     err = delegate->text_poke(delegate, new_event, sample, machine);
+
+     thread__put(thread);
+     return err;
+}
+
+static int aslr_tool__process_ksymbol(const struct perf_tool *tool,
+                             union perf_event *event,
+                             struct perf_sample *sample,
+                             struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     union perf_event *new_event;
+     struct thread *thread;
+     struct machine *aslr_machine;
+     int err;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     new_event = (union perf_event *)aslr->event_copy;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     err = perf_event__process_ksymbol(tool, event, sample, aslr_machine);
+     if (err)
+             return err;
+
+     thread = machine__findnew_thread(aslr_machine, kernel_pid, 0);
+     if (!thread)
+             return -ENOMEM;
+     memcpy(&new_event->ksymbol, &event->ksymbol, event->ksymbol.header.size);
+     /* Remaps the ksymbol.start */
+     new_event->ksymbol.addr = aslr_tool__remap_ksymbol(aslr, thread,
+                                                        event->ksymbol.addr, event->ksymbol.len);
+
+     err = delegate->ksymbol(delegate, new_event, sample, machine);
+     thread__put(thread);
+     return err;
+}
+
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+                             struct perf_sample *sample,
+                             struct evsel *evsel, struct machine *machine)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     int ret;
+     u64 sample_type;
+     struct thread *thread;
+     struct machine *aslr_machine;
+     __u64 max_i;
+     __u64 max_j;
+     union perf_event *new_event;
+     struct perf_sample new_sample;
+     __u64 *in_array, *out_array;
+     u8 cpumode;
+     u64 addr;
+     size_t i;
+     size_t j;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     ret = -EFAULT;
+     sample_type = evsel->core.attr.sample_type;
+     max_i = (event->header.size - sizeof(struct perf_event_header)) / sizeof(__u64);
+     max_j = (PERF_SAMPLE_MAX_SIZE - sizeof(struct perf_event_header)) / sizeof(__u64);
+     new_event = (union perf_event *)aslr->event_copy;
+     cpumode = sample->cpumode;
+     i = 0;
+     j = 0;
+
+     aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+     if (!aslr_machine)
+             return -ENOMEM;
+
+     thread = machine__findnew_thread(aslr_machine, sample->pid, sample->tid);
+
+     if (!thread)
+             return -ENOMEM;
Quoted 8 lines

tools/perf/util/aslr.c line 764

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+
+     if (max_i > PERF_SAMPLE_MAX_SIZE / sizeof(u64))
+             goto out_put;
+
+
+

Excessive blank lines.

Ack.

Quoted 195 lines
Quoted 195 lines
tools/perf/util/aslr.c new file +195 -0
+     new_event->sample.header = event->sample.header;
+
+     in_array = &event->sample.array[0];
+     out_array = &new_event->sample.array[0];
+
+#define CHECK_BOUNDS(required_i, required_j) \
+     do { \
+             if (i + (required_i) > max_i || j + (required_j) > max_j) { \
+                     ret = -EFAULT; \
+                     goto out_put; \
+             } \
+     } while (0)
+
+#define COPY_U64() \
+     do { \
+             CHECK_BOUNDS(1, 1); \
+             out_array[j++] = in_array[i++]; \
+     } while (0)
+
+#define REMAP_U64(addr_field) \
+     do { \
+             CHECK_BOUNDS(1, 1); \
+             out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr_field); \
+             i++; \
+     } while (0)
+
+     if (sample_type & PERF_SAMPLE_IDENTIFIER)
+             COPY_U64(); /* id */
+     if (sample_type & PERF_SAMPLE_IP)
+             REMAP_U64(sample->ip);
+     if (sample_type & PERF_SAMPLE_TID)
+             COPY_U64(); /* pid, tid */
+     if (sample_type & PERF_SAMPLE_TIME)
+             COPY_U64(); /* time */
+     if (sample_type & PERF_SAMPLE_ADDR)
+             REMAP_U64(sample->addr);
+     if (sample_type & PERF_SAMPLE_ID)
+             COPY_U64(); /* id */
+     if (sample_type & PERF_SAMPLE_STREAM_ID)
+             COPY_U64(); /* stream_id */
+     if (sample_type & PERF_SAMPLE_CPU)
+             COPY_U64(); /* cpu, res */
+     if (sample_type & PERF_SAMPLE_PERIOD)
+             COPY_U64(); /* period */
+     if (sample_type & PERF_SAMPLE_READ) {
+             if ((evsel->core.attr.read_format & PERF_FORMAT_GROUP) == 0) {
+                     COPY_U64(); /* value */
+                     if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+                             COPY_U64(); /* time_enabled */
+                     if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+                             COPY_U64(); /* time_running */
+                     if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+                             COPY_U64(); /* id */
+                     if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+                             COPY_U64(); /* lost */
+             } else {
+                     u64 nr;
+
+                     CHECK_BOUNDS(1, 1);
+                     nr = out_array[j++] = in_array[i++];
+                     if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+                             COPY_U64(); /* time_enabled */
+                     if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+                             COPY_U64(); /* time_running */
+                     for (u64 cntr = 0; cntr < nr; cntr++) {
+                             COPY_U64(); /* value */
+                             if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+                                     COPY_U64(); /* id */
+                             if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+                                     COPY_U64(); /* lost */
+                     }
+             }
+     }
+     if (sample_type & PERF_SAMPLE_CALLCHAIN) {
+             u64 nr;
+
+             CHECK_BOUNDS(1, 1);
+             nr = out_array[j++] = in_array[i++];
+
+             for (u64 cntr = 0; cntr < nr; cntr++) {
+                     CHECK_BOUNDS(1, 1);
+                     addr = in_array[i++];
+                     if (addr >= PERF_CONTEXT_MAX) {
+                             out_array[j++] = addr;
+                             switch (addr) {
+                             case PERF_CONTEXT_HV:
+                                     cpumode = PERF_RECORD_MISC_HYPERVISOR;
+                                     break;
+                             case PERF_CONTEXT_KERNEL:
+                                     cpumode = PERF_RECORD_MISC_KERNEL;
+                                     break;
+                             case PERF_CONTEXT_USER:
+                                     cpumode = PERF_RECORD_MISC_USER;
+                                     break;
+                             case PERF_CONTEXT_GUEST:
+                                     cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+                                     break;
+                             case PERF_CONTEXT_GUEST_KERNEL:
+                                     cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+                                     break;
+                             case PERF_CONTEXT_GUEST_USER:
+                                     cpumode = PERF_RECORD_MISC_GUEST_USER;
+                                     break;
+                             case PERF_CONTEXT_USER_DEFERRED:
+                                     /*
+                                      * Immediately followed by a 64-bit
+                                      * stitching cookie. Skip/Copy it!
+                                      */
+                                     CHECK_BOUNDS(1, 1);
+                                     out_array[j++] = in_array[i++];
+                                     cntr++;
+                                     break;
+                             default:
+                                     pr_debug("invalid callchain context: %"PRIx64"\n", addr);
+                                     ret = 0;
+                                     goto out_put;
+                             }
+                             continue;
+                     }
+                     out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr);
+             }
+     }
+     if (sample_type & PERF_SAMPLE_RAW) {
+             size_t bytes = sizeof(u32) + sample->raw_size;
+             size_t u64_words = (bytes + 7) / 8;
+
+             if (i + u64_words > max_i || j + u64_words > max_j) {
+                     ret = -EFAULT;
+                     goto out_put;
+             }
+             memcpy(&out_array[j], &in_array[i], bytes);
+             i += u64_words;
+             j += u64_words;
+             /*
+              * TODO: certain raw samples can be remapped, such as
+              * tracepoints by examining their fields.
+              */
+             pr_debug("Dropping raw samples as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;
+     }
+     if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
+             u64 nr;
+
+             CHECK_BOUNDS(1, 1);
+             nr = out_array[j++] = in_array[i++];
+
+             if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)
+                     COPY_U64(); /* hw_idx */
+
+             if (nr > (ULLONG_MAX / 3)) {
+                     ret = -EFAULT;
+                     goto out_put;
+             }
+             if (nr * 3 > max_i - i || nr * 3 > max_j - j) {
+                     ret = -EFAULT;
+                     goto out_put;
+             }
+             for (u64 cntr = 0; cntr < nr; cntr++) {
+                     out_array[j++] = aslr_tool__remap_address(aslr, thread,
+                                                               sample->cpumode,
+                                                               in_array[i++]); /* from */
+                     out_array[j++] = aslr_tool__remap_address(aslr, thread,
+                                                               sample->cpumode,
+                                                               in_array[i++]); /* to */
+                     out_array[j++] = in_array[i++]; /* flags */
+             }
+             if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) {
+                     if (nr > max_i - i || nr > max_j - j) {
+                             ret = -EFAULT;
+                             goto out_put;
+                     }
+                     memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+                     i += nr;
+                     j += nr;
+                     /* TODO: confirm branch counters don't leak ASLR information. */
+                     pr_debug("Dropping sample branch counters as possible ASLR leak\n");
+                     ret = 0;
+                     goto out_put;
+             }
+     }
+     if (sample_type & PERF_SAMPLE_REGS_USER) {
+             u64 abi;
+
+             COPY_U64(); /* abi */
+             abi = out_array[j-1];
+             if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+                     u64 nr = hweight64(evsel->core.attr.sample_regs_user);
+
+                     if (nr > max_i - i || nr > max_j - j) {
+                             ret = -EFAULT;
+                             goto out_put;
+                     }
+                     memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+                     i += nr;
Quoted 8 lines

tools/perf/util/aslr.c line 965

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+                     j += nr;
+             }
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping regs user sample as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;

Is this mean you drop samples if it contains registers?

Yep, as noted by the TODO.

Quoted 91 lines
Quoted 91 lines
tools/perf/util/aslr.c new file +90 -0
+     }
+     if (sample_type & PERF_SAMPLE_STACK_USER) {
+             u64 size;
+
+             CHECK_BOUNDS(1, 1);
+             size = out_array[j++] = in_array[i++];
+             if (size > 0) {
+                     size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+                     if (u64_words > max_i - i || u64_words > max_j - j) {
+                             ret = -EFAULT;
+                             goto out_put;
+                     }
+                     memcpy(&out_array[j], &in_array[i], size);
+                     if (size % 8) {
+                             size_t pad = 8 - (size % 8);
+
+                             memset(((char *)&out_array[j]) + size, 0, pad);
+                     }
+                     i += u64_words;
+                     j += u64_words;
+
+                     COPY_U64(); /* dyn_size */
+             }
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping stack user sample as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;
+     }
+     if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
+             COPY_U64(); /* perf_sample_weight */
+     if (sample_type & PERF_SAMPLE_DATA_SRC)
+             COPY_U64(); /* data_src */
+     if (sample_type & PERF_SAMPLE_TRANSACTION)
+             COPY_U64(); /* transaction */
+     if (sample_type & PERF_SAMPLE_REGS_INTR) {
+             u64 abi;
+
+             COPY_U64(); /* abi */
+             abi = out_array[j-1];
+             if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+                     u64 nr = hweight64(evsel->core.attr.sample_regs_intr);
+
+                     if (nr > max_i - i || nr > max_j - j) {
+                             ret = -EFAULT;
+                             goto out_put;
+                     }
+                     memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+                     i += nr;
+                     j += nr;
+             }
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping interrupt register sample as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;
+     }
+     if (sample_type & PERF_SAMPLE_PHYS_ADDR) {
+             COPY_U64(); /* phys_addr */
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping physical address sample as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;
+     }
+     if (sample_type & PERF_SAMPLE_CGROUP)
+             COPY_U64(); /* cgroup */
+     if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
+             COPY_U64(); /* data_page_size */
+     if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
+             COPY_U64(); /* code_page_size */
+
+     if (sample_type & PERF_SAMPLE_AUX) {
+             u64 size;
+
+             CHECK_BOUNDS(1, 1);
+             size = out_array[j++] = in_array[i++];
+             if (size > 0) {
+                     size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+                     if (u64_words > max_i - i || u64_words > max_j - j) {
+                             ret = -EFAULT;
+                             goto out_put;
+                     }
+                     memcpy(&out_array[j], &in_array[i], size);
+                     if (size % 8) {
+                             size_t pad = 8 - (size % 8);
+
+                             memset(((char *)&out_array[j]) + size, 0, pad);
+                     }
+                     i += u64_words;
+                     j += u64_words;
Quoted 8 lines

tools/perf/util/aslr.c line 1061

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+             }
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping aux sample as possible ASLR leak\n");
+             ret = 0;
+             goto out_put;
+     }

Can you use perf_event__synthesize_sample()?

I'd prefer not to as I think working field by field is worthwhile in convincing ourselves of a lack of ASLR leaks. Punting this into perf_sample and synthesis opens up gaps for bugs to be introduced.

Quoted 6 lines

tools/perf/util/aslr.c line 1065

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+
+     if (evsel__is_offcpu_event(evsel)) {
+             /* TODO: can this be less conservative? */
+             pr_debug("Dropping off-CPU sample as possible ASLR leak\n");

Why not remap the address?

No reason, but support wasn't a first priority, hence the TODO.

Thanks,
Ian

Quoted 177 lines

Thanks,
Namhyung

Quoted 174 lines
tools/perf/util/aslr.c new file +155 -0
+             ret = 0;
+             goto out_put;
+     }
+
+     new_event->sample.header.size = sizeof(struct perf_event_header) + j * sizeof(u64);
+
+     perf_sample__init(&new_sample, /*all=*/ true);
+     ret = evsel__parse_sample(evsel, new_event, &new_sample);
+     if (ret) {
+             perf_sample__exit(&new_sample);
+             goto out_put;
+     }
+
+     ret = delegate->sample(delegate, new_event, &new_sample, evsel, machine);
+     perf_sample__exit(&new_sample);
+
+out_put:
+     thread__put(thread);
+     return ret;
+}
+
+#undef CHECK_BOUNDS
+#undef COPY_U64
+#undef REMAP_U64
+
+
+static int aslr_tool__process_attr(const struct perf_tool *tool,
+                                union perf_event *event,
+                                struct evlist **pevlist)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct perf_tool *delegate;
+     union perf_event *new_event;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+     delegate = aslr->tool.delegate;
+     new_event = (union perf_event *)aslr->event_copy;
+
+     memcpy(&new_event->attr, &event->attr, event->attr.header.size);
+     if (new_event->attr.attr.type == PERF_TYPE_BREAKPOINT)
+             new_event->attr.attr.bp_addr = 0;  /* Conservatively remove addresses. */
+
+     return delegate->attr(delegate, new_event, pevlist);
+}
+
+static s64 aslr_tool__process_auxtrace(const struct perf_tool *tool __maybe_unused,
+                                    struct perf_session *session,
+                                    union perf_event *event)
+{
+     if (perf_data__is_pipe(session->data)) {
+             int err = skipn(perf_data__fd(session->data), event->auxtrace.size);
+
+             if (err < 0)
+                     return err;
+     }
+     return event->auxtrace.size;
+}
+
+static int aslr_tool__process_auxtrace_info(const struct perf_tool *tool __maybe_unused,
+                                         struct perf_session *session __maybe_unused,
+                                         union perf_event *event __maybe_unused)
+{
+     return 0;
+}
+
+static int aslr_tool__process_auxtrace_error(const struct perf_tool *tool __maybe_unused,
+                                          struct perf_session *session __maybe_unused,
+                                          union perf_event *event __maybe_unused)
+{
+     return 0;
+}
+
+static void aslr_tool__init(struct aslr_tool *aslr, struct perf_tool *delegate)
+{
+     delegate_tool__init(&aslr->tool, delegate);
+     aslr->tool.tool.ordered_events = true;
+
+     machines__init(&aslr->machines);
+
+     hashmap__init(&aslr->remap_addresses,
+                   remap_addresses__hash, remap_addresses__equal,
+                   /*ctx=*/NULL);
+     hashmap__init(&aslr->top_addresses,
+                   top_addresses__hash, top_addresses__equal,
+                   /*ctx=*/NULL);
+     aslr->first_kernel_mapping = true;
+
+     aslr->tool.tool.sample  = aslr_tool__process_sample;
+     /* read - reads a counter, okay to delegate. */
+     aslr->tool.tool.mmap    = aslr_tool__process_mmap;
+     aslr->tool.tool.mmap2   = aslr_tool__process_mmap2;
+     aslr->tool.tool.comm    = aslr_tool__process_comm;
+     aslr->tool.tool.fork    = aslr_tool__process_fork;
+     aslr->tool.tool.exit    = aslr_tool__process_exit;
+     /* namesspaces, cgroup, lost, lost_sample, aux, */
+     /* itrace_start, aux_output_hw_id, context_switch, throttle, unthrottle */
+     /* - no virtual addresses. */
+     aslr->tool.tool.ksymbol = aslr_tool__process_ksymbol;
+     /* bpf - no virtual address. */
+     aslr->tool.tool.text_poke = aslr_tool__process_text_poke;
+     aslr->tool.tool.attr = aslr_tool__process_attr;
+     /* event_update, tracing_data, finished_round, build_id, id_index, */
+     /* event_update, tracing_data, finished_round, build_id, id_index, */
+     /* auxtrace_info, auxtrace_error, time_conv, thread_map, cpu_map, */
+     /* stat_config, stat, feature, finished_init, bpf_metadata, compressed, */
+     /* auxtrace - no virtual addresses. */
+     aslr->tool.tool.auxtrace = aslr_tool__process_auxtrace;
+     aslr->tool.tool.auxtrace_info = aslr_tool__process_auxtrace_info;
+     aslr->tool.tool.auxtrace_error = aslr_tool__process_auxtrace_error;
+}
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate)
+{
+     struct aslr_tool *aslr = zalloc(sizeof(*aslr));
+
+     if (!aslr)
+             return NULL;
+
+     aslr_tool__init(aslr, delegate);
+     return &aslr->tool.tool;
+}
+
+void aslr_tool__delete(struct perf_tool *tool)
+{
+     struct delegate_tool *del_tool;
+     struct aslr_tool *aslr;
+     struct hashmap_entry *cur;
+     size_t bkt;
+
+     if (!tool)
+             return;
+
+     del_tool = container_of(tool, struct delegate_tool, tool);
+     aslr = container_of(del_tool, struct aslr_tool, tool);
+
+     hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+             struct remap_addresses_key *key = (struct remap_addresses_key *)cur->pkey;
+
+             if (key)
+                     dso__put(key->dso);
+             zfree(&cur->pkey);
+             zfree(&cur->pvalue);
+     }
+     hashmap__for_each_entry(&aslr->top_addresses, cur, bkt) {
+             zfree(&cur->pvalue);
+     }
+
+     hashmap__clear(&aslr->remap_addresses);
+     hashmap__clear(&aslr->top_addresses);
+     machines__destroy_kernel_maps(&aslr->machines);
+     machines__exit(&aslr->machines);
+     free(aslr);
+}
tools/perf/util/aslr.h new file +10 -1
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
--

2.54.0.545.g6539524ca2-goog

author reviewer
#32 lore raw

PATCH v5 5/5 perf test: Add inject ASLR test

In reply to Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Harden test suite verification pipelines by upgrading report checks to
strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on
unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
 tools/perf/tests/shell/inject_aslr.sh | 459 ++++++++++++++++++++++++++
 1 file changed, 459 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +459 -0
new file mode 100755
index 000000000000..cdc3aa94de63
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.545.g6539524ca2-goog
reviewer
#33 lore raw

Re: [PATCH v5 5/5] perf test: Add inject ASLR test

Quoted 172 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Harden test suite verification pipelines by upgrading report checks to
strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on
unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
  tools/perf/tests/shell/inject_aslr.sh | 459 ++++++++++++++++++++++++++
  1 file changed, 459 insertions(+)

create mode 100755 tools/perf/tests/shell/inject_aslr.sh

tools/perf/tests/shell/inject_aslr.sh new file +125 -0
new file mode 100755
index 000000000000..cdc3aa94de63
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+

tools/perf/tests/shell/inject_aslr.sh line 135

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"

Hi Ian,

This test fails on Arm. I believe it's because on Arm we request the link register to be sampled with frame pointer unwinds. Then the aslr tool drops all the samples because it sees that user regs were sampled:

/* TODO: can this be less conservative? */ pr_debug("Dropping regs user sample as possible ASLR leak\n"); ret = 0;
goto out_put;

I think maybe that comment is onto something. Perhaps the user regs can be zeroed instead of dropping the sample. Then the frame pointer unwind will still work on Arm and the aslr test will pass. We just won't be able to use the link register to add the leaf frame caller, but that's not a big deal.

James

Quoted 324 lines
tools/perf/tests/shell/inject_aslr.sh new file +324 -0
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
author reviewer
#34 lore raw

Re: [PATCH v5 5/5] perf test: Add inject ASLR test

Quoted 198 lines · James Clark
Quoted 172 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Harden test suite verification pipelines by upgrading report checks to
strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on
unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
  tools/perf/tests/shell/inject_aslr.sh | 459 ++++++++++++++++++++++++++
  1 file changed, 459 insertions(+)

create mode 100755 tools/perf/tests/shell/inject_aslr.sh

tools/perf/tests/shell/inject_aslr.sh new file +125 -0
new file mode 100755
index 000000000000..cdc3aa94de63
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+

tools/perf/tests/shell/inject_aslr.sh line 135

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"

Hi Ian,

This test fails on Arm. I believe it's because on Arm we request the link register to be sampled with frame pointer unwinds. Then the aslr tool drops all the samples because it sees that user regs were sampled:

   /* TODO: can this be less conservative? */
   pr_debug("Dropping regs user sample as possible ASLR leak\n");
   ret = 0;
   goto out_put;
Quoted 5 lines

I think maybe that comment is onto something. Perhaps the user regs can be zeroed instead of dropping the sample. Then the frame pointer unwind will still work on Arm and the aslr test will pass. We just won't be able to use the link register to add the leaf frame caller, but that's not a big deal.

Thanks James. I'm working on a new version of the patches, but I'm having delays getting the AI to approve the changes.

ARM does what? Ah, I knew this and also it didn't really register. I'm wondering now if we can put the machinery behind "EM_HOST == EM_AARCH64":
https://lore.kernel.org/all/[email protected]/
as it seems a mechanism that would benefit other architectures such as ARM32 :-) And I have my mission to make tools/perf/arch disappear as much as is humanly possible.
I also imagine the problem the link register solves for perf happens for BPF, so perhaps this ability shouldn't be encouraged.

I think rather than zeroing the register values it would be better to just remove them from the output events. I'll try to add that support as having this test break on ARM isn't desirable.

Thanks,
Ian

Quoted 327 lines

James

Quoted 324 lines
tools/perf/tests/shell/inject_aslr.sh new file +324 -0
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
reviewer
#35 lore raw

Re: [PATCH v5 5/5] perf test: Add inject ASLR test

Quoted 208 lines · Ian Rogers
Quoted 198 lines · James Clark
Quoted 172 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Harden test suite verification pipelines by upgrading report checks to
strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on
unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty
data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
   tools/perf/tests/shell/inject_aslr.sh | 459 ++++++++++++++++++++++++++
   1 file changed, 459 insertions(+)

create mode 100755 tools/perf/tests/shell/inject_aslr.sh

tools/perf/tests/shell/inject_aslr.sh new file +125 -0
new file mode 100755
index 000000000000..cdc3aa94de63
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+

tools/perf/tests/shell/inject_aslr.sh line 135

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"

Hi Ian,

This test fails on Arm. I believe it's because on Arm we request the link register to be sampled with frame pointer unwinds. Then the aslr tool drops all the samples because it sees that user regs were sampled:

    /* TODO: can this be less conservative? */
    pr_debug("Dropping regs user sample as possible ASLR leak\n");
    ret = 0;
    goto out_put;
Quoted 5 lines

I think maybe that comment is onto something. Perhaps the user regs can be zeroed instead of dropping the sample. Then the frame pointer unwind will still work on Arm and the aslr test will pass. We just won't be able to use the link register to add the leaf frame caller, but that's not a big deal.

Thanks James. I'm working on a new version of the patches, but I'm having delays getting the AI to approve the changes.

Quoted 7 lines

ARM does what? Ah, I knew this and also it didn't really register. I'm wondering now if we can put the machinery behind "EM_HOST == EM_AARCH64":
https://lore.kernel.org/all/[email protected]/
as it seems a mechanism that would benefit other architectures such as ARM32 :-) And I have my mission to make tools/perf/arch disappear as much as is humanly possible.

Yeah that makes sense, the change you sent looks good.

Quoted 2 lines

I also imagine the problem the link register solves for perf happens for BPF, so perhaps this ability shouldn't be encouraged.

Not sure what you mean by this, do you mean adding the link register shoudln't be encouraged, or the compiler dropping the stack frame? Or just the weak function style?

Quoted 5 lines

I think rather than zeroing the register values it would be better to just remove them from the output events. I'll try to add that support as having this test break on ARM isn't desirable.

Makes sense too. I suppose data being there but zeroed could be slightly more confusing than just dropping the sample.

I don't know if modifying the sample type to remove PERF_SAMPLE_REGS_USER and emitting the rest could be an option? It might be more robust to cases when things are auto added to the sample by Perf. For example all the aux stuff has custom setup functions that add who knows what options to the events.

Quoted 330 lines

Thanks,
Ian

Quoted 327 lines

James

Quoted 324 lines
tools/perf/tests/shell/inject_aslr.sh new file +324 -0
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
reviewer
#36 lore raw

Re: [PATCH v5 5/5] perf test: Add inject ASLR test

Quoted 234 lines · James Clark
Quoted 215 lines · Ian Rogers
Quoted 205 lines · James Clark
Quoted 184 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject -- aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (skipping gracefully if permissions restrict recording the kernel map).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout
streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v5: Harden test suite verification pipelines by upgrading report checks to strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.
v4: Reorder set -e/pipefail to prevent temp file leakage in root directory on unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.
v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain empty data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.
v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.
---
   tools/perf/tests/shell/inject_aslr.sh | 459 +++++++++++++++++++++
+++++

   1 file changed, 459 insertions(+)

   create mode 100755 tools/perf/tests/shell/inject_aslr.sh

tools/perf/tests/shell/inject_aslr.sh new file +74 -0
new file mode 100755
index 000000000000..cdc3aa94de63
@@ -0,0 +1,459 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+
+
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original 

file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]" +    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]" +    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +11 -0
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf 

inject --aslr -o "${data2}"

tools/perf/tests/shell/inject_aslr.sh new file +8 -0
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original 

file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]" +    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]" +    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +19 -0
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in 
Quoted 5 lines

original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"

Hi Ian,

This test fails on Arm. I believe it's because on Arm we request the link register to be sampled with frame pointer unwinds. Then the aslr tool drops all the samples because it sees that user regs were sampled:

    /* TODO: can this be less conservative? */ pr_debug("Dropping regs user sample as possible ASLR leak\n"); ret = 0;
    goto out_put;

Quoted 5 lines

I think maybe that comment is onto something. Perhaps the user regs can be zeroed instead of dropping the sample. Then the frame pointer unwind will still work on Arm and the aslr test will pass. We just won't be able to use the link register to add the leaf frame caller, but that's not a big deal.

Thanks James. I'm working on a new version of the patches, but I'm having delays getting the AI to approve the changes.

Quoted 7 lines

ARM does what? Ah, I knew this and also it didn't really register. I'm wondering now if we can put the machinery behind "EM_HOST == EM_AARCH64":
https://lore.kernel.org/all/[email protected]/
as it seems a mechanism that would benefit other architectures such as ARM32 :-) And I have my mission to make tools/perf/arch disappear as much as is humanly possible.

Yeah that makes sense, the change you sent looks good.

Quoted 2 lines

I also imagine the problem the link register solves for perf happens for BPF, so perhaps this ability shouldn't be encouraged.

Not sure what you mean by this, do you mean adding the link register shoudln't be encouraged, or the compiler dropping the stack frame? Or just the weak function style?

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

I think rather than zeroing the register values it would be better to just remove them from the output events. I'll try to add that support as having this test break on ARM isn't desirable.

Makes sense too. I suppose data being there but zeroed could be slightly more confusing than just dropping the sample.

I don't know if modifying the sample type to remove PERF_SAMPLE_REGS_USER and emitting the rest could be an option? It might be more robust to cases when things are auto added to the sample by Perf. For example all the aux stuff has custom setup functions that add who knows what options to the events.

Nevermind, I see this is what is done on V6

Quoted 367 lines
Quoted 366 lines

Thanks,
Ian

Quoted 361 lines

James

Quoted 358 lines

+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]" +    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/ ^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/ ^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]" +      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +13 -0
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing 

in both
+  perf inject -b -i "${data}" -o "${data_clean}" +  perf inject -v -b --aslr -i "${data}" -o "${data2}"

tools/perf/tests/shell/inject_aslr.sh new file +12 -0
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" 
|| true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" 
|| true

+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true

tools/perf/tests/shell/inject_aslr.sh new file +24 -0
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with 

inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"

tools/perf/tests/shell/inject_aslr.sh new file +12 -0
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" 
|| true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" 
|| true

+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true

tools/perf/tests/shell/inject_aslr.sh new file +32 -0
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - -- 

stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}"

|| true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" 
|| true

+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true

tools/perf/tests/shell/inject_aslr.sh new file +23 -0
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- 

sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +33 -0
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > 

"${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +5 -0
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the 

next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')

tools/perf/tests/shell/inject_aslr.sh new file +5 -0
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original 

file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]" +    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]" +    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi

tools/perf/tests/shell/inject_aslr.sh new file +15 -0
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${prog} > 

"${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"

tools/perf/tests/shell/inject_aslr.sh new file +15 -0
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or 

kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report1_norm}" || true +  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | sort > "${report2_norm}" || true +
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true

tools/perf/tests/shell/inject_aslr.sh new file +26 -0
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
author reviewer
#37 lore raw

v6 cover perf tools: Add inject --aslr feature and prerequisite robustness fixes

In reply to Ian Rogers

This patch series introduces the new 'perf inject --aslr' feature to remap virtual memory addresses or drop physical memory event leaks when profile record data is shared between machines. Bundled with this feature are three independent, critical bug fixes inside core event dispatching and map tracking tools that harden perf session analysis against dynamic crashes, concurrent lookup data races, and callchain mapping failures.

Core Feature: 'perf inject --aslr' (Patches 4, 5, and 6)

Transferring perf.data files across environments introduces a potential leak of virtual address footprints, weakening Address Space Layout Randomization (ASLR) on the originating machine. To mitigate this, we introduce the --aslr flag into perf inject. Unknown or unhandled events are dropped conservatively, while handled samples and branch loops undergo systematic virtual memory offset obfuscation.

Events carrying virtual memory layouts are conservatively remap-processed or dropped, while zero-address-risk lifecycle metadata records (such as namespaces, cgroups, and BPF program info) are intentionally delegated to preserve comprehensive downstream trace tool analysis compatibility.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory space layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs. The topological invariant coordinate dso + invariant (start - pgoff) is tracked to uniquely index binary section frameworks, providing complete collision safety against separate overlapping shared-invariant libraries while remaining perfectly immune to boundary shifts or split fragmentations.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, completely drops PERF_RECORD_TEXT_POKE events to prevent absolute immediate pointer operands leaks, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames).

Verification is reinforced in Patch 5 with a comprehensive POSIX shell suite ('inject_aslr.sh'), hardened against SIGPIPE signal exits with stream consuming awk loops and robust 'set -o pipefail' assertions. The suite utilizes a highly dense, system-call intensive VFS byte block loop workload (dd count=500) to guarantee deterministic hardware timer interrupts sampling streams inside kernel privilege states.

Prerequisite Bug Fixes (Patches 1, 2, and 3)

During development, three core event delegation and map indexing issues were identified and resolved to prevent crashes, live-locks, and data-loss during analysis:

1. perf sched: 'timehist' registers standard MMAP, COMM, EXIT, and FORK stubs, but completely omitted registering MMAP2 callbacks. Because modern environments output maps primarily via MMAP2 frames, this caused timehist sessions to silently drop shared library mappings, causing dynamic callchain symbol resolutions to fail. Patch 1 corrects this by properly registering perf_event__process_mmap2.

2. perf tool: Patch 2 fixes missing copies of schedstat callbacks inside delegated wrapper tools (which caused segfaults on NULL stubs) and properly initializes/copies the 'dont_split_sample_group' grouping parameters to prevent stack garbage from triggering silent non-leader events drops during split deliver streams.

3. perf symbols: Patch 3 replaces old remove-reinsert map boundary update cycles with a high-performance, thread-safe transactional framework maps__mutate_mapping() that enforces write semaphore lock closures around all in-place virtual address mutations and sorting invalidations, completely closing concurrent lookup race condition windows. It explicitly executes DWARF address space cache invalidation (libdw__invalidate_dwfl()) to keep debugger unwinding frames perfectly synchronized.

Changes since v5:

- Core Concurrency Fix (Patch 3): Refactor map address boundary mutations across ELF loaders, proc kallsyms parsers, and dynamic module managers to utilize a thread-safe, synchronized transactional framework maps__mutate_mapping() that encapsulates mutations and sorting invalidations under write lock closures, eliminating concurrent lookup race condition windows. Cites intention-revealing callbacks names (remap_kernel_cb).

- Feature Exclusivity (Patch 4): Inject strict command-line validation checks enforcing mutual exclusivity between --aslr and --convert-callchain to prevent silent trace unwind failures since ASLR stack dropping conflicts directly with DWARF parsing needs.

- KASLR Hardening (Patch 4): Secure mmap.pgoff unconditionally for all host and guest kernel text mapping regions to prevent unredacted active KASLR base deltas leakage.

- TEXT_POKE Drops (Patch 4): Conservatively drop PERF_RECORD_TEXT_POKE events completely via a local static drop stub to prevent unredacted absolute 64-bit kernel virtual pointer immediate operands leakage.

- Parsing Invariants (Patch 4): Inject explicit array-end bounds validation check blocks before consuming trailing PERF_CONTEXT_USER_DEFERRED callchain cookies to completely eliminate out-of-bounds reads and parser desynchronization faults.

- Commit Records Alignment (Patch 4): Precisely clarify commit descriptions to reflect that zero-address metadata events are intentionally delegated to protect downstream trace tool processing backward compatibility.

- Telemetry Stabilization (Patch 5): Upgrade kernel space tracking workloads to utilize a dedicated system-call intensive VFS byte block loop workload (dd count=500) instead of purely userspace-bound tight loops, guaranteeing high-density kernel privilege state sampling streams and eliminating intermittent execution flakiness dropouts.

- Profile Retention Optimizer (Patch 6): Refactor sample processor to dynamically strip out ONLY register dump words out of sample payloads while shrinking output header sizes, overwriting ABI words to NONE, and scrubbing attributes up front. This completely rescues trace profiles from complete sample drop starvation, which happened by default on ARM64.

Ian Rogers (6):
perf sched: Add missing mmap2 handler in timehist
perf tool: Missing delegate_tool schedstat delegates and
dont_split_sample_group
perf maps: Add maps__mutate_mapping
perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses perf test: Add inject ASLR test
perf aslr: Strip sample registers

 tools/perf/builtin-inject.c           |   47 +-
 tools/perf/builtin-sched.c            |    1 +
 tools/perf/tests/shell/inject_aslr.sh |  511 ++++++++++++
 tools/perf/util/Build                 |    1 +
 tools/perf/util/aslr.c                | 1035 +++++++++++++++++++++++++
 tools/perf/util/aslr.h                |   10 +
 tools/perf/util/machine.c             |   32 +-
 tools/perf/util/maps.c                |   26 +
 tools/perf/util/maps.h                |    2 +
 tools/perf/util/symbol-elf.c          |   41 +-
 tools/perf/util/symbol.c              |   17 +-
 tools/perf/util/tool.c                |    6 +
 12 files changed, 1697 insertions(+), 32 deletions(-)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author reviewer
#38 lore raw

PATCH v6 1/6 perf sched: Add missing mmap2 handler in timehist

perf_sched__timehist() registers event handlers for options using the sched->tool struct. It registers handlers for MMAP, COMM, EXIT, FORK, etc. but completely omits registering a handler for MMAP2 events.

Failing to register both MMAP and MMAP2 handlers causes modern systems (which primarily output MMAP2 records) to silently drop VMA map mappings. This results in uninitialized machine/thread mapping structures, making it impossible to resolve shared library instruction pointers (IPs) to dynamic symbols/DSOs during timehist callchain analysis.

Fix this by correctly registering perf_event__process_mmap2 in sched->tool inside perf_sched__timehist().

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 49394a2a24c78ce0 ("perf sched timehist: Introduce timehist command")
---
 tools/perf/builtin-sched.c | 1 +
 1 file changed, 1 insertion(+)
tools/perf/builtin-sched.c +1 -0
index 555247568e7a..241c2f808f7b 100644
@@ -3299,6 +3299,7 @@ static int perf_sched__timehist(struct perf_sched *sched)
 	 */
 	sched->tool.sample	 = perf_timehist__process_sample;
 	sched->tool.mmap	 = perf_event__process_mmap;
+	sched->tool.mmap2	 = perf_event__process_mmap2;
 	sched->tool.comm	 = perf_event__process_comm;
 	sched->tool.exit	 = perf_event__process_exit;
 	sched->tool.fork	 = perf_event__process_fork;
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author reviewer
#39 lore raw

PATCH v6 2/6 perf tool: Missing delegate_tool schedstat delegates and dont_split_sample_group

In reply to Ian Rogers

delegate_tool was missing the delegate overrides for schedstat_cpu and schedstat_domain. As a result, when allocated with zalloc, these callbacks defaulted to NULL, causing a segmentation fault crash if any schedstat events were delivered during event processing. Fix this by adding delegate_schedstat_cpu and delegate_schedstat_domain via the CREATE_DELEGATE_OP2 macro, and ensuring delegate_tool__init correctly registers them.

Additionally, delegate_tool__init completely omitted copying the dont_split_sample_group property from the delegate. This would cause wrapper tools to default the flag to false, which corrupts piped event processing (e.g., in perf inject) by triggering duplicate event deliveries on split sample values in deliver_sample_group().

Similarly, perf_tool__init() omitted the initialization of this boolean field. On stack-allocated tools that rely on this initializer (like intel-tpebs or __cmd_evlist), this could result in uninitialized stack garbage evaluating to true—silently dropping non-leader event members in deliver_sample_group().

Fix both issues by properly copying the field in delegate_tool__init and initializing it to false in perf_tool__init.

Assisted-by Gemini-CLI:Google Gemini 3
Fixes 6331b2669359 ("perf tool: Add a delegate_tool that just delegates actions to another tool")
Fixes 79bcd34e0f3d ("perf inject: Fix leader sampling inserting additional samples")
---
 tools/perf/util/tool.c | 6 ++++++
 1 file changed, 6 insertions(+)
tools/perf/util/tool.c +6 -0
index 013c7839e2cf..ff2150517b75 100644
@@ -285,6 +285,7 @@ void perf_tool__init(struct perf_tool *tool, bool ordered_events)
 	tool->no_warn = false;
 	tool->show_feat_hdr = SHOW_FEAT_NO_HEADER;
 	tool->merge_deferred_callchains = true;
+	tool->dont_split_sample_group = false;
 
 	tool->sample = process_event_sample_stub;
 	tool->mmap = process_event_stub;
@@ -433,6 +434,8 @@ CREATE_DELEGATE_OP2(stat_config);
 CREATE_DELEGATE_OP2(stat_round);
 CREATE_DELEGATE_OP2(thread_map);
 CREATE_DELEGATE_OP2(time_conv);
+CREATE_DELEGATE_OP2(schedstat_cpu);
+CREATE_DELEGATE_OP2(schedstat_domain);
 CREATE_DELEGATE_OP2(tracing_data);
 
 #define CREATE_DELEGATE_OP3(name)					\
@@ -470,6 +473,7 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.no_warn = delegate->no_warn;
 	tool->tool.show_feat_hdr = delegate->show_feat_hdr;
 	tool->tool.merge_deferred_callchains = delegate->merge_deferred_callchains;
+	tool->tool.dont_split_sample_group = delegate->dont_split_sample_group;
 
 	tool->tool.sample = delegate_sample;
 	tool->tool.read = delegate_read;
@@ -516,4 +520,6 @@ void delegate_tool__init(struct delegate_tool *tool, struct perf_tool *delegate)
 	tool->tool.bpf_metadata = delegate_bpf_metadata;
 	tool->tool.compressed = delegate_compressed;
 	tool->tool.auxtrace = delegate_auxtrace;
+	tool->tool.schedstat_cpu = delegate_schedstat_cpu;
+	tool->tool.schedstat_domain = delegate_schedstat_domain;
 }
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author reviewer
#40 lore raw

PATCH v6 3/6 perf maps: Add maps__mutate_mapping

In reply to Ian Rogers

During kernel ELF symbol parsing (dso__process_kernel_symbol), proc kallsyms image loading (dso__load_kernel_sym, dso__load_guest_kernel_sym), and dynamic kernel memory map alignment updates (machine__update_kernel_mmap), the loader directly modifies live virtual address boundary keys fields on map objects. If these boundaries are mutated while the map pointer actively resides inside the parent maps cache array list (kmaps) outside of any lock closure, an unsafe concurrent window is exposed where parallel worker lookup threads (e.g., inside perf top) can mistakenly assume the cache remains sorted based on stale parameters, executing binary search queries (bsearch) across an unsorted range and triggering lookups failure.

Fix this by introducing a thread-safe, atomic transactional framework routine maps__mutate_mapping() that explicitly acquires the parent maps write semaphore lock, executes an incoming mutation callback block to perform the field updates under full lock protection, and invalidates the sorted tracking flags prior to releasing the write lock. This guarantees absolute atomic synchronization invariants, completely closing the concurrent lookup race window. The adjacent module alignment pass inside machine__create_kernel_maps() is safely preserved as a high-performance lockless pass, as its invocation lifecycle bounds remain strictly single-threaded by contract during session initialization construction. There is a potential for self deadlock if maps__mutate_mapping is called with the lock held, such as with maps__for_each_map but this problem also existed with the previous remove and insert approaches.

Fixes 39b12f781271 ("perf tools: Make it possible to read object code from vmlinux")
---
 tools/perf/util/machine.c    | 32 +++++++++++++++++-----------
 tools/perf/util/maps.c       | 26 +++++++++++++++++++++++
 tools/perf/util/maps.h       |  2 ++
 tools/perf/util/symbol-elf.c | 41 +++++++++++++++++++++++-------------
 tools/perf/util/symbol.c     | 17 +++++++++++----
 5 files changed, 87 insertions(+), 31 deletions(-)
tools/perf/util/machine.c +20 -12
index e76f8c86e62a..8d4452c70cb5 100644
@@ -1522,22 +1522,30 @@ static void machine__set_kernel_mmap(struct machine *machine,
 		map__set_end(machine->vmlinux_map, ~0ULL);
 }
 
-static int machine__update_kernel_mmap(struct machine *machine,
-				     u64 start, u64 end)
+struct kernel_mmap_mutation_ctx {
+	u64 start;
+	u64 end;
+};
+
+static int kernel_mmap_mutate_cb(struct map *map, void *data)
 {
-	struct map *orig, *updated;
-	int err;
+	struct kernel_mmap_mutation_ctx *ctx = data;
 
-	orig = machine->vmlinux_map;
-	updated = map__get(orig);
+	map__set_start(map, ctx->start);
+	map__set_end(map, ctx->end);
+	if (ctx->start == 0 && ctx->end == 0)
+		map__set_end(map, ~0ULL);
+	return 0;
+}
 
-	machine->vmlinux_map = updated;
-	maps__remove(machine__kernel_maps(machine), orig);
-	machine__set_kernel_mmap(machine, start, end);
-	err = maps__insert(machine__kernel_maps(machine), updated);
-	map__put(orig);
+static int machine__update_kernel_mmap(struct machine *machine,
+				     u64 start, u64 end)
+{
+	struct kernel_mmap_mutation_ctx ctx = { .start = start, .end = end };
 
-	return err;
+	return maps__mutate_mapping(machine__kernel_maps(machine),
+				     machine->vmlinux_map,
+				     kernel_mmap_mutate_cb, &ctx);
 }
 
 int machine__create_kernel_maps(struct machine *machine)
tools/perf/util/maps.c +26 -0
index 81a97ac34077..91345a773aa2 100644
@@ -575,6 +575,32 @@ void maps__remove(struct maps *maps, struct map *map)
 #endif
 }
 
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data)
+{
+	int err = 0;
+
+	if (maps)
+		down_write(maps__lock(maps));
+
+	err = mutate_cb(map, data);
+
+	if (maps) {
+		RC_CHK_ACCESS(maps)->maps_by_address_sorted = false;
+		RC_CHK_ACCESS(maps)->maps_by_name_sorted = false;
+	}
+
+	if (maps)
+		up_write(maps__lock(maps));
+
+#ifdef HAVE_LIBDW_SUPPORT
+	if (maps)
+		libdw__invalidate_dwfl(maps, maps__libdw_addr_space_dwfl(maps));
+#endif
+
+	return err;
+}
+
 bool maps__empty(struct maps *maps)
 {
 	bool res;
tools/perf/util/maps.h +2 -0
index 20c52084ba9e..de74ccbb8a12 100644
@@ -61,6 +61,8 @@ size_t maps__fprintf(struct maps *maps, FILE *fp);
 
 int maps__insert(struct maps *maps, struct map *map);
 void maps__remove(struct maps *maps, struct map *map);
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data);
 
 struct map *maps__find(struct maps *maps, u64 addr);
 struct symbol *maps__find_symbol(struct maps *maps, u64 addr, struct map **mapp);
tools/perf/util/symbol-elf.c +26 -15

54 lines not on this page · raw message

tools/perf/util/symbol.c +13 -4
index fcaeeddbbb6b..09b93e844887 100644
@@ -48,6 +48,13 @@
 #include <symbol/kallsyms.h>
 #include <sys/utsname.h>
 
+static int map_fixup_cb(struct map *map, void *data __maybe_unused)
+{
+	map__fixup_start(map);
+	map__fixup_end(map);
+	return 0;
+}
+
 static int dso__load_kernel_sym(struct dso *dso, struct map *map);
 static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map);
 static bool symbol__is_idle(const char *name);
@@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 	free(kallsyms_allocated_filename);
 
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
 		dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
 	}
 
 	return err;
@@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
 	if (err > 0)
 		pr_debug("Using %s for symbols\n", kallsyms_filename);
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS);
 		dso__set_long_name(dso, machine->mmap_name, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
 	}
 
 	return err;
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
reviewer
#41 lore raw

Re: [PATCH v6 3/6] perf maps: Add maps__mutate_mapping

Quoted 92 lines · Ian Rogers

During kernel ELF symbol parsing (dso__process_kernel_symbol), proc kallsyms image loading (dso__load_kernel_sym, dso__load_guest_kernel_sym), and dynamic kernel memory map alignment updates (machine__update_kernel_mmap), the loader directly modifies live virtual address boundary keys fields on map objects. If these boundaries are mutated while the map pointer actively resides inside the parent maps cache array list (kmaps) outside of any lock closure, an unsafe concurrent window is exposed where parallel worker lookup threads (e.g., inside perf top) can mistakenly assume the cache remains sorted based on stale parameters, executing binary search queries (bsearch) across an unsorted range and triggering lookups failure.

Fix this by introducing a thread-safe, atomic transactional framework routine maps__mutate_mapping() that explicitly acquires the parent maps write semaphore lock, executes an incoming mutation callback block to perform the field updates under full lock protection, and invalidates the sorted tracking flags prior to releasing the write lock. This guarantees absolute atomic synchronization invariants, completely closing the concurrent lookup race window. The adjacent module alignment pass inside machine__create_kernel_maps() is safely preserved as a high-performance lockless pass, as its invocation lifecycle bounds remain strictly single-threaded by contract during session initialization construction. There is a potential for self deadlock if maps__mutate_mapping is called with the lock held, such as with maps__for_each_map but this problem also existed with the previous remove and insert approaches.

Fixes 39b12f781271 ("perf tools: Make it possible to read object code from vmlinux")
---
  tools/perf/util/machine.c    | 32 +++++++++++++++++-----------
  tools/perf/util/maps.c       | 26 +++++++++++++++++++++++
  tools/perf/util/maps.h       |  2 ++
  tools/perf/util/symbol-elf.c | 41 +++++++++++++++++++++++-------------
  tools/perf/util/symbol.c     | 17 +++++++++++----
  5 files changed, 87 insertions(+), 31 deletions(-)
tools/perf/util/machine.c +20 -12
index e76f8c86e62a..8d4452c70cb5 100644
@@ -1522,22 +1522,30 @@ static void machine__set_kernel_mmap(struct machine *machine,
  		map__set_end(machine->vmlinux_map, ~0ULL);
  }
 
-static int machine__update_kernel_mmap(struct machine *machine,
-				     u64 start, u64 end)
+struct kernel_mmap_mutation_ctx {
+	u64 start;
+	u64 end;
+};
+
+static int kernel_mmap_mutate_cb(struct map *map, void *data)
  {
-	struct map *orig, *updated;
-	int err;
+	struct kernel_mmap_mutation_ctx *ctx = data;
 
-	orig = machine->vmlinux_map;
-	updated = map__get(orig);
+	map__set_start(map, ctx->start);
+	map__set_end(map, ctx->end);
+	if (ctx->start == 0 && ctx->end == 0)
+		map__set_end(map, ~0ULL);
+	return 0;
+}
 
-	machine->vmlinux_map = updated;
-	maps__remove(machine__kernel_maps(machine), orig);
-	machine__set_kernel_mmap(machine, start, end);
-	err = maps__insert(machine__kernel_maps(machine), updated);
-	map__put(orig);
+static int machine__update_kernel_mmap(struct machine *machine,
+				     u64 start, u64 end)
+{
+	struct kernel_mmap_mutation_ctx ctx = { .start = start, .end = end };
 
-	return err;
+	return maps__mutate_mapping(machine__kernel_maps(machine),
+				     machine->vmlinux_map,
+				     kernel_mmap_mutate_cb, &ctx);
  }
 
  int machine__create_kernel_maps(struct machine *machine)
tools/perf/util/maps.c +0 -0
index 81a97ac34077..91345a773aa2 100644
@@ -575,6 +575,32 @@ void maps__remove(struct maps *maps, struct map *map)
  #endif
  }

tools/perf/util/maps.c void maps__remove(struct maps *maps, struct map *map) · line 586

Quoted 10 lines
tools/perf/util/maps.c +9 -0
 
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data)
+{
+	int err = 0;
+
+	if (maps)
+		down_write(maps__lock(maps));
+
+	err = mutate_cb(map, data);

Hi Ian,

I get this error when building with LLVM=1 on Ubuntu clang version 18.1.8 (11~20.04.2):

util/maps.c:586:8: error: mutex 'maps__lock(maps)' is not held on every path through here [-Werror,-Wthread-safety-analysis]
586 | err = mutate_cb(map, data);
| ^
util/maps.c:584:3: note: mutex acquired here

  584 |                 down_write(maps__lock(maps));
      |                 ^
util/maps.c:594:3: error: releasing mutex 'maps__lock(maps)' that was not held [-Werror,-Wthread-safety-analysis]
  594 |                 up_write(maps__lock(maps));
      |                 ^

2 errors generated.

Quoted 139 lines
tools/perf/util/maps.c +17 -0
+
+	if (maps) {
+		RC_CHK_ACCESS(maps)->maps_by_address_sorted = false;
+		RC_CHK_ACCESS(maps)->maps_by_name_sorted = false;
+	}
+
+	if (maps)
+		up_write(maps__lock(maps));
+
+#ifdef HAVE_LIBDW_SUPPORT
+	if (maps)
+		libdw__invalidate_dwfl(maps, maps__libdw_addr_space_dwfl(maps));
+#endif
+
+	return err;
+}
+
  bool maps__empty(struct maps *maps)
  {
  	bool res;
tools/perf/util/maps.h +2 -0
index 20c52084ba9e..de74ccbb8a12 100644
@@ -61,6 +61,8 @@ size_t maps__fprintf(struct maps *maps, FILE *fp);
 
  int maps__insert(struct maps *maps, struct map *map);
  void maps__remove(struct maps *maps, struct map *map);
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data);
 
  struct map *maps__find(struct maps *maps, u64 addr);
  struct symbol *maps__find_symbol(struct maps *maps, u64 addr, struct map **mapp);
tools/perf/util/symbol-elf.c +26 -15
index 7afa8a117139..dc4ab58857b3 100644
@@ -1341,6 +1341,24 @@ static u64 ref_reloc(struct kmap *kmap)
  void __weak arch__sym_update(struct symbol *s __maybe_unused,
  		GElf_Sym *sym __maybe_unused) { }
 
+struct remap_kernel_ctx {
+	u64 sh_addr;
+	u64 sh_size;
+	u64 sh_offset;
+	struct kmap *kmap;
+};
+
+static int remap_kernel_cb(struct map *map, void *data)
+{
+	struct remap_kernel_ctx *ctx = data;
+
+	map__set_start(map, ctx->sh_addr + ref_reloc(ctx->kmap));
+	map__set_end(map, map__start(map) + ctx->sh_size);
+	map__set_pgoff(map, ctx->sh_offset);
+	map__set_mapping_type(map, MAPPING_TYPE__DSO);
+	return 0;
+}
+
  static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
  				      GElf_Sym *sym, GElf_Shdr *shdr,
  				      struct maps *kmaps, struct kmap *kmap,
@@ -1371,22 +1389,15 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
  		 * map to the kernel dso.
  		 */
  		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
+			struct remap_kernel_ctx ctx = {
+				.sh_addr = shdr->sh_addr,
+				.sh_size = shdr->sh_size,
+				.sh_offset = shdr->sh_offset,
+				.kmap = kmap
+			};
+
  			*remap_kernel = false;
-			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
-			map__set_end(map, map__start(map) + shdr->sh_size);
-			map__set_pgoff(map, shdr->sh_offset);
-			map__set_mapping_type(map, MAPPING_TYPE__DSO);
-			/* Ensure maps are correctly ordered */
-			if (kmaps) {
-				int err;
-				struct map *tmp = map__get(map);
-
-				maps__remove(kmaps, map);
-				err = maps__insert(kmaps, map);
-				map__put(tmp);
-				if (err)
-					return err;
-			}
+			maps__mutate_mapping(kmaps, map, remap_kernel_cb, &ctx);
  		}
 
  		/*
tools/perf/util/symbol.c +13 -4
index fcaeeddbbb6b..09b93e844887 100644
@@ -48,6 +48,13 @@
  #include <symbol/kallsyms.h>
  #include <sys/utsname.h>
 
+static int map_fixup_cb(struct map *map, void *data __maybe_unused)
+{
+	map__fixup_start(map);
+	map__fixup_end(map);
+	return 0;
+}
+
  static int dso__load_kernel_sym(struct dso *dso, struct map *map);
  static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map);
  static bool symbol__is_idle(const char *name);
@@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
  	free(kallsyms_allocated_filename);
 
  	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
  		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
  		dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
  	}
 
  	return err;
@@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
  	if (err > 0)
  		pr_debug("Using %s for symbols\n", kallsyms_filename);
  	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
  		dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS);
  		dso__set_long_name(dso, machine->mmap_name, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
  	}
 
  	return err;
#42 lore raw

Re: [PATCH v6 3/6] perf maps: Add maps__mutate_mapping

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Self-deadlock in the kallsyms symbol loading path. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Self-deadlock in the kallsyms symbol loading path.
--

commit 1340dc1c4b3b633e8a032536f0c7948f87b17ce3
Author: Ian Rogers <[email protected]>

perf maps: Add maps__mutate_mapping

This commit introduces maps__mutate_mapping to safely update map boundaries by acquiring a write lock on the maps collection. It applies this new synchronization to kernel ELF parsing, kallsyms image loading, and dynamic memory map updates to close concurrent lookup races.

Quoted 3 lines

There is a potential for self deadlock if maps__mutate_mapping is called with the lock held, such as with maps__for_each_map but this problem also existed with the previous remove and insert approaches.

Is this commit message accurate for all modified paths? Prior to this patch, dso__load_kernel_sym and dso__load_guest_kernel_sym used map__fixup_start and map__fixup_end directly without locking.

Quoted 4 lines
tools/perf/util/symbol.c +0 -0
index fcaeeddbbb6b9..09b93e844887d 100644

[ ... ]

tools/perf/util/symbol.c static int dso__load_kernel_sym(struct dso *dso, struct map *map) · line 2135

Quoted 11 lines
tools/perf/util/symbol.c +3 -2
@@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 	free(kallsyms_allocated_filename);
 
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
 		dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);

Can this cause a self-deadlock when resolving kernel symbols by name?

If a tool resolves a symbol upon first load, the call chain appears to hold a read lock while attempting to acquire a write lock on the exact same maps collection:

maps__find_symbol_by_name()
maps__for_each_map() <-- acquires read lock

    maps__find_symbol_by_name_cb()
      map__load()
        dso__load_kernel_sym()
          maps__mutate_mapping()        <-- attempts to acquire write lock

Since rw_semaphore cannot be upgraded from read to write without releasing the read lock first, won't this immediately deadlock on the kmaps lock?

Quoted 3 lines
tools/perf/util/symbol.c +0 -0
 	}
 
 	return err;

[ ... ]

tools/perf/util/symbol.c static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map) · line 2179

Quoted 11 lines
tools/perf/util/symbol.c +3 -2
@@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
 	if (err > 0)
 		pr_debug("Using %s for symbols\n", kallsyms_filename);
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS);
 		dso__set_long_name(dso, machine->mmap_name, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);

Does this guest kernel symbol loading path suffer from the exact same self-deadlock sequence?

Quoted 3 lines
tools/perf/util/symbol.c +0 -0
 	}
 
 	return err;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
maintainer
#43 lore raw

Re: [PATCH v6 3/6] perf maps: Add maps__mutate_mapping

In reply to Ian Rogers
Quoted 108 lines · Ian Rogers

During kernel ELF symbol parsing (dso__process_kernel_symbol), proc kallsyms image loading (dso__load_kernel_sym, dso__load_guest_kernel_sym), and dynamic kernel memory map alignment updates (machine__update_kernel_mmap), the loader directly modifies live virtual address boundary keys fields on map objects. If these boundaries are mutated while the map pointer actively resides inside the parent maps cache array list (kmaps) outside of any lock closure, an unsafe concurrent window is exposed where parallel worker lookup threads (e.g., inside perf top) can mistakenly assume the cache remains sorted based on stale parameters, executing binary search queries (bsearch) across an unsorted range and triggering lookups failure.

Fix this by introducing a thread-safe, atomic transactional framework routine maps__mutate_mapping() that explicitly acquires the parent maps write semaphore lock, executes an incoming mutation callback block to perform the field updates under full lock protection, and invalidates the sorted tracking flags prior to releasing the write lock. This guarantees absolute atomic synchronization invariants, completely closing the concurrent lookup race window. The adjacent module alignment pass inside machine__create_kernel_maps() is safely preserved as a high-performance lockless pass, as its invocation lifecycle bounds remain strictly single-threaded by contract during session initialization construction. There is a potential for self deadlock if maps__mutate_mapping is called with the lock held, such as with maps__for_each_map but this problem also existed with the previous remove and insert approaches.

Fixes 39b12f781271 ("perf tools: Make it possible to read object code from vmlinux")
---
 tools/perf/util/machine.c    | 32 +++++++++++++++++-----------
 tools/perf/util/maps.c       | 26 +++++++++++++++++++++++
 tools/perf/util/maps.h       |  2 ++
 tools/perf/util/symbol-elf.c | 41 +++++++++++++++++++++++-------------
 tools/perf/util/symbol.c     | 17 +++++++++++----
 5 files changed, 87 insertions(+), 31 deletions(-)
tools/perf/util/machine.c +20 -12
index e76f8c86e62a..8d4452c70cb5 100644
@@ -1522,22 +1522,30 @@ static void machine__set_kernel_mmap(struct machine *machine,
 		map__set_end(machine->vmlinux_map, ~0ULL);
 }
 
-static int machine__update_kernel_mmap(struct machine *machine,
-				     u64 start, u64 end)
+struct kernel_mmap_mutation_ctx {
+	u64 start;
+	u64 end;
+};
+
+static int kernel_mmap_mutate_cb(struct map *map, void *data)
 {
-	struct map *orig, *updated;
-	int err;
+	struct kernel_mmap_mutation_ctx *ctx = data;
 
-	orig = machine->vmlinux_map;
-	updated = map__get(orig);
+	map__set_start(map, ctx->start);
+	map__set_end(map, ctx->end);
+	if (ctx->start == 0 && ctx->end == 0)
+		map__set_end(map, ~0ULL);
+	return 0;
+}
 
-	machine->vmlinux_map = updated;
-	maps__remove(machine__kernel_maps(machine), orig);
-	machine__set_kernel_mmap(machine, start, end);
-	err = maps__insert(machine__kernel_maps(machine), updated);
-	map__put(orig);
+static int machine__update_kernel_mmap(struct machine *machine,
+				     u64 start, u64 end)
+{
+	struct kernel_mmap_mutation_ctx ctx = { .start = start, .end = end };
 
-	return err;
+	return maps__mutate_mapping(machine__kernel_maps(machine),
+				     machine->vmlinux_map,
+				     kernel_mmap_mutate_cb, &ctx);
 }
 
 int machine__create_kernel_maps(struct machine *machine)
tools/perf/util/maps.c +15 -0
index 81a97ac34077..91345a773aa2 100644
@@ -575,6 +575,32 @@ void maps__remove(struct maps *maps, struct map *map)
 #endif
 }
 
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data)
+{
+	int err = 0;
+
+	if (maps)
+		down_write(maps__lock(maps));
+
+	err = mutate_cb(map, data);
+
+	if (maps) {
+		RC_CHK_ACCESS(maps)->maps_by_address_sorted = false;
+		RC_CHK_ACCESS(maps)->maps_by_name_sorted = false;
+	}
+

tools/perf/util/maps.c void maps__remove(struct maps *maps, struct map *map) · line 602

Quoted 10 lines
tools/perf/util/maps.c +10 -0
+	if (maps)
+		up_write(maps__lock(maps));
+
+#ifdef HAVE_LIBDW_SUPPORT
+	if (maps)
+		libdw__invalidate_dwfl(maps, maps__libdw_addr_space_dwfl(maps));
+#endif
+
+	return err;
+}

Could be simplified by checking 'maps' once. But I'm not sure if there's a case it doesn't have the maps.

Thanks,
Namhyung

Quoted 126 lines
tools/perf/util/maps.c +1 -0
+
 bool maps__empty(struct maps *maps)
 {
 	bool res;
tools/perf/util/maps.h +2 -0
index 20c52084ba9e..de74ccbb8a12 100644
@@ -61,6 +61,8 @@ size_t maps__fprintf(struct maps *maps, FILE *fp);
 
 int maps__insert(struct maps *maps, struct map *map);
 void maps__remove(struct maps *maps, struct map *map);
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data);
 
 struct map *maps__find(struct maps *maps, u64 addr);
 struct symbol *maps__find_symbol(struct maps *maps, u64 addr, struct map **mapp);
tools/perf/util/symbol-elf.c +26 -15
index 7afa8a117139..dc4ab58857b3 100644
@@ -1341,6 +1341,24 @@ static u64 ref_reloc(struct kmap *kmap)
 void __weak arch__sym_update(struct symbol *s __maybe_unused,
 		GElf_Sym *sym __maybe_unused) { }
 
+struct remap_kernel_ctx {
+	u64 sh_addr;
+	u64 sh_size;
+	u64 sh_offset;
+	struct kmap *kmap;
+};
+
+static int remap_kernel_cb(struct map *map, void *data)
+{
+	struct remap_kernel_ctx *ctx = data;
+
+	map__set_start(map, ctx->sh_addr + ref_reloc(ctx->kmap));
+	map__set_end(map, map__start(map) + ctx->sh_size);
+	map__set_pgoff(map, ctx->sh_offset);
+	map__set_mapping_type(map, MAPPING_TYPE__DSO);
+	return 0;
+}
+
 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
 				      GElf_Sym *sym, GElf_Shdr *shdr,
 				      struct maps *kmaps, struct kmap *kmap,
@@ -1371,22 +1389,15 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
 		 * map to the kernel dso.
 		 */
 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
+			struct remap_kernel_ctx ctx = {
+				.sh_addr = shdr->sh_addr,
+				.sh_size = shdr->sh_size,
+				.sh_offset = shdr->sh_offset,
+				.kmap = kmap
+			};
+
 			*remap_kernel = false;
-			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
-			map__set_end(map, map__start(map) + shdr->sh_size);
-			map__set_pgoff(map, shdr->sh_offset);
-			map__set_mapping_type(map, MAPPING_TYPE__DSO);
-			/* Ensure maps are correctly ordered */
-			if (kmaps) {
-				int err;
-				struct map *tmp = map__get(map);
-
-				maps__remove(kmaps, map);
-				err = maps__insert(kmaps, map);
-				map__put(tmp);
-				if (err)
-					return err;
-			}
+			maps__mutate_mapping(kmaps, map, remap_kernel_cb, &ctx);
 		}
 
 		/*
tools/perf/util/symbol.c +13 -4
index fcaeeddbbb6b..09b93e844887 100644
@@ -48,6 +48,13 @@
 #include <symbol/kallsyms.h>
 #include <sys/utsname.h>
 
+static int map_fixup_cb(struct map *map, void *data __maybe_unused)
+{
+	map__fixup_start(map);
+	map__fixup_end(map);
+	return 0;
+}
+
 static int dso__load_kernel_sym(struct dso *dso, struct map *map);
 static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map);
 static bool symbol__is_idle(const char *name);
@@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 	free(kallsyms_allocated_filename);
 
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
 		dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
 	}
 
 	return err;
@@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
 	if (err > 0)
 		pr_debug("Using %s for symbols\n", kallsyms_filename);
 	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS);
 		dso__set_long_name(dso, machine->mmap_name, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
 	}
 
 	return err;
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
reviewer
#44 lore raw

Re: [PATCH v6 3/6] perf maps: Add maps__mutate_mapping

Quoted 123 lines · Namhyung Kim
Quoted 108 lines · Ian Rogers

During kernel ELF symbol parsing (dso__process_kernel_symbol), proc kallsyms image loading (dso__load_kernel_sym, dso__load_guest_kernel_sym), and dynamic kernel memory map alignment updates (machine__update_kernel_mmap), the loader directly modifies live virtual address boundary keys fields on map objects. If these boundaries are mutated while the map pointer actively resides inside the parent maps cache array list (kmaps) outside of any lock closure, an unsafe concurrent window is exposed where parallel worker lookup threads (e.g., inside perf top) can mistakenly assume the cache remains sorted based on stale parameters, executing binary search queries (bsearch) across an unsorted range and triggering lookups failure.

Fix this by introducing a thread-safe, atomic transactional framework routine maps__mutate_mapping() that explicitly acquires the parent maps write semaphore lock, executes an incoming mutation callback block to perform the field updates under full lock protection, and invalidates the sorted tracking flags prior to releasing the write lock. This guarantees absolute atomic synchronization invariants, completely closing the concurrent lookup race window. The adjacent module alignment pass inside machine__create_kernel_maps() is safely preserved as a high-performance lockless pass, as its invocation lifecycle bounds remain strictly single-threaded by contract during session initialization construction. There is a potential for self deadlock if maps__mutate_mapping is called with the lock held, such as with maps__for_each_map but this problem also existed with the previous remove and insert approaches.

Fixes 39b12f781271 ("perf tools: Make it possible to read object code from vmlinux")
---
  tools/perf/util/machine.c    | 32 +++++++++++++++++-----------
  tools/perf/util/maps.c       | 26 +++++++++++++++++++++++
  tools/perf/util/maps.h       |  2 ++
  tools/perf/util/symbol-elf.c | 41 +++++++++++++++++++++++-------------
  tools/perf/util/symbol.c     | 17 +++++++++++----
  5 files changed, 87 insertions(+), 31 deletions(-)
tools/perf/util/machine.c +20 -12
index e76f8c86e62a..8d4452c70cb5 100644
@@ -1522,22 +1522,30 @@ static void machine__set_kernel_mmap(struct machine *machine,
  		map__set_end(machine->vmlinux_map, ~0ULL);
  }
 
-static int machine__update_kernel_mmap(struct machine *machine,
-				     u64 start, u64 end)
+struct kernel_mmap_mutation_ctx {
+	u64 start;
+	u64 end;
+};
+
+static int kernel_mmap_mutate_cb(struct map *map, void *data)
  {
-	struct map *orig, *updated;
-	int err;
+	struct kernel_mmap_mutation_ctx *ctx = data;
 
-	orig = machine->vmlinux_map;
-	updated = map__get(orig);
+	map__set_start(map, ctx->start);
+	map__set_end(map, ctx->end);
+	if (ctx->start == 0 && ctx->end == 0)
+		map__set_end(map, ~0ULL);
+	return 0;
+}
 
-	machine->vmlinux_map = updated;
-	maps__remove(machine__kernel_maps(machine), orig);
-	machine__set_kernel_mmap(machine, start, end);
-	err = maps__insert(machine__kernel_maps(machine), updated);
-	map__put(orig);
+static int machine__update_kernel_mmap(struct machine *machine,
+				     u64 start, u64 end)
+{
+	struct kernel_mmap_mutation_ctx ctx = { .start = start, .end = end };
 
-	return err;
+	return maps__mutate_mapping(machine__kernel_maps(machine),
+				     machine->vmlinux_map,
+				     kernel_mmap_mutate_cb, &ctx);
  }
 
  int machine__create_kernel_maps(struct machine *machine)
tools/perf/util/maps.c +15 -0
index 81a97ac34077..91345a773aa2 100644
@@ -575,6 +575,32 @@ void maps__remove(struct maps *maps, struct map *map)
  #endif
  }
 
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data)
+{
+	int err = 0;
+
+	if (maps)
+		down_write(maps__lock(maps));
+
+	err = mutate_cb(map, data);
+
+	if (maps) {
+		RC_CHK_ACCESS(maps)->maps_by_address_sorted = false;
+		RC_CHK_ACCESS(maps)->maps_by_name_sorted = false;
+	}
+

tools/perf/util/maps.c void maps__remove(struct maps *maps, struct map *map) · line 602

Quoted 10 lines
tools/perf/util/maps.c +10 -0
+	if (maps)
+		up_write(maps__lock(maps));
+
+#ifdef HAVE_LIBDW_SUPPORT
+	if (maps)
+		libdw__invalidate_dwfl(maps, maps__libdw_addr_space_dwfl(maps));
+#endif
+
+	return err;
+}

Could be simplified by checking 'maps' once. But I'm not sure if there's a case it doesn't have the maps.

Quoted 3 lines

Thanks,
Namhyung

Hi Ian,

The multiple maps checks after mutate_cb() still seem to be in V19.

I noticed because I still get the -Wthread-safety-analysis error on x86 clang 15. Not sure why the compiler isn't able to see that maps doesn't change, and no amount of re-arranging made it go away. The only way to fix it is to have the lock and unlock in the same block, but I don't think it looks bad:

	if (maps) {
		down_write(maps__lock(maps));

		err = mutate_cb(map, data);

		RC_CHK_ACCESS(maps)->maps_by_address_sorted = false;
		RC_CHK_ACCESS(maps)->maps_by_name_sorted = false;

		up_write(maps__lock(maps));
	} else {
		err = mutate_cb(map, data);
	}

Thanks
James

Quoted 126 lines
Quoted 126 lines
tools/perf/util/maps.c +1 -0
+
  bool maps__empty(struct maps *maps)
  {
  	bool res;
tools/perf/util/maps.h +2 -0
index 20c52084ba9e..de74ccbb8a12 100644
@@ -61,6 +61,8 @@ size_t maps__fprintf(struct maps *maps, FILE *fp);
 
  int maps__insert(struct maps *maps, struct map *map);
  void maps__remove(struct maps *maps, struct map *map);
+int maps__mutate_mapping(struct maps *maps, struct map *map,
+			 int (*mutate_cb)(struct map *map, void *data), void *data);
 
  struct map *maps__find(struct maps *maps, u64 addr);
  struct symbol *maps__find_symbol(struct maps *maps, u64 addr, struct map **mapp);
tools/perf/util/symbol-elf.c +26 -15
index 7afa8a117139..dc4ab58857b3 100644
@@ -1341,6 +1341,24 @@ static u64 ref_reloc(struct kmap *kmap)
  void __weak arch__sym_update(struct symbol *s __maybe_unused,
  		GElf_Sym *sym __maybe_unused) { }
 
+struct remap_kernel_ctx {
+	u64 sh_addr;
+	u64 sh_size;
+	u64 sh_offset;
+	struct kmap *kmap;
+};
+
+static int remap_kernel_cb(struct map *map, void *data)
+{
+	struct remap_kernel_ctx *ctx = data;
+
+	map__set_start(map, ctx->sh_addr + ref_reloc(ctx->kmap));
+	map__set_end(map, map__start(map) + ctx->sh_size);
+	map__set_pgoff(map, ctx->sh_offset);
+	map__set_mapping_type(map, MAPPING_TYPE__DSO);
+	return 0;
+}
+
  static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
  				      GElf_Sym *sym, GElf_Shdr *shdr,
  				      struct maps *kmaps, struct kmap *kmap,
@@ -1371,22 +1389,15 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
  		 * map to the kernel dso.
  		 */
  		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
+			struct remap_kernel_ctx ctx = {
+				.sh_addr = shdr->sh_addr,
+				.sh_size = shdr->sh_size,
+				.sh_offset = shdr->sh_offset,
+				.kmap = kmap
+			};
+
  			*remap_kernel = false;
-			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
-			map__set_end(map, map__start(map) + shdr->sh_size);
-			map__set_pgoff(map, shdr->sh_offset);
-			map__set_mapping_type(map, MAPPING_TYPE__DSO);
-			/* Ensure maps are correctly ordered */
-			if (kmaps) {
-				int err;
-				struct map *tmp = map__get(map);
-
-				maps__remove(kmaps, map);
-				err = maps__insert(kmaps, map);
-				map__put(tmp);
-				if (err)
-					return err;
-			}
+			maps__mutate_mapping(kmaps, map, remap_kernel_cb, &ctx);
  		}
 
  		/*
tools/perf/util/symbol.c +13 -4
index fcaeeddbbb6b..09b93e844887 100644
@@ -48,6 +48,13 @@
  #include <symbol/kallsyms.h>
  #include <sys/utsname.h>
 
+static int map_fixup_cb(struct map *map, void *data __maybe_unused)
+{
+	map__fixup_start(map);
+	map__fixup_end(map);
+	return 0;
+}
+
  static int dso__load_kernel_sym(struct dso *dso, struct map *map);
  static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map);
  static bool symbol__is_idle(const char *name);
@@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
  	free(kallsyms_allocated_filename);
 
  	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
  		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
  		dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
  	}
 
  	return err;
@@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
  	if (err > 0)
  		pr_debug("Using %s for symbols\n", kallsyms_filename);
  	if (err > 0 && !dso__is_kcore(dso)) {
+		struct maps *kmaps = map__kmaps(map);
+
  		dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS);
  		dso__set_long_name(dso, machine->mmap_name, false);
-		map__fixup_start(map);
-		map__fixup_end(map);
+		maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL);
  	}
 
  	return err;
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author reviewer
#45 lore raw

PATCH v6 4/6 perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

In reply to Ian Rogers

If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

Events carrying virtual memory layouts are conservatively remap-processed or dropped, while zero-address-risk lifecycle metadata records (such as namespaces, cgroups, and BPF program info) are intentionally delegated to preserve comprehensive downstream trace tool analysis compatibility.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory space layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, completely drops PERF_RECORD_TEXT_POKE events to prevent absolute immediate pointer operands leaks, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames).

Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Enforce strict command-line validation mutual exclusivity between
--aslr and --convert-callchain to prevent silent unwind failures. Secure mmap.pgoff unconditionally for all host and guest kernel text mapping regions to completely prevent active KASLR load deltas leakage. Conservatively drop PERF_RECORD_TEXT_POKE events completely via a local static drop stub to prevent absolute 64-bit kernel virtual pointer immediate operands leaks. Inject explicit array-end bounds validation check blocks before consuming trailing PERF_CONTEXT_USER_DEFERRED callchain cookies to eliminate out-of-bounds reads and parser desynchronization faults. Simplify ASLR mapping remap logic. Ensure that encountering a PERF_CONTEXT_USER_DEFERRED context marker explicitly updates cpumode.

v5: Add machine to remap addresss key so that it is guest/host
safe. Add 'first_kernel_mapping' tracking guard inside aslr.c to rewrite the core kernel pgoff virtual address while safely protecting module file offsets from corruption. Clean up breakpoint address (bp_addr) memory scrubbing by executing the scrubbing loop directly at core session initialization startup level, natively securing both file headers and streaming pipe channels while removing redundant runtime tool wrapper interception hooks layers.

v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove
kernel mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.

v3: Combine split-map fixes, guest namespaces, bounds checks, OOM
rollbacks, hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.

v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   36 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1036 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1082 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +35 -1
index 6ab20df358c4..51dcf248b653 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;
@@ -304,6 +306,8 @@ static int perf_event__repipe(const struct perf_tool *tool,
 	return perf_event__repipe_synth(tool, event);
 }
 
+
+
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
 			    union perf_event *event __maybe_unused,
 			    struct perf_sample *sample __maybe_unused,
@@ -2459,6 +2463,8 @@ static int __cmd_inject(struct perf_inject *inject)
 			}
 		}
 
+
+
 		session->header.data_offset = output_data_offset;
 		session->header.data_size = inject->bytes_written;
 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2565,6 +2571,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2572,6 +2580,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2592,6 +2601,11 @@ int cmd_inject(int argc, const char **argv)
 	if (argc)
 		usage_with_options(inject_usage, options);
 
+	if (inject.aslr && inject.convert_callchain) {
+		pr_err("Error: --aslr and --convert-callchain are mutually exclusive features.\n");
+		return -EINVAL;
+	}
+
 	if (inject.strip && !inject.itrace_synth_opts.set) {
 		pr_err("--strip option requires --itrace option\n");
 		return -1;
@@ -2685,18 +2699,36 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
 	if (zstd_init(&(inject.session->zstd_data), 0) < 0)
 		pr_warning("Decompression initialization failed.\n");
 
+	if (inject.aslr) {
+		struct evsel *evsel;
+
+		evlist__for_each_entry(inject.session->evlist, evsel) {
+			if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+				evsel->core.attr.bp_addr = 0;
+		}
+	}
+
 	/* Save original section info before feature bits change */
 	ret = save_section_info(&inject);
 	if (ret)
@@ -2790,6 +2822,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +1036 -0

1,036 lines not on this page · raw message

tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
#46 lore raw
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The sample repacking logic silently drops unknown fields without clearing their corresponding UAPI…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The sample repacking logic silently drops unknown fields without clearing their corresponding UAPI presence flags, corrupting downstream parsing.
- [High] Missing PERF_RECORD_MISC_GUEST_KERNEL checks in mapping and remapping logic break ASLR obfuscation for guest kernel samples. --

commit e5353f445ca316e60de67b84bb7594a8aa6daa49
Author: Ian Rogers <[email protected]>

perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses

This commit introduces a new ASLR obfuscation tool to perf inject that remaps or drops virtual addresses to prevent ASLR leaks when sharing perf.data files. It uses a delegate tool architecture to intercept and sanitize events and samples.

Quoted 5 lines
tools/perf/util/aslr.c new file +0 -0
new file mode 100644
index 0000000000000..09b7f2f8fb850

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+static u64 aslr_tool__remap_address(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u8 cpumode,
+				    u64 addr)
+{

[ ... ]

tools/perf/util/aslr.c line 147

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	key.machine = maps__machine(aslr_thread->maps);
+	key.dso = map__dso(al.map);
+	key.invariant = map__start(al.map) - map__pgoff(al.map);
+	key.pid = effective_cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;

Does this also need to check for PERF_RECORD_MISC_GUEST_KERNEL? If a guest kernel sample interrupts a user process, missing this check might cause key.pid to be assigned aslr_thread->pid_ instead of kernel_pid (-1). Could this mismatch prevent hashmap__find() from resolving the mapping?

[ ... ]

Quoted 5 lines
tools/perf/util/aslr.c new file +5 -0
+static u64 aslr_tool__findnew_mapping(struct aslr_tool *aslr,
+				       struct thread *aslr_thread,
+				       u8 cpumode, u64 start,
+				       u64 len, u64 pgoff)
+{

[ ... ]

tools/perf/util/aslr.c line 194

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+	/* The key to look up an incoming address to the outgoing value. */
+	addr_location__init(&al);
+	remap_key.machine = maps__machine(aslr_thread->maps);
+	remap_key.pid = (cpumode == PERF_RECORD_MISC_KERNEL) ? kernel_pid : aslr_thread->pid_;

Similarly here, if cpumode is PERF_RECORD_MISC_GUEST_KERNEL, shouldn't remap_key.pid also be set to kernel_pid?

[ ... ]

Quoted 2 lines
tools/perf/util/aslr.c new file +2 -0
+	/* No mmap, create an entry from the top address. */
+	if (hashmap__find(&aslr->top_addresses, &top_addr_key, &pmax)) {

[ ... ]

tools/perf/util/aslr.c line 237

Quoted 6 lines
tools/perf/util/aslr.c new file +6 -0
+	} else {
+		/* First address of the process, allocate key and first top address. */
+		struct top_addresses_key *tk;
+
+		remap_addr = (cpumode == PERF_RECORD_MISC_KERNEL) ?
+			     kernel_space_start : user_space_start;

Would guest kernel maps erroneously be allocated in the user_space_start range here instead of kernel_space_start due to the missing check for PERF_RECORD_MISC_GUEST_KERNEL?

[ ... ]

Quoted 4 lines
tools/perf/util/aslr.c new file +4 -0
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{

[ ... ]

Quoted 25 lines
tools/perf/util/aslr.c new file +25 -0
+	if (sample_type & PERF_SAMPLE_AUX) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping aux sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;

tools/perf/util/aslr.c line 870

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	}
+
+	if (evsel__is_offcpu_event(evsel)) {
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping off-CPU sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+
+	new_event->sample.header.size = sizeof(struct perf_event_header) + j * sizeof(u64);

If the sample contains unknown UAPI fields (for instance, when processing a perf.data file generated by a newer kernel), they appear to be silently dropped from the payload during this repacking loop.

However, since unrecognized bits aren't cleared from evsel->core.attr, will downstream parsers encounter missing fields while expecting them to be present? Could this lead to reading misaligned data or triggering -EFAULT parsing failures when analyzing the resulting trace?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer
#47 lore raw
In reply to Ian Rogers
Quoted 95 lines · Ian Rogers

If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked.

Events carrying virtual memory layouts are conservatively remap-processed or dropped, while zero-address-risk lifecycle metadata records (such as namespaces, cgroups, and BPF program info) are intentionally delegated to preserve comprehensive downstream trace tool analysis compatibility.

The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory space layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs.

To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, completely drops PERF_RECORD_TEXT_POKE events to prevent absolute immediate pointer operands leaks, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames).

Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Enforce strict command-line validation mutual exclusivity between
--aslr and --convert-callchain to prevent silent unwind failures. Secure mmap.pgoff unconditionally for all host and guest kernel text mapping regions to completely prevent active KASLR load deltas leakage. Conservatively drop PERF_RECORD_TEXT_POKE events completely via a local static drop stub to prevent absolute 64-bit kernel virtual pointer immediate operands leaks. Inject explicit array-end bounds validation check blocks before consuming trailing PERF_CONTEXT_USER_DEFERRED callchain cookies to eliminate out-of-bounds reads and parser desynchronization faults. Simplify ASLR mapping remap logic. Ensure that encountering a PERF_CONTEXT_USER_DEFERRED context marker explicitly updates cpumode.

v5: Add machine to remap addresss key so that it is guest/host
safe. Add 'first_kernel_mapping' tracking guard inside aslr.c to rewrite the core kernel pgoff virtual address while safely protecting module file offsets from corruption. Clean up breakpoint address (bp_addr) memory scrubbing by executing the scrubbing loop directly at core session initialization startup level, natively securing both file headers and streaming pipe channels while removing redundant runtime tool wrapper interception hooks layers.

v4: Scrub bp_addr from headers/pipe synthesis attributes. Remove
kernel mmap pgoff mathematical delta adjustment leaks to maintain secure base obfuscation bounds. Harden guest space contexts mapping loops, correct ksymbol map base invariants tracking, and plug tail-word padding heap leakage vectors in user stacks and AUX payloads.

v3: Combine split-map fixes, guest namespaces, bounds checks, OOM
rollbacks, hot path optimization, safe dso references, and I/O stream error handling from v3/v4 development. Drop raw auxtrace events. Fix thread reference leaks in event handlers. Fix 32-bit truncation bug in hashmaps using u64* values. Prevent leaking uninitialized heap memory by zeroing copy buffer. Correct bitmask checks for branch stack flags. Avoid PMU configuration corruption.

v2: First review feedback adjustments.

---
 tools/perf/builtin-inject.c |   36 +-
 tools/perf/util/Build       |    1 +
 tools/perf/util/aslr.c      | 1036 +++++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h      |   10 +
 4 files changed, 1082 insertions(+), 1 deletion(-)
 create mode 100644 tools/perf/util/aslr.c
 create mode 100644 tools/perf/util/aslr.h
tools/perf/builtin-inject.c +2 -0
index 6ab20df358c4..51dcf248b653 100644
@@ -8,6 +8,7 @@
  */
 #include "builtin.h"
 
+#include "util/aslr.h"
 #include "util/color.h"
 #include "util/dso.h"
 #include "util/vdso.h"
@@ -123,6 +124,7 @@ struct perf_inject {
 	bool			in_place_update_dry_run;
 	bool			copy_kcore_dir;
 	bool			convert_callchain;
+	bool			aslr;
 	const char		*input_name;
 	struct perf_data	output;
 	u64			bytes_written;

tools/perf/builtin-inject.c static int perf_event__repipe(const struct perf_tool *tool, · line 310

Quoted 5 lines
tools/perf/builtin-inject.c +2 -0
@@ -304,6 +306,8 @@ static int perf_event__repipe(const struct perf_tool *tool,
 	return perf_event__repipe_synth(tool, event);
 }
 
+
+

Still have unnecessary blank lines.

tools/perf/builtin-inject.c static int __cmd_inject(struct perf_inject *inject) · line 2467

Quoted 9 lines
tools/perf/builtin-inject.c +2 -0
 static int perf_event__drop(const struct perf_tool *tool __maybe_unused,
 			    union perf_event *event __maybe_unused,
 			    struct perf_sample *sample __maybe_unused,
@@ -2459,6 +2463,8 @@ static int __cmd_inject(struct perf_inject *inject)
 			}
 		}
 
+
+

Ditto.

Quoted 355 lines
tools/perf/builtin-inject.c +29 -1
 		session->header.data_offset = output_data_offset;
 		session->header.data_size = inject->bytes_written;
 		perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc,
@@ -2565,6 +2571,8 @@ int cmd_inject(int argc, const char **argv)
 			   " instance has a subdir"),
 		OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain,
 			    "Generate callchains using DWARF and drop register/stack data"),
+		OPT_BOOLEAN(0, "aslr", &inject.aslr,
+			    "Remap virtual memory addresses similar to ASLR"),
 		OPT_END()
 	};
 	const char * const inject_usage[] = {
@@ -2572,6 +2580,7 @@ int cmd_inject(int argc, const char **argv)
 		NULL
 	};
 	bool ordered_events;
+	struct perf_tool *tool = &inject.tool;
 
 	if (!inject.itrace_synth_opts.set) {
 		/* Disable eager loading of kernel symbols that adds overhead to perf inject. */
@@ -2592,6 +2601,11 @@ int cmd_inject(int argc, const char **argv)
 	if (argc)
 		usage_with_options(inject_usage, options);
 
+	if (inject.aslr && inject.convert_callchain) {
+		pr_err("Error: --aslr and --convert-callchain are mutually exclusive features.\n");
+		return -EINVAL;
+	}
+
 	if (inject.strip && !inject.itrace_synth_opts.set) {
 		pr_err("--strip option requires --itrace option\n");
 		return -1;
@@ -2685,18 +2699,36 @@ int cmd_inject(int argc, const char **argv)
 	inject.tool.schedstat_domain	= perf_event__repipe_op2_synth;
 	inject.tool.dont_split_sample_group = true;
 	inject.tool.merge_deferred_callchains = false;
-	inject.session = __perf_session__new(&data, &inject.tool,
+	if (inject.aslr) {
+		tool = aslr_tool__new(&inject.tool);
+		if (!tool) {
+			ret = -ENOMEM;
+			goto out_close_output;
+		}
+	}
+	inject.session = __perf_session__new(&data, tool,
 					     /*trace_event_repipe=*/inject.output.is_pipe,
 					     /*host_env=*/NULL);
 
 	if (IS_ERR(inject.session)) {
 		ret = PTR_ERR(inject.session);
+		if (inject.aslr)
+			aslr_tool__delete(tool);
 		goto out_close_output;
 	}
 
 	if (zstd_init(&(inject.session->zstd_data), 0) < 0)
 		pr_warning("Decompression initialization failed.\n");
 
+	if (inject.aslr) {
+		struct evsel *evsel;
+
+		evlist__for_each_entry(inject.session->evlist, evsel) {
+			if (evsel->core.attr.type == PERF_TYPE_BREAKPOINT)
+				evsel->core.attr.bp_addr = 0;
+		}
+	}
+
 	/* Save original section info before feature bits change */
 	ret = save_section_info(&inject);
 	if (ret)
@@ -2790,6 +2822,8 @@ int cmd_inject(int argc, const char **argv)
 	strlist__delete(inject.known_build_ids);
 	zstd_fini(&(inject.session->zstd_data));
 	perf_session__delete(inject.session);
+	if (inject.aslr)
+		aslr_tool__delete(tool);
 out_close_output:
 	if (!inject.in_place_update)
 		perf_data__close(&inject.output);
tools/perf/util/Build +1 -0
index 70cc91d00804..65b96f3b87e2 100644
@@ -6,6 +6,7 @@ perf-util-y += arm64-frame-pointer-unwind-support.o
 perf-util-y += addr2line.o
 perf-util-y += addr_location.o
 perf-util-y += annotate.o
+perf-util-y += aslr.o
 perf-util-y += blake2s.o
 perf-util-y += block-info.o
 perf-util-y += block-range.o
tools/perf/util/aslr.c new file +258 -0
new file mode 100644
index 000000000000..09b7f2f8fb85
@@ -0,0 +1,1036 @@
+// SPDX-License-Identifier: GPL-2.0
+#include "aslr.h"
+
+#include "addr_location.h"
+#include "debug.h"
+#include "event.h"
+#include "evsel.h"
+#include "machine.h"
+#include "map.h"
+#include "thread.h"
+#include "tool.h"
+#include "session.h"
+#include "data.h"
+#include "dso.h"
+
+#include <internal/lib.h>  /* page_size */
+#include <linux/compiler.h>
+#include <linux/zalloc.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <unistd.h>
+
+/**
+ * struct remap_addresses_key - Key for mapping original addresses to remapped ones.
+ * @dso: Pointer to the DSO (Dynamic Shared Object) associated with the mapping.
+ * @invariant: Unique offset invariant within the VMA (Virtual Memory Area).
+ *             Calculated as `start - pgoff`. This value remains constant when
+ *             perf's internal `maps__fixup_overlap_and_insert` splits a map into
+ *             fragmented VMA pieces due to overlapping events, allowing us to
+ *             resolve split maps consistently back to the original VMA.
+ * @pid: Process ID associated with the mapping.
+ */
+struct remap_addresses_key {
+	struct machine *machine;
+	struct dso *dso;
+	u64 invariant;
+	pid_t pid;
+};
+
+struct aslr_mapping {
+	struct list_head node;
+	u64 orig_start;
+	u64 len;
+	u64 remap_start;
+};
+
+struct aslr_tool {
+	/** @tool: The tool implemented here and a pointer to a delegate to process the data. */
+	struct delegate_tool tool;
+	/** @machines: The machines with the input, not remapped, virtual address layout. */
+	struct machines machines;
+	/** @event_copy: Buffer used to create an event to pass to the delegate. */
+	char event_copy[PERF_SAMPLE_MAX_SIZE] __aligned(8);
+	/** @remap_addresses: mapping from remap_addresses_key to remapped address. */
+	struct hashmap remap_addresses;
+	/** @top_addresses: mapping from process to max remapped address. */
+	struct hashmap top_addresses;
+};
+
+static const pid_t kernel_pid = -1;
+
+/* Start remapping user processes from a small non-zero offset. */
+static const u64 user_space_start = 0x200000;
+static const u64 kernel_space_start = 0xffff800010000000;
+
+static size_t remap_addresses__hash(long _key, void *ctx __maybe_unused)
+{
+	struct remap_addresses_key *key = (struct remap_addresses_key *)_key;
+
+	return (size_t)key->machine ^ (size_t)key->dso ^ key->invariant ^ key->pid;
+}
+
+static bool remap_addresses__equal(long _key1, long _key2, void *ctx __maybe_unused)
+{
+	struct remap_addresses_key *key1 = (struct remap_addresses_key *)_key1;
+	struct remap_addresses_key *key2 = (struct remap_addresses_key *)_key2;
+
+	return key1->machine == key2->machine &&
+	       RC_CHK_EQUAL(key1->dso, key2->dso) &&
+	       key1->invariant == key2->invariant &&
+	       key1->pid == key2->pid;
+}
+
+struct top_addresses_key {
+	struct machine *machine;
+	pid_t pid;
+};
+
+static size_t top_addresses__hash(long _key, void *ctx __maybe_unused)
+{
+	struct top_addresses_key *key = (struct top_addresses_key *)_key;
+
+	return (size_t)key->machine ^ key->pid;
+}
+
+static bool top_addresses__equal(long _key1, long _key2, void *ctx __maybe_unused)
+{
+	struct top_addresses_key *key1 = (struct top_addresses_key *)_key1;
+	struct top_addresses_key *key2 = (struct top_addresses_key *)_key2;
+
+	return key1->machine == key2->machine && key1->pid == key2->pid;
+}
+
+static u64 round_up_to_page_size(u64 addr)
+{
+	return (addr + page_size - 1) & ~((u64)page_size - 1);
+}
+
+static u64 aslr_tool__remap_address(struct aslr_tool *aslr,
+				    struct thread *aslr_thread,
+				    u8 cpumode,
+				    u64 addr)
+{
+	struct addr_location al;
+	struct remap_addresses_key key;
+	u64 *remapped_invariant_ptr = NULL;
+	u64 remap_addr = 0;
+	u8 effective_cpumode = cpumode;
+
+	if (!aslr_thread)
+		return 0; /* No thread. */
+
+	addr_location__init(&al);
+	if (!thread__find_map(aslr_thread, cpumode, addr, &al)) {
+		/*
+		 * If lookup fails with specified cpumode, try fallback to the other space
+		 * to be robust against bad cpumode in samples.
+		 */
+		if (cpumode == PERF_RECORD_MISC_KERNEL)
+			effective_cpumode = PERF_RECORD_MISC_USER;
+		else if (cpumode == PERF_RECORD_MISC_USER)
+			effective_cpumode = PERF_RECORD_MISC_KERNEL;
+		else if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL)
+			effective_cpumode = PERF_RECORD_MISC_GUEST_USER;
+		else if (cpumode == PERF_RECORD_MISC_GUEST_USER)
+			effective_cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+
+		if (!thread__find_map(aslr_thread, effective_cpumode, addr, &al)) {
+			addr_location__exit(&al);
+			return 0; /* No mmap. */
+		}
+	}
+
+	key.machine = maps__machine(aslr_thread->maps);
+	key.dso = map__dso(al.map);
+	key.invariant = map__start(al.map) - map__pgoff(al.map);
+	key.pid = effective_cpumode == PERF_RECORD_MISC_KERNEL ? kernel_pid : aslr_thread->pid_;
+
+	if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr)) {
+		remap_addr = *remapped_invariant_ptr + map__pgoff(al.map) +
+			     (addr - map__start(al.map));
+	} else {
+		pr_debug("Cannot find a remapped entry for address %lx "
+			 "in mapping %lx(%lx) for pid=%d\n",
+			 addr, map__start(al.map), map__size(al.map), key.pid);
+	}
+
+	addr_location__exit(&al);
+	return remap_addr;
+}
+
+static u64 aslr_tool__findnew_mapping(struct aslr_tool *aslr,
+				       struct thread *aslr_thread,
+				       u8 cpumode, u64 start,
+				       u64 len, u64 pgoff)
+{
+	/* Address location for dso lookup. */
+	struct addr_location al;
+	/* Original ASLR address based key for the remap table. */
+	struct remap_addresses_key remap_key;
+	/* The address in the ASLR sanitized address space less pg_off. */
+	u64 *remapped_invariant_ptr;
+	/* Key for the maximum address in a process. */
+	struct top_addresses_key top_addr_key;
+	/* Value in top address table. */
+	u64 *pmax = NULL;
+	/* Address in ASLR sanitized address space. */
+	u64 remap_addr;
+	/* Potentially allocated remap table key. */
+	struct remap_addresses_key *new_remap_key = NULL;
+	/*
+	 * Potentially allocated remap table key.
+	 * TODO: Avoid allocation necessary for perf 32-bit binary support.
+	 */
+	u64 *new_remap_val = NULL;
+	int err;
+
+	if (!aslr_thread)
+		return 0;
+
+	/* The key to look up an incoming address to the outgoing value. */
+	addr_location__init(&al);
+	remap_key.machine = maps__machine(aslr_thread->maps);
+	remap_key.pid = (cpumode == PERF_RECORD_MISC_KERNEL) ? kernel_pid : aslr_thread->pid_;
+	if (thread__find_map(aslr_thread, cpumode, start, &al)) {
+		remap_key.dso = map__dso(al.map);
+		remap_key.invariant = map__start(al.map) - map__pgoff(al.map);
+	} else {
+		remap_key.dso = NULL;
+		remap_key.invariant = start - pgoff;
+	}
+
+	/* The key to look up top allocated address. */
+	top_addr_key.machine = remap_key.machine;
+	top_addr_key.pid = remap_key.pid;
+
+	if (hashmap__find(&aslr->remap_addresses, &remap_key, &remapped_invariant_ptr)) {
+		/* Mmap already exists. */
+		u64 calculated_max;
+
+		remap_addr = *remapped_invariant_ptr + (al.map ? map__pgoff(al.map) : pgoff);
+		calculated_max = remap_addr + len;
+
+		/* See if top mapping was expanded. */
+		if (hashmap__find(&aslr->top_addresses, &top_addr_key, &pmax)) {
+			if (calculated_max > *pmax)
+				*pmax = calculated_max;
+		}
+		addr_location__exit(&al);
+		return remap_addr;
+	}
+	/* No mmap, create an entry from the top address. */
+	if (hashmap__find(&aslr->top_addresses, &top_addr_key, &pmax)) {
+		/* Current max allocated mmap address within the process. */
+		remap_addr = *pmax;
+
+		/* Give 1 page gap from current max page. */
+		remap_addr = round_up_to_page_size(remap_addr);
+		remap_addr += page_size;
+		if (remap_addr + len > *pmax)
+			*pmax = remap_addr + len;
+	} else {
+		/* First address of the process, allocate key and first top address. */
+		struct top_addresses_key *tk;
+
+		remap_addr = (cpumode == PERF_RECORD_MISC_KERNEL) ?
+			     kernel_space_start : user_space_start;
+		remap_addr = round_up_to_page_size(remap_addr);
+
+		tk = malloc(sizeof(*tk));
+		pmax = malloc(sizeof(u64));
+		if (!tk || !pmax) {
+			err = -ENOMEM;
+		} else {
+			*tk = top_addr_key;
+			*pmax = remap_addr + len;
+			err = hashmap__insert(&aslr->top_addresses, tk, pmax, HASHMAP_ADD, NULL, NULL);
+		}
+		if (err) {
+			errno = -err;
+			pr_err("Failure to add ASLR process top address %m\n");
+			free(tk);
+			free(pmax);
+			addr_location__exit(&al);
+			return 0;
+		}
+	}
+	/* Create rmeapping entry. */

tools/perf/util/aslr.c line 268

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	new_remap_key = malloc(sizeof(*new_remap_key));
+	new_remap_val = malloc(sizeof(u64));
+	if (!new_remap_key || !new_remap_val) {
+		err = -ENOMEM;
+	} else {
+		*new_remap_key = remap_key;
+		new_remap_key->dso = dso__get(remap_key.dso);
+		if (cpumode == PERF_RECORD_MISC_KERNEL) {
+			if (al.map)
+				*new_remap_val = remap_addr - (start - map__start(al.map)) - map__pgoff(al.map);

A too long line.

Quoted 280 lines
tools/perf/util/aslr.c new file +280 -0
+			else
+				*new_remap_val = remap_addr;
+		} else {
+			*new_remap_val = remap_addr - (al.map ? map__pgoff(al.map) : pgoff);
+		}
+		err = hashmap__add(&aslr->remap_addresses, new_remap_key, new_remap_val);
+		if (err)
+			dso__put(new_remap_key->dso);
+	}
+	if (err) {
+		errno = -err;
+		pr_err("Failure to add ASLR remapping %m\n");
+		free(new_remap_key);
+		free(new_remap_val);
+		addr_location__exit(&al);
+		return 0;
+	}
+	addr_location__exit(&al);
+	return remap_addr;
+}
+
+static int aslr_tool__process_mmap(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	u8 cpumode;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_mmap(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, event->mmap.pid, event->mmap.tid);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap.start = aslr_tool__findnew_mapping(aslr, thread, cpumode,
+							     event->mmap.start,
+							     event->mmap.len,
+							     event->mmap.pgoff);
+	if (cpumode == PERF_RECORD_MISC_KERNEL || cpumode == PERF_RECORD_MISC_GUEST_KERNEL)
+		new_event->mmap.pgoff = new_event->mmap.start;
+	err = delegate->mmap(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_mmap2(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	u8 cpumode;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_mmap2(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, event->mmap2.pid, event->mmap2.tid);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->mmap2, &event->mmap2, event->mmap2.header.size);
+	/* Remaps the mmap.start. */
+	new_event->mmap2.start = aslr_tool__findnew_mapping(aslr, thread, cpumode,
+							       event->mmap2.start,
+							       event->mmap2.len,
+							       event->mmap2.pgoff);
+	if (cpumode == PERF_RECORD_MISC_KERNEL || cpumode == PERF_RECORD_MISC_GUEST_KERNEL)
+		new_event->mmap2.pgoff = new_event->mmap2.start;
+	err = delegate->mmap2(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_comm(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_comm(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->comm(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_fork(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_fork(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->fork(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_exit(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	/* Create the thread, map, etc. in the ASLR before virtual address space. */
+	err = perf_event__process_exit(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	return delegate->exit(delegate, event, sample, machine);
+}
+
+static int aslr_tool__process_text_poke(const struct perf_tool *tool __maybe_unused,
+					union perf_event *event __maybe_unused,
+					struct perf_sample *sample __maybe_unused,
+					struct machine *machine __maybe_unused)
+{
+	/* Drop in case the instruction encodes an ASLR revealing address. */
+	return 0;
+}
+
+static int aslr_tool__process_ksymbol(const struct perf_tool *tool,
+				union perf_event *event,
+				struct perf_sample *sample,
+				struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	int err;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+
+	err = perf_event__process_ksymbol(tool, event, sample, aslr_machine);
+	if (err)
+		return err;
+
+	thread = machine__findnew_thread(aslr_machine, kernel_pid, 0);
+	if (!thread)
+		return -ENOMEM;
+	memcpy(&new_event->ksymbol, &event->ksymbol, event->ksymbol.header.size);
+	/* Remaps the ksymbol.start */
+	new_event->ksymbol.addr = aslr_tool__findnew_mapping(aslr, thread,
+							       PERF_RECORD_MISC_KERNEL,
+							       event->ksymbol.addr,
+							       event->ksymbol.len,
+							       /*pgoff=*/0);
+
+	err = delegate->ksymbol(delegate, new_event, sample, machine);
+	thread__put(thread);
+	return err;
+}
+
+static int aslr_tool__process_sample(const struct perf_tool *tool, union perf_event *event,
+				struct perf_sample *sample,
+				struct evsel *evsel, struct machine *machine)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	int ret;
+	u64 sample_type;
+	struct thread *thread;
+	struct machine *aslr_machine;
+	__u64 max_i;
+	__u64 max_j;
+	union perf_event *new_event;
+	struct perf_sample new_sample;
+	__u64 *in_array, *out_array;
+	u8 cpumode;
+	u64 addr;
+	size_t i;
+	size_t j;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	ret = -EFAULT;
+	sample_type = evsel->core.attr.sample_type;
+	max_i = (event->header.size - sizeof(struct perf_event_header)) / sizeof(__u64);
+	max_j = (PERF_SAMPLE_MAX_SIZE - sizeof(struct perf_event_header)) / sizeof(__u64);
+	new_event = (union perf_event *)aslr->event_copy;
+	cpumode = sample->cpumode;
+	i = 0;
+	j = 0;
+
+	aslr_machine = machines__findnew(&aslr->machines, machine->pid);
+	if (!aslr_machine)
+		return -ENOMEM;
+

tools/perf/util/aslr.c line 558

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	thread = machine__findnew_thread(aslr_machine, sample->pid, sample->tid);
+
+	if (!thread)
+		return -ENOMEM;
+
+	if (max_i > PERF_SAMPLE_MAX_SIZE / sizeof(u64))
+		goto out_put;
+
+
+

Here as well.

Quoted 16 lines
tools/perf/util/aslr.c new file +16 -0
+	new_event->sample.header = event->sample.header;
+
+	in_array = &event->sample.array[0];
+	out_array = &new_event->sample.array[0];
+
+#define CHECK_BOUNDS(required_i, required_j) \
+	do { \
+		if (i + (required_i) > max_i || j + (required_j) > max_j) { \
+			ret = -EFAULT; \
+			goto out_put; \
+		} \
+	} while (0)
+
+#define COPY_U64() \
+	do { \
+		CHECK_BOUNDS(1, 1); \

tools/perf/util/aslr.c line 584

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+		out_array[j++] = in_array[i++]; \
+	} while (0)
+
+#define REMAP_U64(addr_field) \
+	do { \
+		CHECK_BOUNDS(1, 1); \
+		out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr_field); \
+		i++; \
+	} while (0)
+

I'm still not sure if it's a good idea to expose all the details of the sample layout here. It needs to be in sync with evsel__parse_sample() for any future changes.

Quoted 110 lines
tools/perf/util/aslr.c new file +110 -0
+	if (sample_type & PERF_SAMPLE_IDENTIFIER)
+		COPY_U64(); /* id */
+	if (sample_type & PERF_SAMPLE_IP)
+		REMAP_U64(sample->ip);
+	if (sample_type & PERF_SAMPLE_TID)
+		COPY_U64(); /* pid, tid */
+	if (sample_type & PERF_SAMPLE_TIME)
+		COPY_U64(); /* time */
+	if (sample_type & PERF_SAMPLE_ADDR)
+		REMAP_U64(sample->addr);
+	if (sample_type & PERF_SAMPLE_ID)
+		COPY_U64(); /* id */
+	if (sample_type & PERF_SAMPLE_STREAM_ID)
+		COPY_U64(); /* stream_id */
+	if (sample_type & PERF_SAMPLE_CPU)
+		COPY_U64(); /* cpu, res */
+	if (sample_type & PERF_SAMPLE_PERIOD)
+		COPY_U64(); /* period */
+	if (sample_type & PERF_SAMPLE_READ) {
+		if ((evsel->core.attr.read_format & PERF_FORMAT_GROUP) == 0) {
+			COPY_U64(); /* value */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+				COPY_U64(); /* time_enabled */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+				COPY_U64(); /* time_running */
+			if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+				COPY_U64(); /* id */
+			if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+				COPY_U64(); /* lost */
+		} else {
+			u64 nr;
+
+			CHECK_BOUNDS(1, 1);
+			nr = out_array[j++] = in_array[i++];
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
+				COPY_U64(); /* time_enabled */
+			if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
+				COPY_U64(); /* time_running */
+			for (u64 cntr = 0; cntr < nr; cntr++) {
+				COPY_U64(); /* value */
+				if (evsel->core.attr.read_format & PERF_FORMAT_ID)
+					COPY_U64(); /* id */
+				if (evsel->core.attr.read_format & PERF_FORMAT_LOST)
+					COPY_U64(); /* lost */
+			}
+		}
+	}
+	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
+		u64 nr;
+
+		CHECK_BOUNDS(1, 1);
+		nr = out_array[j++] = in_array[i++];
+
+		for (u64 cntr = 0; cntr < nr; cntr++) {
+			CHECK_BOUNDS(1, 1);
+			addr = in_array[i++];
+			if (addr >= PERF_CONTEXT_MAX) {
+				out_array[j++] = addr;
+				switch (addr) {
+				case PERF_CONTEXT_HV:
+					cpumode = PERF_RECORD_MISC_HYPERVISOR;
+					break;
+				case PERF_CONTEXT_KERNEL:
+					cpumode = PERF_RECORD_MISC_KERNEL;
+					break;
+				case PERF_CONTEXT_USER:
+					cpumode = PERF_RECORD_MISC_USER;
+					break;
+				case PERF_CONTEXT_GUEST:
+					cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+					break;
+				case PERF_CONTEXT_GUEST_KERNEL:
+					cpumode = PERF_RECORD_MISC_GUEST_KERNEL;
+					break;
+				case PERF_CONTEXT_GUEST_USER:
+					cpumode = PERF_RECORD_MISC_GUEST_USER;
+					break;
+				case PERF_CONTEXT_USER_DEFERRED:
+					if (cntr + 1 >= nr) {
+						pr_debug("Truncated callchain deferred cookie context\n");
+						ret = 0;
+						goto out_put;
+					}
+					/*
+					 * Immediately followed by a 64-bit
+					 * stitching cookie. Skip/Copy it!
+					 */
+					CHECK_BOUNDS(1, 1);
+					out_array[j++] = in_array[i++];
+					cntr++;
+					cpumode = PERF_RECORD_MISC_USER;
+					break;
+				default:
+					pr_debug("invalid callchain context: %"PRIx64"\n", addr);
+					ret = 0;
+					goto out_put;
+				}
+				continue;
+			}
+			out_array[j++] = aslr_tool__remap_address(aslr, thread, cpumode, addr);
+		}
+	}
+	if (sample_type & PERF_SAMPLE_RAW) {
+		size_t bytes = sizeof(u32) + sample->raw_size;
+		size_t u64_words = (bytes + 7) / 8;
+
+		if (i + u64_words > max_i || j + u64_words > max_j) {
+			ret = -EFAULT;
+			goto out_put;
+		}

tools/perf/util/aslr.c line 704

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+		memcpy(&out_array[j], &in_array[i], bytes);
+		i += u64_words;
+		j += u64_words;
+		/*
+		 * TODO: certain raw samples can be remapped, such as
+		 * tracepoints by examining their fields.
+		 */
+		pr_debug("Dropping raw samples as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;

There's not much point to do it when we drop all samples as the sample type flags will be the same for an evsel. Maybe better to check if it has unsupported flags earlier.

Quoted 271 lines
tools/perf/util/aslr.c new file +271 -0
+	}
+	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
+		u64 nr;
+
+		CHECK_BOUNDS(1, 1);
+		nr = out_array[j++] = in_array[i++];
+
+		if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)
+			COPY_U64(); /* hw_idx */
+
+		if (nr > (ULLONG_MAX / 3)) {
+			ret = -EFAULT;
+			goto out_put;
+		}
+		if (nr * 3 > max_i - i || nr * 3 > max_j - j) {
+			ret = -EFAULT;
+			goto out_put;
+		}
+		for (u64 cntr = 0; cntr < nr; cntr++) {
+			out_array[j++] = aslr_tool__remap_address(aslr, thread,
+								  sample->cpumode,
+								  in_array[i++]); /* from */
+			out_array[j++] = aslr_tool__remap_address(aslr, thread,
+								  sample->cpumode,
+								  in_array[i++]); /* to */
+			out_array[j++] = in_array[i++]; /* flags */
+		}
+		if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) {
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+			/* TODO: confirm branch counters don't leak ASLR information. */
+			pr_debug("Dropping sample branch counters as possible ASLR leak\n");
+			ret = 0;
+			goto out_put;
+		}
+	}
+	if (sample_type & PERF_SAMPLE_REGS_USER) {
+		u64 abi;
+
+		COPY_U64(); /* abi */
+		abi = out_array[j-1];
+		if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+			u64 nr = hweight64(evsel->core.attr.sample_regs_user);
+
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping regs user sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_STACK_USER) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+
+			COPY_U64(); /* dyn_size */
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping stack user sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
+		COPY_U64(); /* perf_sample_weight */
+	if (sample_type & PERF_SAMPLE_DATA_SRC)
+		COPY_U64(); /* data_src */
+	if (sample_type & PERF_SAMPLE_TRANSACTION)
+		COPY_U64(); /* transaction */
+	if (sample_type & PERF_SAMPLE_REGS_INTR) {
+		u64 abi;
+
+		COPY_U64(); /* abi */
+		abi = out_array[j-1];
+		if (abi != PERF_SAMPLE_REGS_ABI_NONE) {
+			u64 nr = hweight64(evsel->core.attr.sample_regs_intr);
+
+			if (nr > max_i - i || nr > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], nr * sizeof(u64));
+			i += nr;
+			j += nr;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping interrupt register sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_PHYS_ADDR) {
+		COPY_U64(); /* phys_addr */
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping physical address sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+	if (sample_type & PERF_SAMPLE_CGROUP)
+		COPY_U64(); /* cgroup */
+	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
+		COPY_U64(); /* data_page_size */
+	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
+		COPY_U64(); /* code_page_size */
+
+	if (sample_type & PERF_SAMPLE_AUX) {
+		u64 size;
+
+		CHECK_BOUNDS(1, 1);
+		size = out_array[j++] = in_array[i++];
+		if (size > 0) {
+			size_t u64_words = size / 8 + (size % 8 ? 1 : 0);
+
+			if (u64_words > max_i - i || u64_words > max_j - j) {
+				ret = -EFAULT;
+				goto out_put;
+			}
+			memcpy(&out_array[j], &in_array[i], size);
+			if (size % 8) {
+				size_t pad = 8 - (size % 8);
+
+				memset(((char *)&out_array[j]) + size, 0, pad);
+			}
+			i += u64_words;
+			j += u64_words;
+		}
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping aux sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+
+	if (evsel__is_offcpu_event(evsel)) {
+		/* TODO: can this be less conservative? */
+		pr_debug("Dropping off-CPU sample as possible ASLR leak\n");
+		ret = 0;
+		goto out_put;
+	}
+
+	new_event->sample.header.size = sizeof(struct perf_event_header) + j * sizeof(u64);
+
+	perf_sample__init(&new_sample, /*all=*/ true);
+	ret = evsel__parse_sample(evsel, new_event, &new_sample);
+	if (ret) {
+		perf_sample__exit(&new_sample);
+		goto out_put;
+	}
+
+	ret = delegate->sample(delegate, new_event, &new_sample, evsel, machine);
+	perf_sample__exit(&new_sample);
+
+out_put:
+	thread__put(thread);
+	return ret;
+}
+
+#undef CHECK_BOUNDS
+#undef COPY_U64
+#undef REMAP_U64
+
+
+static int aslr_tool__process_attr(const struct perf_tool *tool,
+				   union perf_event *event,
+				   struct evlist **pevlist)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct perf_tool *delegate;
+	union perf_event *new_event;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+	delegate = aslr->tool.delegate;
+	new_event = (union perf_event *)aslr->event_copy;
+
+	memcpy(&new_event->attr, &event->attr, event->attr.header.size);
+	if (new_event->attr.attr.type == PERF_TYPE_BREAKPOINT)
+		new_event->attr.attr.bp_addr = 0;  /* Conservatively remove addresses. */
+
+	return delegate->attr(delegate, new_event, pevlist);
+}
+
+static int skipn(int fd, off_t n)
+{
+	char buf[4096];
+	ssize_t ret;
+
+	while (n > 0) {
+		ret = read(fd, buf, min(n, (off_t)sizeof(buf)));
+		if (ret <= 0)
+			return ret;
+		n -= ret;
+	}
+
+	return 0;
+}
+
+static s64 aslr_tool__process_auxtrace(const struct perf_tool *tool __maybe_unused,
+				       struct perf_session *session,
+				       union perf_event *event)
+{
+	if (perf_data__is_pipe(session->data)) {
+		/* Copy behavior of the stub by reading all pipe data. */
+		int err = skipn(perf_data__fd(session->data), event->auxtrace.size);
+
+		if (err < 0)
+			return err;
+	}
+	return event->auxtrace.size;
+}
+
+static int aslr_tool__process_auxtrace_info(const struct perf_tool *tool __maybe_unused,
+					    struct perf_session *session __maybe_unused,
+					    union perf_event *event __maybe_unused)
+{
+	return 0;
+}
+
+static int aslr_tool__process_auxtrace_error(const struct perf_tool *tool __maybe_unused,
+					     struct perf_session *session __maybe_unused,
+					     union perf_event *event __maybe_unused)
+{
+	return 0;
+}
+
+static void aslr_tool__init(struct aslr_tool *aslr, struct perf_tool *delegate)
+{
+	delegate_tool__init(&aslr->tool, delegate);
+	aslr->tool.tool.ordered_events = true;
+
+	machines__init(&aslr->machines);
+
+	hashmap__init(&aslr->remap_addresses,
+		      remap_addresses__hash, remap_addresses__equal,
+		      /*ctx=*/NULL);
+	hashmap__init(&aslr->top_addresses,
+		      top_addresses__hash, top_addresses__equal,
+		      /*ctx=*/NULL);
+
+	aslr->tool.tool.sample	= aslr_tool__process_sample;
+	/* read - reads a counter, okay to delegate. */
+	aslr->tool.tool.mmap	= aslr_tool__process_mmap;
+	aslr->tool.tool.mmap2	= aslr_tool__process_mmap2;
+	aslr->tool.tool.comm	= aslr_tool__process_comm;
+	aslr->tool.tool.fork	= aslr_tool__process_fork;

tools/perf/util/aslr.c line 985

Quoted 10 lines
tools/perf/util/aslr.c new file +10 -0
+	aslr->tool.tool.exit	= aslr_tool__process_exit;
+	/* namesspaces, cgroup, lost, lost_sample, aux, */
+	/* itrace_start, aux_output_hw_id, context_switch, throttle, unthrottle */
+	/* - no virtual addresses. */
+	aslr->tool.tool.ksymbol	= aslr_tool__process_ksymbol;
+	/* bpf - no virtual address. */
+	aslr->tool.tool.text_poke = aslr_tool__process_text_poke;
+	aslr->tool.tool.attr = aslr_tool__process_attr;
+	/* event_update, tracing_data, finished_round, build_id, id_index, */
+	/* event_update, tracing_data, finished_round, build_id, id_index, */

The same line appears twice.

tools/perf/util/aslr.c line 988

Quoted 3 lines
tools/perf/util/aslr.c new file +3 -0
+	/* auxtrace_info, auxtrace_error, time_conv, thread_map, cpu_map, */
+	/* stat_config, stat, feature, finished_init, bpf_metadata, compressed, */
+	/* auxtrace - no virtual addresses. */

The auxtrace related ones are listed but handled differently?

Thanks,
Namhyung

Quoted 67 lines
tools/perf/util/aslr.c new file +48 -0
+	aslr->tool.tool.auxtrace = aslr_tool__process_auxtrace;
+	aslr->tool.tool.auxtrace_info = aslr_tool__process_auxtrace_info;
+	aslr->tool.tool.auxtrace_error = aslr_tool__process_auxtrace_error;
+}
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate)
+{
+	struct aslr_tool *aslr = zalloc(sizeof(*aslr));
+
+	if (!aslr)
+		return NULL;
+
+	aslr_tool__init(aslr, delegate);
+	return &aslr->tool.tool;
+}
+
+void aslr_tool__delete(struct perf_tool *tool)
+{
+	struct delegate_tool *del_tool;
+	struct aslr_tool *aslr;
+	struct hashmap_entry *cur;
+	size_t bkt;
+
+	if (!tool)
+		return;
+
+	del_tool = container_of(tool, struct delegate_tool, tool);
+	aslr = container_of(del_tool, struct aslr_tool, tool);
+
+	hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) {
+		struct remap_addresses_key *key = (struct remap_addresses_key *)cur->pkey;
+
+		if (key)
+			dso__put(key->dso);
+		zfree(&cur->pkey);
+		zfree(&cur->pvalue);
+	}
+	hashmap__for_each_entry(&aslr->top_addresses, cur, bkt) {
+		zfree(&cur->pkey);
+		zfree(&cur->pvalue);
+	}
+
+	hashmap__clear(&aslr->remap_addresses);
+	hashmap__clear(&aslr->top_addresses);
+	machines__destroy_kernel_maps(&aslr->machines);
+	machines__exit(&aslr->machines);
+	free(aslr);
+}
tools/perf/util/aslr.h new file +10 -0
new file mode 100644
index 000000000000..ea984d82681f
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PERF_ASLR_H
+#define __PERF_ASLR_H
+
+struct perf_tool;
+
+struct perf_tool *aslr_tool__new(struct perf_tool *delegate);
+void aslr_tool__delete(struct perf_tool *aslr);
+
+#endif /* __PERF_ASLR_H */
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author reviewer
#48 lore raw

PATCH v6 5/6 perf test: Add inject ASLR test

In reply to Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (utilizing a dedicated kernel-intensive VFS dd workload to guarantee continuous timer interrupts sampling flow inside kernel privilege states).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Refactor kernel-space sampling test cases to utilize a dedicated
system-call intensive VFS dd workload (kprog) instead of purely userspace-bound tight loops, guaranteeing high-density kernel privilege state sampling streams and eliminating intermittent execution flakiness dropouts.

v5: Harden test suite verification pipelines by upgrading report
checks to strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.

v4: Reorder set -e/pipefail to prevent temp file leakage in root
directory on unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.

v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain
empty data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.

v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
 tools/perf/tests/shell/inject_aslr.sh | 460 ++++++++++++++++++++++++++
 1 file changed, 460 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +460 -0
new file mode 100755
index 000000000000..6363a0f69d2b
@@ -0,0 +1,460 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+kprog="dd if=/dev/zero of=/dev/null bs=1M count=500"
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${kprog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${kprog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | \
+    sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | \
+    sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
reviewer
#49 lore raw

Re: [PATCH v6 5/6] perf test: Add inject ASLR test

Quoted 17 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (utilizing a dedicated kernel-intensive VFS dd workload to guarantee continuous timer interrupts sampling flow inside kernel privilege states).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Quoted 9 lines
Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Refactor kernel-space sampling test cases to utilize a dedicated
system-call intensive VFS dd workload (kprog) instead of purely userspace-bound tight loops, guaranteeing high-density kernel privilege state sampling streams and eliminating intermittent execution flakiness dropouts.

Hi Ian,

V5 passed on X86, but now I get this test failing about 50% of the time with output like:

Test user register stripping
User registers stripping test [Failed - report parsing differs] Showing first 20 lines of diff:

tmp/perf-test-aslr.ssH9urcfri/report_regs2.clean 2026-05-08 14:14:02.129298219 +0100 renamed from tmp/perf-test-aslr.ssH9urcfri/report_regs1.clean 2026-05-08 14:14:02.127298207 +0100 +1 -1
@@ -30,8 +30,8 @@
      0.02%  perf          ld-linux-x86-64.so.2  [.] mmap64
      0.02%  perf-noploop  [kernel.kallsyms]     [k] kmem_cache_free
      0.02%  perf-noploop  [kernel.kallsyms]     [k] nohz_balancer_kick
-     0.02%  perf-noploop  [kernel.kallsyms]     [k] pvclock_gtod_notify
      0.02%  perf-noploop  [kernel.kallsyms]     [k] try_to_wake_up
+     0.02%  perf-noploop  [kvm]                 [k] pvclock_gtod_notify
      0.02%  perf-noploop  libc.so.6             [.] __cxa_finalize
      0.04%  perf          ld-linux-x86-64.so.2  [.] strcmp
      0.05%  perf          libLLVM-15.so.1       [.] 

llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) ---- end ----

or:

Test user register stripping
User registers stripping test [Failed - report parsing differs] Showing first 20 lines of diff:

tmp/perf-test-aslr.NoDUUXtHyh/report_regs2.clean 2026-05-08 14:05:31.111246503 +0100 renamed from tmp/perf-test-aslr.NoDUUXtHyh/report_regs1.clean 2026-05-08 14:05:31.109246491 +0100 +0 -0
@@ -2,8 +2,8 @@
      0.01%  perf          [kernel.kallsyms]     [k] 

find_mergeable_anon_vma

      0.01%  perf          [kernel.kallsyms]     [k] finish_fault
      0.01%  perf          [kernel.kallsyms]     [k] 
pte_offset_map_rw_nolock
+     0.02%  perf          [amdgpu]              [k] amdgpu_device_rreg
      0.02%  perf          [kernel.kallsyms]     [k] 
__alloc_frozen_pages_noprof
-     0.02%  perf          [kernel.kallsyms]     [k] amdgpu_device_rreg
      0.02%  perf          [kernel.kallsyms]     [k] 
__build_id_parse.isra.0
      0.02%  perf          [kernel.kallsyms]     [k] filemap_get_entry
      0.02%  perf          [kernel.kallsyms]     [k] filemap_map_pages

---- end ----

And on Arm I get a hang/infinite loop every time in "Test kernel ASLR remapping". Looks like it could be related to the changes in V6 as I didn't see it on V5:

#0 __read_once_size (size=4, res=0xffffe56c64a0, p=0xaaaaeaedbab8)

      at linux/tools/include/linux/compiler.h:180
  #1  atomic_read (v=0xaaaaeaedbab8) at 
linux/tools/include/asm-generic/atomic-gcc.h:26
  #2  0x0000aaaaaf65cd6c in refcount_read (r=0xaaaaeaedbab8)
      at linux/tools/include/linux/refcount.h:70
  #3  0x0000aaaaaf65d9dc in check_invariants (maps=0xaaaae7e3b480) at 

util/maps.c:114
#4 0x0000aaaaaf65eef8 in maps__insert (maps=0xaaaae7e3b480,
map=0xaaaaec2ccf10) at util/maps.c:536
#5 0x0000aaaaaf62a028 in maps__split_kallsyms (kmaps=0xaaaae7e3b480,
dso=0xaaaae7e3f910, delta=1879048192,

      initial_map=0xaaaae7e3fab0) at util/symbol.c:986
  #6  0x0000aaaaaf62b550 in __dso__load_kallsyms (dso=0xaaaae7e3f910, 
filename=0xaaaae7e55200 "/proc/kallsyms",
      map=0xaaaae7e3fab0, no_kcore=false) at util/symbol.c:1530
  #7  0x0000aaaaaf62b5bc in dso__load_kallsyms (dso=0xaaaae7e3f910, 
filename=0xaaaae7e55200 "/proc/kallsyms",
      map=0xaaaae7e3fab0) at util/symbol.c:1536

#8 0x0000aaaaaf62cbc0 in dso__load_kernel_sym (dso=0xaaaae7e3f910,
map=0xaaaae7e3fab0) at util/symbol.c:2125
#9 0x0000aaaaaf62bc5c in dso__load (dso=0xaaaae7e3f910,
map=0xaaaae7e3fab0) at util/symbol.c:1721
#10 0x0000aaaaaf65b98c in map__load (map=0xaaaae7e3fab0) at
util/map.c:351
#11 0x0000aaaaaf5e43cc in thread__find_map (thread=0xaaaae7e443b0,
cpumode=1 '\001', addr=18446603336494207932,

      al=0xffffe56c8c28) at util/event.c:744
  #12 0x0000aaaaaf5e4810 in machine__resolve (machine=0xaaaae7e3bee0, 
al=0xffffe56c8c28, sample=0xffffe56c8df0)
      at util/event.c:818
  #13 0x0000aaaaaf41d850 in process_sample_event (tool=0xffffe56c93d0, 
event=0xffffb1091ec8, sample=0xffffe56c8df0,
      evsel=0xaaaae7e3b580, machine=0xaaaae7e3bee0) at 
builtin-script.c:2686
  #14 0x0000aaaaaf6668f4 in evlist__deliver_sample 
(evlist=0xaaaae7e3c550, tool=0xffffe56c93d0, event=0xffffb1091ec8,
      sample=0xffffe56c8df0, evsel=0xaaaae7e3b580, 
machine=0xaaaae7e3bee0) at util/session.c:1335
  #15 0x0000aaaaaf667000 in machines__deliver_event 
(machines=0xaaaae7e3bee0, evlist=0xaaaae7e3c550, event=0xffffb1091ec8,
      sample=0xffffe56c8df0, tool=0xffffe56c93d0, file_offset=3784,
      file_path=0xaaaae7e3b540 
"/tmp/perf-test-aslr.J1XB8pvpFy/perf.data2.kernel.FA0Uvd") at util/session.c:1502
  #16 0x0000aaaaaf667538 in perf_session__deliver_event 
(session=0xaaaae7e3bca0, event=0xffffb1091ec8,
      tool=0xffffe56c93d0, file_offset=3784,
      file_path=0xaaaae7e3b540 

"/tmp/perf-test-aslr.J1XB8pvpFy/perf.data2.kernel.FA0Uvd") at util/session.c:1593
#17 0x0000aaaaaf662bbc in ordered_events__deliver_event
(oe=0xaaaae7e3c460, event=0xaaaae7e44740) at util/session.c:134
#18 0x0000aaaaaf672c98 in do_flush (oe=0xaaaae7e3c460,
show_progress=true) at util/ordered-events.c:245
#19 0x0000aaaaaf673048 in __ordered_events__flush (oe=0xaaaae7e3c460,
how=OE_FLUSH__FINAL, timestamp=0)

      at util/ordered-events.c:324
  #20 0x0000aaaaaf673154 in ordered_events__flush (oe=0xaaaae7e3c460, 

how=OE_FLUSH__FINAL) at util/ordered-events.c:342
#21 0x0000aaaaaf669e54 in __perf_session__process_events
(session=0xaaaae7e3bca0) at util/session.c:2508
#22 0x0000aaaaaf66a790 in perf_session__process_events
(session=0xaaaae7e3bca0) at util/session.c:2675
#23 0x0000aaaaaf41f59c in __cmd_script (script=0xffffe56c93d0) at
builtin-script.c:3241
#24 0x0000aaaaaf4242b0 in cmd_script (argc=0, argv=0xffffe56cb370) at
builtin-script.c:4586
#25 0x0000aaaaaf4a03f8 in run_builtin (p=0xaaaaafa14e60
<commands+480>, argc=3, argv=0xffffe56cb370) at perf.c:348
#26 0x0000aaaaaf4a066c in handle_internal_command (argc=3,
argv=0xffffe56cb370) at perf.c:398
#27 0x0000aaaaaf4a0824 in run_argv (argcp=0xffffe56cb1ac,
argv=0xffffe56cb1a0) at perf.c:442
#28 0x0000aaaaaf4a0b4c in main (argc=3, argv=0xffffe56cb370) at
perf.c:549

reviewer
#50 lore raw

Re: [PATCH v6 5/6] perf test: Add inject ASLR test

Quoted 83 lines · James Clark
Quoted 18 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (utilizing a dedicated kernel-intensive VFS
dd workload
   to guarantee continuous timer interrupts sampling flow inside kernel privilege states).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Quoted 9 lines
Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Refactor kernel-space sampling test cases to utilize a dedicated system-call intensive VFS dd workload (kprog) instead of purely userspace-bound tight loops, guaranteeing high-density kernel privilege state sampling streams and eliminating intermittent execution flakiness dropouts.

Hi Ian,

V5 passed on X86, but now I get this test failing about 50% of the time with output like:

Test user register stripping
User registers stripping test [Failed - report parsing differs] Showing first 20 lines of diff:
--- /tmp/perf-test-aslr.ssH9urcfri/report_regs1.clean   2026-05-08 14:14:02.127298207 +0100
+++ /tmp/perf-test-aslr.ssH9urcfri/report_regs2.clean   2026-05-08 14:14:02.129298219 +0100

tmp/perf-test-aslr.ssH9urcfri/report_regs2.clean 2026-05-08 14:14:02.129298219 +0100 renamed from tmp/perf-test-aslr.ssH9urcfri/report_regs1.clean 2026-05-08 14:14:02.127298207 +0100 +1 -1
@@ -30,8 +30,8 @@
       0.02%  perf          ld-linux-x86-64.so.2  [.] mmap64
       0.02%  perf-noploop  [kernel.kallsyms]     [k] kmem_cache_free
       0.02%  perf-noploop  [kernel.kallsyms]     [k] nohz_balancer_kick
-     0.02%  perf-noploop  [kernel.kallsyms]     [k] pvclock_gtod_notify
       0.02%  perf-noploop  [kernel.kallsyms]     [k] try_to_wake_up
+     0.02%  perf-noploop  [kvm]                 [k] pvclock_gtod_notify
       0.02%  perf-noploop  libc.so.6             [.] __cxa_finalize
       0.04%  perf          ld-linux-x86-64.so.2  [.] strcmp
       0.05%  perf          libLLVM-15.so.1       [.] 

llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) ---- end ----

or:

Test user register stripping
User registers stripping test [Failed - report parsing differs] Showing first 20 lines of diff:
--- /tmp/perf-test-aslr.NoDUUXtHyh/report_regs1.clean   2026-05-08 14:05:31.109246491 +0100
+++ /tmp/perf-test-aslr.NoDUUXtHyh/report_regs2.clean   2026-05-08 14:05:31.111246503 +0100

tmp/perf-test-aslr.NoDUUXtHyh/report_regs2.clean 2026-05-08 14:05:31.111246503 +0100 renamed from tmp/perf-test-aslr.NoDUUXtHyh/report_regs1.clean 2026-05-08 14:05:31.109246491 +0100 +0 -0
@@ -2,8 +2,8 @@
       0.01%  perf          [kernel.kallsyms]     [k] 

find_mergeable_anon_vma
      0.01%  perf          [kernel.kallsyms]     [k] finish_fault 0.01%  perf          [kernel.kallsyms]     [k]
pte_offset_map_rw_nolock
+     0.02%  perf          [amdgpu]              [k] amdgpu_device_rreg
      0.02%  perf          [kernel.kallsyms]     [k]
__alloc_frozen_pages_noprof
-     0.02%  perf          [kernel.kallsyms]     [k] amdgpu_device_rreg
      0.02%  perf          [kernel.kallsyms]     [k]
__build_id_parse.isra.0
      0.02%  perf          [kernel.kallsyms]     [k] filemap_get_entry 0.02%  perf          [kernel.kallsyms]     [k] filemap_map_pages
---- end ----

Quoted 1 line

And on Arm I get a hang/infinite loop every time in "Test kernel ASLR remapping". Looks like it could be related to the changes in V6 as I didn't see it on V5:

After around an hour it ended up passing successfully, so not an infinite loop, just very slow.

Then after that, "User registers stripping test" failed the same way as on x86.

Quoted 76 lines

  #0  __read_once_size (size=4, res=0xffffe56c64a0, p=0xaaaaeaedbab8)

       at linux/tools/include/linux/compiler.h:180
   #1  atomic_read (v=0xaaaaeaedbab8) at linux/tools/include/asm- 
generic/atomic-gcc.h:26
   #2  0x0000aaaaaf65cd6c in refcount_read (r=0xaaaaeaedbab8)
       at linux/tools/include/linux/refcount.h:70
   #3  0x0000aaaaaf65d9dc in check_invariants (maps=0xaaaae7e3b480) at 

util/maps.c:114
  #4  0x0000aaaaaf65eef8 in maps__insert (maps=0xaaaae7e3b480,
map=0xaaaaec2ccf10) at util/maps.c:536
  #5  0x0000aaaaaf62a028 in maps__split_kallsyms (kmaps=0xaaaae7e3b480,
dso=0xaaaae7e3f910, delta=1879048192,
      initial_map=0xaaaae7e3fab0) at util/symbol.c:986
  #6  0x0000aaaaaf62b550 in __dso__load_kallsyms (dso=0xaaaae7e3f910,
filename=0xaaaae7e55200 "/proc/kallsyms",
      map=0xaaaae7e3fab0, no_kcore=false) at util/symbol.c:1530 #7  0x0000aaaaaf62b5bc in dso__load_kallsyms (dso=0xaaaae7e3f910,
filename=0xaaaae7e55200 "/proc/kallsyms",
      map=0xaaaae7e3fab0) at util/symbol.c:1536
  #8  0x0000aaaaaf62cbc0 in dso__load_kernel_sym (dso=0xaaaae7e3f910,
map=0xaaaae7e3fab0) at util/symbol.c:2125
  #9  0x0000aaaaaf62bc5c in dso__load (dso=0xaaaae7e3f910,
map=0xaaaae7e3fab0) at util/symbol.c:1721
  #10 0x0000aaaaaf65b98c in map__load (map=0xaaaae7e3fab0) at util/
map.c:351
  #11 0x0000aaaaaf5e43cc in thread__find_map (thread=0xaaaae7e443b0,
cpumode=1 '\001', addr=18446603336494207932,
      al=0xffffe56c8c28) at util/event.c:744
  #12 0x0000aaaaaf5e4810 in machine__resolve (machine=0xaaaae7e3bee0,
al=0xffffe56c8c28, sample=0xffffe56c8df0)

       at util/event.c:818
   #13 0x0000aaaaaf41d850 in process_sample_event (tool=0xffffe56c93d0, 

event=0xffffb1091ec8, sample=0xffffe56c8df0,
      evsel=0xaaaae7e3b580, machine=0xaaaae7e3bee0) at builtin-
script.c:2686
  #14 0x0000aaaaaf6668f4 in evlist__deliver_sample
(evlist=0xaaaae7e3c550, tool=0xffffe56c93d0, event=0xffffb1091ec8,
      sample=0xffffe56c8df0, evsel=0xaaaae7e3b580,
machine=0xaaaae7e3bee0) at util/session.c:1335
  #15 0x0000aaaaaf667000 in machines__deliver_event
(machines=0xaaaae7e3bee0, evlist=0xaaaae7e3c550, event=0xffffb1091ec8,
      sample=0xffffe56c8df0, tool=0xffffe56c93d0, file_offset=3784, file_path=0xaaaae7e3b540 "/tmp/perf-test-aslr.J1XB8pvpFy/
perf.data2.kernel.FA0Uvd") at util/session.c:1502
  #16 0x0000aaaaaf667538 in perf_session__deliver_event
(session=0xaaaae7e3bca0, event=0xffffb1091ec8,
      tool=0xffffe56c93d0, file_offset=3784, file_path=0xaaaae7e3b540 "/tmp/perf-test-aslr.J1XB8pvpFy/
perf.data2.kernel.FA0Uvd") at util/session.c:1593
  #17 0x0000aaaaaf662bbc in ordered_events__deliver_event
(oe=0xaaaae7e3c460, event=0xaaaae7e44740) at util/session.c:134
  #18 0x0000aaaaaf672c98 in do_flush (oe=0xaaaae7e3c460,
show_progress=true) at util/ordered-events.c:245
  #19 0x0000aaaaaf673048 in __ordered_events__flush (oe=0xaaaae7e3c460,
how=OE_FLUSH__FINAL, timestamp=0)

       at util/ordered-events.c:324
   #20 0x0000aaaaaf673154 in ordered_events__flush (oe=0xaaaae7e3c460, 

how=OE_FLUSH__FINAL) at util/ordered-events.c:342
  #21 0x0000aaaaaf669e54 in __perf_session__process_events
(session=0xaaaae7e3bca0) at util/session.c:2508
  #22 0x0000aaaaaf66a790 in perf_session__process_events
(session=0xaaaae7e3bca0) at util/session.c:2675
  #23 0x0000aaaaaf41f59c in __cmd_script (script=0xffffe56c93d0) at
builtin-script.c:3241
  #24 0x0000aaaaaf4242b0 in cmd_script (argc=0, argv=0xffffe56cb370) at
builtin-script.c:4586
  #25 0x0000aaaaaf4a03f8 in run_builtin (p=0xaaaaafa14e60
<commands+480>, argc=3, argv=0xffffe56cb370) at perf.c:348
  #26 0x0000aaaaaf4a066c in handle_internal_command (argc=3,
argv=0xffffe56cb370) at perf.c:398
  #27 0x0000aaaaaf4a0824 in run_argv (argcp=0xffffe56cb1ac,
argv=0xffffe56cb1a0) at perf.c:442
  #28 0x0000aaaaaf4a0b4c in main (argc=3, argv=0xffffe56cb370) at
perf.c:549

maintainer
#51 lore raw

Re: [PATCH v6 5/6] perf test: Add inject ASLR test

In reply to Ian Rogers
Quoted 110 lines · Ian Rogers

Add a new shell test inject_aslr.sh to verify the perf inject --aslr feature. The test covers:
- Basic address remapping for user space samples.
- Pipe mode coverage for perf record piped into perf inject --aslr.
- Callchain address remapping.
- Consistency of perf report output before and after injection.
- Pipe mode report consistency.
- Dropping of samples that leak ASLR info (physical addresses).
- Kernel address remapping (utilizing a dedicated kernel-intensive VFS dd workload to guarantee continuous timer interrupts sampling flow inside kernel privilege states).
- Kernel report consistency with address normalization.

The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams.

Assisted-by Gemini-CLI:Google Gemini 3

---
v6: Refactor kernel-space sampling test cases to utilize a dedicated
system-call intensive VFS dd workload (kprog) instead of purely userspace-bound tight loops, guaranteeing high-density kernel privilege state sampling streams and eliminating intermittent execution flakiness dropouts.

v5: Harden test suite verification pipelines by upgrading report
checks to strict sorted line-by-line diff comparisons to accommodate remapped pointer shifts. Append || true fallback operators to grep-v filtering pipelines to prevent the shell test from spuriously aborting under set -o pipefail on empty inputs, ensuring graceful failure checks trigger correctly.

v4: Reorder set -e/pipefail to prevent temp file leakage in root
directory on unprivileged record failures when run as root. Ensure grep report filters have || true suffixes to avoid aborts under pipefail. Add comprehensive pipe stdout injection attributes validation case.

v3: Harden script with pipefail, SIGPIPE awk pipeline fixes, callchain
empty data asserts, baseline sample verification, and grep report abort protections. Reorder set -e/pipefail to prevent stack leaks in mktemp failures.

v2: Add sum comparison for kernel overhead and 32-bit math corrections. Add
awk with gsub for trailing dots and brackets normalizations. Trap EXIT, prevent race conditions and avoid hardcoded perf binary.

---
 tools/perf/tests/shell/inject_aslr.sh | 460 ++++++++++++++++++++++++++
 1 file changed, 460 insertions(+)
 create mode 100755 tools/perf/tests/shell/inject_aslr.sh
tools/perf/tests/shell/inject_aslr.sh new file +52 -0
new file mode 100755
index 000000000000..6363a0f69d2b
@@ -0,0 +1,460 @@
+#!/bin/bash
+# perf inject --aslr test
+# SPDX-License-Identifier: GPL-2.0
+
+set -e
+set -o pipefail
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/perf_has_symbol.sh
+. "${shelldir}"/lib/perf_has_symbol.sh
+
+sym="noploop"
+
+skip_test_missing_symbol ${sym}
+
+# Create global temp directory
+temp_dir=$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX)
+data="${temp_dir}/perf.data"
+data2="${temp_dir}/perf.data2"
+
+prog="perf test -w noploop"
+[ "$(uname -m)" = "s390x" ] && prog="$prog 3"
+err=0
+kprog="dd if=/dev/zero of=/dev/null bs=1M count=500"
+
+cleanup() {
+  # Check if temp_dir is set and looks sane before removing
+  if [[ "${temp_dir}" =~ ^/tmp/perf-test-aslr\. ]]; then
+    rm -rf "${temp_dir}"
+  fi
+}
+
+trap_cleanup() {
+  cleanup
+  exit 1
+}
+
+trap cleanup EXIT
+trap trap_cleanup TERM INT
+
+get_noploop_addr() {
+  local file=$1
+  perf script -i "$file" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<=NF; i++) {
+        if ($i ~ /noploop\+/) {
+          if (!found) {
+            print $(i-1)
+            found=1
+          }
+        }

tools/perf/tests/shell/inject_aslr.sh line 62

Quoted 10 lines
tools/perf/tests/shell/inject_aslr.sh new file +10 -0
+      }
+    }'
+}
+
+test_basic_aslr() {
+  echo "Test basic ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.basic.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX")

Why not use the globally defined data and data2 here and below?

Thanks,
Namhyung

Quoted 401 lines
tools/perf/tests/shell/inject_aslr.sh new file +398 -0
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -v --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Basic ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Basic ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Basic ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Basic ASLR test [Success]"
+  fi
+}
+
+test_pipe_aslr() {
+  echo "Test pipe mode ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX")
+
+  # Use tee to save the original pipe data for comparison
+  perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject --aslr -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Pipe ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Pipe ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Pipe ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Pipe ASLR test [Success]"
+  fi
+}
+
+test_callchain_aslr() {
+  echo "Test Callchain ASLR remapping"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX")
+
+  perf record -g -e task-clock:u -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  orig_addr=$(get_noploop_addr "${data}")
+  new_addr=$(get_noploop_addr "${data2}")
+
+  echo "Callchain ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Callchain ASLR test [Failed - no noploop samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Callchain ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    # Extract callchain addresses (indented lines starting with hex addresses)
+    orig_callchain=$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+    new_callchain=$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a-f]+/ {print $1}')
+
+    if [ -z "$orig_callchain" ]; then
+      echo "Callchain ASLR test [Failed - no callchain samples in original file]"
+      err=1
+    elif [ -z "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain data was dropped]"
+      err=1
+    elif [ "$orig_callchain" = "$new_callchain" ]; then
+      echo "Callchain ASLR test [Failed - callchain addresses were not remapped]"
+      err=1
+    else
+      echo "Callchain ASLR test [Success]"
+    fi
+  fi
+}
+
+test_report_aslr() {
+  echo "Test perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${data}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${data}" -o "${data2}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_report_aslr() {
+  echo "Test pipe mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  # Use tee to save the original pipe data, then process it with inject -b
+  perf record -e task-clock:u -o - ${prog} | \
+    tee "${data}" | \
+    perf inject -b --aslr -o "${data2}"
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${data2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Report ASLR test [Success]"
+  fi
+}
+
+test_pipe_out_report_aslr() {
+  echo "Test pipe output mode perf report consistency"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+
+  perf record -e task-clock:u -o "${data}" ${prog}
+  perf inject -b -i "${data}" -o "${data_clean}"
+
+  local report1="${temp_dir}/report1"
+  local report2="${temp_dir}/report2"
+  local report1_clean="${temp_dir}/report1.clean"
+  local report2_clean="${temp_dir}/report2.clean"
+  local diff_file="${temp_dir}/diff"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true
+
+  diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_clean}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Pipe Output Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Pipe Output Report ASLR test [Success]"
+  fi
+}
+
+test_dropped_samples() {
+  echo "Test dropped samples (phys-data)"
+  local data
+  data=$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX")
+  local data2
+  data2=$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX")
+
+  # Check if --phys-data is supported by recording a short run
+  if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 > /dev/null 2>&1; then
+    echo "Skipping dropped samples test as --phys-data is not supported"
+    return
+  fi
+
+  perf record -e task-clock:u --phys-data -o "${data}" ${prog}
+  perf inject --aslr -i "${data}" -o "${data2}"
+
+  # Verify that the original file actually contained samples!
+  orig_samples=$(perf script -i "${data}" | wc -l)
+  if [ "$orig_samples" -eq 0 ]; then
+    echo "Dropped samples test [Failed - no samples in original file]"
+    err=1
+  else
+    # Verify that samples are dropped.
+    samples_count=$(perf script -i "${data2}" | wc -l)
+
+    if [ "$samples_count" -gt 0 ]; then
+      echo "Dropped samples test [Failed - samples were not dropped]"
+      err=1
+    else
+      echo "Dropped samples test [Success]"
+    fi
+  fi
+}
+
+test_kernel_aslr() {
+  echo "Test kernel ASLR remapping"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${kprog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel ASLR test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel ASLR test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  perf inject -v --aslr -i "${kdata}" -o "${kdata2}"
+
+  # Check if kernel addresses are remapped.
+  # Find the field that ends with :k: (the event name) and take the next field!
+  orig_addr=$(perf script -i "${kdata}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+  new_addr=$(perf script -i "${kdata2}" | awk '
+    BEGIN { found=0 }
+    {
+      for (i=1; i<NF; i++) {
+        if ($i ~ /:[k]+:?$/) {
+          if (!found) {
+            print $(i+1)
+            found=1
+          }
+        }
+      }
+    }')
+
+  echo "Kernel ASLR: orig_addr=$orig_addr, new_addr=$new_addr"
+
+  if [ -z "$orig_addr" ]; then
+    echo "Kernel ASLR test [Failed - no kernel samples in original file]"
+    err=1
+  elif [ -z "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - could not find remapped address]"
+    err=1
+  elif [ "$orig_addr" = "$new_addr" ]; then
+    echo "Kernel ASLR test [Failed - addresses are not remapped]"
+    err=1
+  else
+    echo "Kernel ASLR test [Success]"
+  fi
+}
+
+test_kernel_report_aslr() {
+  echo "Test kernel perf report consistency"
+  local kdata
+  kdata=$(mktemp "${temp_dir}/perf.data.kernel_report.XXXXXX")
+  local kdata2
+  kdata2=$(mktemp "${temp_dir}/perf.data2.kernel_report.XXXXXX")
+  local data_clean
+  data_clean=$(mktemp "${temp_dir}/perf.data.clean.XXXXXX")
+  local log_file
+  log_file=$(mktemp "${temp_dir}/kernel_report_record.log.XXXXXX")
+
+  # Try to record kernel samples
+  if ! perf record -e task-clock:k -o "${kdata}" ${kprog} > "${log_file}" 2>&1; then
+    echo "Skipping kernel report test as recording failed (maybe no permissions)"
+    return
+  fi
+
+  # Check for warning about kernel map restriction
+  if grep -q "Couldn't record kernel reference relocation symbol" "${log_file}"; then
+    echo "Skipping kernel report test as kernel map could not be recorded (permissions restricted)"
+    return
+  fi
+
+  # Use -b to inject build-ids and force ordered events processing in both
+  perf inject -b -i "${kdata}" -o "${data_clean}"
+  perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}"
+
+  local report1="${temp_dir}/report_kernel1"
+  local report2="${temp_dir}/report_kernel2"
+  local report1_clean="${temp_dir}/report_kernel1.clean"
+  local report2_clean="${temp_dir}/report_kernel2.clean"
+
+  perf report -i "${data_clean}" --stdio > "${report1}"
+  perf report -i "${kdata2}" --stdio > "${report2}"
+
+  # Strip headers and compare lines with percentages
+  grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true
+  grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true
+
+  # Normalize kernel DSOs and addresses in clean reports
+  # This allows kernel modules to be either a module or kernel.kallsyms
+  local report1_norm="${temp_dir}/report_kernel1.norm"
+  local report2_norm="${temp_dir}/report_kernel2.norm"
+  local diff_file="${temp_dir}/diff_kernel"
+
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | \
+    sort > "${report1_norm}" || true
+  grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \
+    awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0); print}' | \
+    sort > "${report2_norm}" || true
+
+  diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true
+
+  if [ ! -s "${report1_norm}" ]; then
+    echo "Kernel Report ASLR test [Failed - no samples captured]"
+    err=1
+  elif [ -s "${diff_file}" ]; then
+    echo "Kernel Report ASLR test [Failed - reports differ]"
+    echo "Showing first 20 lines of diff:"
+    head -n 20 "${diff_file}"
+    err=1
+  else
+    echo "Kernel Report ASLR test [Success]"
+  fi
+}
+
+test_basic_aslr
+test_pipe_aslr
+test_callchain_aslr
+test_report_aslr
+test_pipe_report_aslr
+test_pipe_out_report_aslr
+test_dropped_samples
+test_kernel_aslr
+test_kernel_report_aslr
+
+cleanup
+exit $err
Signature · 1 line
2.54.0.563.g4f69b47b94-goog