#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
# Check Arm CoreSight disassembly script completes without errors (exclusive)

# The disassembly script reconstructs ranges of instructions and gives these to objdump to
# decode. objdump doesn't like ranges that go backwards, but these are a good indication
# that decoding has gone wrong either in OpenCSD, Perf or in the range reconstruction in
# the script. Test all 3 parts are working correctly by running the script.

skip_if_no_cs_etm_event() {
	perf list pmu | grep -q 'cs_etm//' && return 0

	# cs_etm event doesn't exist
	return 2
}

skip_if_no_cs_etm_event || exit 2

# Assume an error unless we reach the very end
set -e
glb_err=1

# shellcheck source=lib/setup_python.sh
. "$(dirname "$0")"/../lib/setup_python.sh
$PYTHON -c "import perf" 2>/dev/null || {
	echo "Skipping test, perf python module not found"
	exit 2
}

perfdata_dir=$(mktemp -d /tmp/__perf_test.perf.data.XXXXX)
perfdata=${perfdata_dir}/perf.data
file=$(mktemp /tmp/temporary_file.XXXXX)

cleanup_files()
{
	set +e
	rm -rf ${perfdata_dir}
	rm -f ${file}
	trap - EXIT TERM INT
	exit $glb_err
}

trap cleanup_files EXIT TERM INT

# Ranges start and end on branches, so check for some likely branch instructions
branch_search='[[:space:]](bl|b(\.(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al))?|br|blr|ret|cbz|cbnz|tbz|tbnz|svc|eret)([[:space:]]|$)'

## Test kernel ##
if [ "$(id -u)" == 0 ] && [ -e /proc/kcore ]; then
	echo "Testing kernel disassembly"
	perf record -o ${perfdata} -e cs_etm//k --kcore -Se -m,64K -- touch $file > /dev/null 2>&1
	perf script -i ${perfdata} arm-cs-trace-disasm -- \
		-d --stop-sample=2 -k ${perfdata}/kcore_dir/kcore 2> /dev/null > ${file}
	grep -q -E ${branch_search} ${file}
	echo "Found kernel branches"
else
	# Root and kcore are required for correct kernel decode due to runtime code patching
	echo "No root or kcore, skipping kernel test"
fi

## Test user ##
echo "Testing userspace disassembly"
perf record -o ${perfdata} -e cs_etm//u -Se -m,64K -- touch $file > /dev/null 2>&1
perf script -i ${perfdata} arm-cs-trace-disasm -- \
	-d --stop-sample=2 2> /dev/null > ${file}
grep -q -E ${branch_search} ${file}
echo "Found userspace branches"

glb_err=0