#!/bin/sh
# DF-5803 -- build + run harness (executed on the guest via vm.sh run_user/run_root)
set -e

case "$1" in
build)
	cc -O -o /tmp/crashy /tmp/crashy.c
	echo BUILD_OK
	;;
baseline)
	# default kern.corefile: crash must NOT produce the "too long" log
	rm -f /home/maxx/crashy.core /tmp/core.*
	( cd /tmp && ulimit -c unlimited && ./crashy ) >/dev/null 2>&1 || true
	sleep 1
	echo BASELINE_DONE
	;;
setup-long-corefile)
	# root: 1020 'A' + "%N" -> n=1020, +6 ("crashy") = 1026 > MAXPATHLEN(1024)
	# -> overflow branch at the %N case -> log() with unterminated temp
	COREFILE="$(printf 'A%.0s' $(seq 1 1020))%N"
	sysctl -w kern.corefile="$COREFILE"
	sysctl -n kern.corefile | wc -c
	;;
trigger)
	rm -f /home/maxx/*.core /tmp/*.core /home/maxx/crashy*
	( cd /tmp && ulimit -c unlimited && ./crashy ) >/dev/null 2>&1 || true
	sleep 1
	echo TRIGGER_DONE
	;;
restore)
	sysctl -w kern.corefile="%N.core"
	;;
readmsg-user)
	# can an unprivileged user read the message buffer?
	sysctl -n kern.msgbuf 2>&1 | tail -5 || true
	;;
esac
