#!/bin/bash
# Feed zsh's read builtin one line of NUL bytes ending in a newline: RUNS times
# with 2^29 NUL bytes (the bug) and RUNS times with one byte fewer (the control),
# printing one summary line for each.
# Usage: ./run.sh [RUNS]   (default 1; each run takes minutes and 1 GiB of memory)
# The shell under test is $ZSH_BIN, or the first zsh on PATH.
# A run counts as a crash when zsh dies from a signal (exit status above
# 128). zsh's stderr is discarded. This script exits 0 either way.
set -u
runs=${1:-1}
zsh_bin=${ZSH_BIN:-zsh}
# read stores a NUL byte as two bytes, so 2^29 of them fill the buffer to 2^30.
limit=536870912

count() {
    local nul_bytes=$1 crash=0 other=0 rc
    for _ in $(seq 1 "$runs"); do
        {
            { head -c "$nul_bytes" /dev/zero; echo; } | "$zsh_bin" -f -c 'read line'
            rc=${PIPESTATUS[1]}
        } 2>/dev/null
        if [ "$rc" -ge 128 ]; then crash=$((crash + 1)); elif [ "$rc" -ne 0 ]; then other=$((other + 1)); fi
    done
    echo "args=[nul_bytes=$nul_bytes] runs=$runs crashes=$crash other_failures=$other"
}

echo "$("$zsh_bin" --version), $(uname -sm)"
count "$limit"
count "$((limit - 1))"
