lkdtm: Add REPORT_STACK for checking stack offsets
[linux-2.6-microblaze.git] / tools / testing / selftests / lkdtm / stack-entropy.sh
1 #!/bin/sh
2 # SPDX-License-Identifier: GPL-2.0
3 #
4 # Measure kernel stack entropy by sampling via LKDTM's REPORT_STACK test.
5 set -e
6 samples="${1:-1000}"
7
8 # Capture dmesg continuously since it may fill up depending on sample size.
9 log=$(mktemp -t stack-entropy-XXXXXX)
10 dmesg --follow >"$log" & pid=$!
11 report=-1
12 for i in $(seq 1 $samples); do
13         echo "REPORT_STACK" >/sys/kernel/debug/provoke-crash/DIRECT
14         if [ -t 1 ]; then
15                 percent=$(( 100 * $i / $samples ))
16                 if [ "$percent" -ne "$report" ]; then
17                         /bin/echo -en "$percent%\r"
18                         report="$percent"
19                 fi
20         fi
21 done
22 kill "$pid"
23
24 # Count unique offsets since last run.
25 seen=$(tac "$log" | grep -m1 -B"$samples"0 'Starting stack offset' | \
26         grep 'Stack offset' | awk '{print $NF}' | sort | uniq -c | wc -l)
27 bits=$(echo "obase=2; $seen" | bc | wc -L)
28 echo "Bits of stack entropy: $bits"
29 rm -f "$log"
30
31 # We would expect any functional stack randomization to be at least 5 bits.
32 if [ "$bits" -lt 5 ]; then
33         exit 1
34 else
35         exit 0
36 fi