#!/bin/bash

modulename=hide_pid

test_pid() {
	kill -s SIGCONT "$pid" 2>/dev/null
}


if ! addr="$(sudo grep -m 1 sys_call_table /proc/kallsyms | cut -d ' ' -f 1)" || [ -z "$addr" ]; then
	echo failed to find symbol for sys_call_table
	exit 1
fi
echo "sys_call_table address is 0x$addr"

# add some randomness to the script
for _ in $(seq "$(od -An -N1 -i /dev/urandom | tr -d ' ')"); do
	sleep 0
done
sleep 200 &

pid=$!

if [ -z "$pid" ]; then
	echo "Error: pid is null"
	exit 1
fi

# shellcheck disable=SC2009
if ! test_pid; then
	echo "Process cannot be found!"
	exit 1
fi

if ! modprobe $modulename target="$pid" sys_call_table="0x$addr" ; then
	echo "Could not load module $modulename.ko!"
	exit 1
fi

# shellcheck disable=SC2009
if test_pid; then
	echo "Process can still be found!"
	exit 1
fi

if ! jobs | grep -q Running ; then
	echo "Job has been killed!"
	exit 1
fi

sleep 200 &
pid2=$!

if ! kill -s SIGTERM $pid2; then
	echo "Normal behaviour of signal is broken!"
	exit 1
fi

if pgrep $pid2 ; then
	echo "Normal behaviour of signal is broken!"
	exit 1
fi

if ! rmmod $modulename; then
	echo "Fail while unloading module"
	exit 1
fi

# shellcheck disable=SC2009
if ! test_pid; then
	echo "Process cannot be found after removing module!"
	exit 1
fi

if ! jobs | grep -q Running ; then
	echo "Job has been killed!"
	exit 1
fi


echo scan > /sys/kernel/debug/kmemleak
sleep 60
cat /sys/kernel/debug/kmemleak
