#!/usr/bin/zsh

# attempt to start a zsh instance with 'ulimit -v' set to $1
probe() (
    printf "ulimit -v %d ... " $1
    ulimit -v $1 || return $?
    zsh -fc true
)

# exponentially decrease the 'ulimit -v' value until zsh fails to start
mem_limit=$((2**30))
while test 1 -lt $mem_limit && probe $mem_limit; do
    printf "OK\n"
    mem_limit=$(($mem_limit / 2))
done

# increment the 'ulimit -v' value in a loop and check if a signal is raised
probe_limit=$(($mem_limit * 4))
while test $mem_limit -lt $probe_limit; do
    printf "\r"
    mem_limit=$(($mem_limit + 1))
    probe $mem_limit
    ec=$?
    if test 128 -lt $ec; then
        printf "raised signal %d\n" $(($ec - 128))
    fi
done
